text:
package com.google.cloud.logging;

import com.google.api.core.ApiFunction;
import com.google.cloud.StringEnumType;
import com.google.cloud.StringEnumValue;
import com.google.common.base.MoreObjects;

import java.io.Serializable;
import java.util.Objects;

/**
 * Objects of this class represent information about the (optional) HTTP request associated with a
 * log entry.
 *
 * @see
 *     Http Request
 */
public final class HttpRequest implements Serializable {

  private static final long serialVersionUID = -274998005454709817L;

  private final RequestMethod requestMethod;
  private final String requestUrl;
  private final Long requestSize;
  private final Integer status;
  private final Long responseSize;
  private final String userAgent;
  private final String remoteIp;
  private final String serverIp;
  private final String referer;
  private final boolean cacheLookup;
  private final boolean cacheHit;
  private final boolean cacheValidatedWithOriginServer;
  private final Long cacheFillBytes;

  /**
   * The HTTP request method.
   */
  public static final class RequestMethod extends StringEnumValue {
    private static final long serialVersionUID = 2403969065179486996L;

    private RequestMethod(String constant) {
      super(constant);
    }

    private static final ApiFunction<String, RequestMethod> CONSTRUCTOR =
        new ApiFunction<String, RequestMethod>() {
          @Override
          public RequestMethod apply(String constant) {
            return new RequestMethod(constant);
          }
        };

    private static final StringEnumType<RequestMethod> type = new StringEnumType(
        RequestMethod.class,
        CONSTRUCTOR);

    public static final RequestMethod GET = type.createAndRegister("GET");
    public static final RequestMethod HEAD = type.createAndRegister("HEAD");
    public static final RequestMethod PUT = type.createAndRegister("PUT");
    public static final RequestMethod POST = type.createAndRegister("POST");

    /**
     * Get the RequestMethod for the given String constant, and throw an exception if the constant is
     * not recognized.
     */
    public static RequestMethod valueOfStrict(String constant) {
      return type.valueOfStrict(constant);
    }

    /**
     * Get the RequestMethod for the given String constant, and allow unrecognized values.
     */
    public static RequestMethod valueOf(String constant) {
      return type.valueOf(constant);
    }

    /**
     * Return the known values for RequestMethod.
     */
    public static RequestMethod[] values() {
      return type.values();
    }
  }

  /**
   * A builder for {@code HttpRequest} objects.
   */
  public static final class Builder {

    private RequestMethod requestMethod;
    private String requestUrl;
    private Long requestSize;
    private Integer status;
    private Long responseSize;
    private String userAgent;
    private String remoteIp;
    private String serverIp;
    private String referer;
    private boolean cacheLookup;
    private boolean cacheHit;
    private boolean cacheValidatedWithOriginServer;
    private Long cacheFillBytes;

    Builder() {}

    Builder(HttpRequest request) {
      this.requestMethod = request.requestMethod;
      this.requestUrl = request.requestUrl;
      this.requestSize = request.requestSize;
      this.status = request.status;
      this.responseSize = request.responseSize;
      this.userAgent = request.userAgent;
      this.remoteIp = request.remoteIp;
      this.serverIp = request.serverIp;
      this.referer = request.referer;
      this.cacheLookup = request.cacheLookup;
      this.cacheHit = request.cacheHit;
      this.cacheValidatedWithOriginServer = request.cacheValidatedWithOriginServer;
      this.cacheFillBytes = request.cacheFillBytes;
    }

    /**
     * Sets the HTTP request method.
     */
    public Builder setRequestMethod(RequestMethod requestMethod) {
      this.requestMethod = requestMethod;
      return this;
    }

    /**
     * Sets the requested URL. Request URL contains the scheme ({@code http}, {@code https}), the
     * host name, the path and the query portion of the URL that was requested. Example:
     * {@code http://example.com/some/info?color=red}.
     */
    public Builder setRequestUrl(String requestUrl) {
      this.requestUrl = requestUrl;
      return this;
    }

    /**
     * Sets the size of the HTTP request message in bytes, including the request headers and the
     * request body.
     */
    public Builder setRequestSize(long requestSize) {
      this.requestSize = requestSize;
      return this;
    }

    /**
     * Sets the response code indicating the status of response.
     */
    public Builder setStatus(int status) {
      this.status = status;
      return this;
    }

    /**
     * Sets the size of the HTTP response message sent back to the client, in bytes, including the
     * response headers and the response body.
     */
    public Builder setResponseSize(long responseSize) {
      this.responseSize = responseSize;
      return this;
    }

    /**
     * Sets the user agent sent by the client. Example:
     * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}.
     */
    public Builder setUserAgent(String userAgent) {
      this.userAgent = userAgent;
      return this;
    }

    /**
     * Sets the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples:
     * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}.
     */
    public Builder setRemoteIp(String remoteIp) {
      this.remoteIp = remoteIp;
      return this;
    }

    /**
     * Sets the IP address (IPv4 or IPv6) of the origin server that the request was sent to.
     * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}.
     */
    public Builder setServerIp(String serverIp) {
      this.serverIp = serverIp;
      return this;
    }

    /**
     * Sets the referer URL of the request, as defined in HTTP/1.1 Header Field Definitions.
     *
     * @see HTTP/1.1 Header Field
     *     Definitions
     */
    public Builder setReferer(String referer) {
      this.referer = referer;
      return this;
    }

    /**
     * Sets whether or not a cache lookup was attempted. If not set, {@code false} is used.
     */
    public Builder setCacheLookup(boolean cacheLookup) {
      this.cacheLookup = cacheLookup;
      return this;
    }

    /**
     * Sets whether or not an entity was served from cache (with or without validation). If not set,
     * {@code false} is used.
     */
    public Builder setCacheHit(boolean cacheHit) {
      this.cacheHit = cacheHit;
      return this;
    }

    /**
     * Sets whether or not the response was validated with the origin server before being served
     * from cache. This field is only meaningful if {@link #setCacheHit(boolean)} is set to
     * {@code true}. If not set, {@code false} is used.
     */
    public Builder setCacheValidatedWithOriginServer(boolean cacheValidatedWithOriginServer) {
      this.cacheValidatedWithOriginServer = cacheValidatedWithOriginServer;
      return this;
    }

    /**
     * Sets the number of HTTP response bytes inserted into cache. Set only when a cache fill was
     * attempted.
     */
    public Builder setCacheFillBytes(long cacheFillBytes) {
      this.cacheFillBytes = cacheFillBytes;
      return this;
    }

    /**
     * Creates a {@code HttpRequest} object for this builder.
     */
    public HttpRequest build() {
      return new HttpRequest(this);
    }
  }

  HttpRequest(Builder builder) {
    this.requestMethod = builder.requestMethod;
    this.requestUrl = builder.requestUrl;
    this.requestSize = builder.requestSize;
    this.status = builder.status;
    this.responseSize = builder.responseSize;
    this.userAgent = builder.userAgent;
    this.remoteIp = builder.remoteIp;
    this.serverIp = builder.serverIp;
    this.referer = builder.referer;
    this.cacheLookup = builder.cacheLookup;
    this.cacheHit = builder.cacheHit;
    this.cacheValidatedWithOriginServer = builder.cacheValidatedWithOriginServer;
    this.cacheFillBytes = builder.cacheFillBytes;
  }

  /**
   * Returns the HTTP request method.
   */
  public RequestMethod getRequestMethod() {
    return requestMethod;
  }

  /**
   * Returns the requested URL. Request URL contains the scheme ({@code http}, {@code https}), the
   * host name, the path and the query portion of the URL that was requested. Example:
   * {@code http://example.com/some/info?color=red}.
   */
  public String getRequestUrl() {
    return requestUrl;
  }

  /**
   * Returns the size of the HTTP request message in bytes, including the request headers and the
   * request body.
   */
  public Long getRequestSize() {
    return requestSize;
  }

  /**
   * Returns the response code indicating the status of response.
   */
  public Integer getStatus() {
    return status;
  }

  /**
   * Returns the size of the HTTP response message sent back to the client, in bytes, including the
   * response headers and the response body.
   */
  public Long getResponseSize() {
    return responseSize;
  }

  /**
   * Returns the user agent sent by the client. Example:
   * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}.
   */
  public String getUserAgent() {
    return userAgent;
  }

  /**
   * Returns the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples:
   * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}.
   */
  public String getRemoteIp() {
    return remoteIp;
  }

  /**
   * Returns the IP address (IPv4 or IPv6) of the origin server that the request was sent to.
   * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}.
   */
  public String getServerIp() {
    return serverIp;
  }

  /**
   * Returns the referer URL of the request, as defined in HTTP/1.1 Header Field Definitions.
   *
   * @see HTTP/1.1 Header Field
   *     Definitions
   */
  public String getReferer() {
    return referer;
  }

  /**
   * Returns whether or not a cache lookup was attempted. If not set, this method returns
   * {@code false}.
   */
  public boolean cacheLookup() {
    return cacheLookup;
  }

  /**
   * Returns whether or not an entity was served from cache (with or without validation). If not
   * set, this method returns {@code false}.
   */
  public boolean cacheHit() {
    return cacheHit;
  }

  /**
   * Returns whether or not the response was validated with the origin server before being served
   * from cache. If not set, this method returns {@code false}. This field is only meaningful if
   * {@link #cacheHit()} is set to {@code true}.
   */
  public boolean cacheValidatedWithOriginServer() {
    return cacheValidatedWithOriginServer;
  }

  /**
   * Returns the number of HTTP response bytes inserted into cache. Set only when a cache fill was
   * attempted.
   */
  public Long getCacheFillBytes() {
    return cacheFillBytes;
  }

  @Override
  public int hashCode() {
    return Objects.hash(requestMethod, requestUrl, requestSize, status, responseSize, userAgent,
        serverIp, cacheLookup, cacheFillBytes, remoteIp, referer, cacheHit,
        cacheValidatedWithOriginServer);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("requestMethod", requestMethod)
        .add("requestUrl", requestUrl)
        .add("requestSize", requestSize)
        .add("status", status)
        .add("responseSize", responseSize)
        .add("userAgent", userAgent)
        .add("remoteIp", remoteIp)
        .add("serverIp", serverIp)
        .add("referer", referer)
        .add("cacheLookup", cacheLookup)
        .add("cacheHit", cacheHit)
        .add("cacheValidatedWithOriginServer", cacheValidatedWithOriginServer)
        .add("cacheFillBytes", cacheFillBytes)
        .toString();
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof HttpRequest)) {
      return false;
    }
    HttpRequest other = (HttpRequest) obj;
    return Objects.equals(requestMethod, other.requestMethod)
        && Objects.equals(requestUrl, other.requestUrl)
        && Objects.equals(requestSize, other.requestSize)
        && Objects.equals(status, other.status)
        && Objects.equals(responseSize, other.responseSize)
        && Objects.equals(userAgent, other.userAgent)
        && Objects.equals(remoteIp, other.remoteIp)
        && Objects.equals(serverIp, other.serverIp)
        && Objects.equals(referer, other.referer)
        && cacheLookup == other.cacheLookup
        && cacheHit == other.cacheHit
        && cacheValidatedWithOriginServer == other.cacheValidatedWithOriginServer
        && Objects.equals(cacheFillBytes, other.cacheFillBytes);
  }

  /**
   * Returns a builder for this object.
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  com.google.logging.type.HttpRequest toPb() {
    com.google.logging.type.HttpRequest.Builder builder =
        com.google.logging.type.HttpRequest.newBuilder();
    if (requestMethod != null) {
      builder.setRequestMethod(requestMethod.name());
    }
    if (requestUrl != null) {
      builder.setRequestUrl(requestUrl);
    }
    if (requestSize != null) {
      builder.setRequestSize(requestSize);
    }
    if (status != null) {
      builder.setStatus(status);
    }
    if (responseSize != null) {
      builder.setResponseSize(responseSize);
    }
    if (userAgent != null) {
      builder.setUserAgent(userAgent);
    }
    if (remoteIp != null) {
      builder.setRemoteIp(remoteIp);
    }
    if (serverIp != null) {
      builder.setServerIp(serverIp);
    }
    if (referer != null) {
      builder.setReferer(referer);
    }
    builder.setCacheLookup(cacheLookup);
    builder.setCacheHit(cacheHit);
    builder.setCacheValidatedWithOriginServer(cacheValidatedWithOriginServer);
    if (cacheFillBytes != null) {
      builder.setCacheFillBytes(cacheFillBytes);
    }
    return builder.build();
  }

  /**
   * Returns a builder for {@code HttpRequest} objects.
   */
  public static Builder newBuilder() {
    return new Builder();
  }

  static HttpRequest fromPb(com.google.logging.type.HttpRequest requestPb) {
    Builder builder = newBuilder();
    if (requestPb.getRequestMethod() != null && !requestPb.getRequestMethod().equals("")) {
      builder.setRequestMethod(RequestMethod.valueOf(requestPb.getRequestMethod()));
    }
    if (requestPb.getRequestUrl() != null && !requestPb.getRequestUrl().equals("")) {
      builder.setRequestUrl(requestPb.getRequestUrl());
    }
    if (requestPb.getRequestSize() != 0L) {
      builder.setRequestSize(requestPb.getRequestSize());
    }
    if (requestPb.getStatus() != 0L) {
      builder.setStatus(requestPb.getStatus());
    }
    if (requestPb.getResponseSize() != 0L) {
      builder.setResponseSize(requestPb.getResponseSize());
    }
    if (requestPb.getUserAgent() != null && !requestPb.getRequestUrl().equals("")) {
      builder.setUserAgent(requestPb.getUserAgent());
    }
    if (requestPb.getServerIp() != null && !requestPb.getServerIp().equals("")) {
      builder.setServerIp(requestPb.getServerIp());
    }
    if (requestPb.getRemoteIp() != null && !requestPb.getRemoteIp().equals("")) {
      builder.setRemoteIp(requestPb.getRemoteIp());
    }
    if (requestPb.getReferer() != null && !requestPb.getReferer().equals("")) {
      builder.setReferer(requestPb.getReferer());
    }
    builder.setCacheLookup(requestPb.getCacheLookup());
    builder.setCacheHit(requestPb.getCacheHit());
    builder.setCacheValidatedWithOriginServer(requestPb.getCacheValidatedWithOriginServer());
    if (requestPb.getCacheFillBytes() != 0L) {
      builder.setCacheFillBytes(requestPb.getCacheFillBytes());
    }
    return builder.build();
  }
}


text:
package org.ebookdroid.core;

import org.ebookdroid.core.models.ZoomModel;

public class PageTreeLevel {

    public static final int ZOOM_THRESHOLD = 2;

    public static final PageTreeLevel ROOT;
    public static final PageTreeLevel[] LEVELS;
    public static final int NODES;

    static {
        int count = 1 + (int) Math.ceil(Math.log(ZoomModel.MAX_ZOOM) / Math.log(2));
        ROOT = new PageTreeLevel(count);
        LEVELS = new PageTreeLevel[count];
        LEVELS[0] = ROOT;
        int end = ROOT.end;
        int index = 1;
        for (PageTreeLevel l = ROOT.next; l != null; l = l.next) {
            LEVELS[index++] = l;
            end = l.end;
        }
        NODES = end;
    }

    public final int level;
    public final float zoom;
    public final int start;
    public final int end;

    public final PageTreeLevel prev;
    public final PageTreeLevel next;

    private PageTreeLevel(int count) {
        this.level = 0;
        this.zoom = ZoomModel.MIN_ZOOM;
        this.start = 0;
        this.end = 1;

        this.prev = null;
        this.next = new PageTreeLevel(this, count - 1);
    }

    private PageTreeLevel(final PageTreeLevel parent, int count) {
        this.level = parent.level + 1;
        this.zoom = parent.zoom * ZOOM_THRESHOLD;
        this.start = parent.end;
        this.end = this.start + (int) Math.pow(PageTree.splitMasks.length, this.level);

        this.prev = parent;
        this.next = count > 1 ? new PageTreeLevel(this, count - 1) : null;
    }

    public static PageTreeLevel getLevel(float zoom) {
        for (int i = 1; i < LEVELS.length; i++) {
            if (zoom < LEVELS[i].zoom) {
                return LEVELS[i - 1];
            } else if (zoom == LEVELS[i].zoom) {
                return LEVELS[i];
            }
        }
        return LEVELS[LEVELS.length - 1];
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation MIHRSAPublicKey (Internal)

- (instancetype)initWithRSA:(RSA *)rsa
{
    self = [super init];
    if (self) {
        CRYPTO_add(&rsa->references, 1, CRYPTO_LOCK_RSA);
        _rsa = rsa;
    }

    return self;
}

@end


text:
DO
$body$
BEGIN
	IF NOT EXISTS (
    	SELECT 1 FROM pg_type JOIN pg_namespace ON typnamespace=pg_namespace.oid WHERE nspname='pwaf' AND typname='g_seq'
    ) THEN

		CREATE SEQUENCE pwaf.g_seq
		  INCREMENT 1
		  MINVALUE 1
		  MAXVALUE 9223372036854775807
		  START 1000000
		  CACHE 1;

   	END IF;
END
$body$
;

ALTER SEQUENCE pwaf.g_seq OWNER TO pwaf;
--


text:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>java-analytics-dashboard</application>
    <version>1</version>
    <threadsafe>true</threadsafe>

    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
    </system-properties>
</appengine-web-app>


text:
''' filestatshandler.py '''
import json
import os
import stat
import tornado.web

from heron.shell.src.python import utils

class FileStatsHandler(tornado.web.RequestHandler):
  """
  Get the file stats in JSON format given the path.
  """
  async def get(self, path):
    ''' get method '''
    path = tornado.escape.url_unescape(path)
    if not path:
      path = "."

    # User should not be able to access anything outside
    # of the dir that heron-shell is running in. This ensures
    # sandboxing. So we don't allow absolute paths and parent
    # accessing.
    if not utils.check_path(path):
      self.set_status(403)
      await self.finish("Only relative paths are allowed")
      return

    listing = utils.get_listing(path)
    file_stats = {}
    for fn in listing:
      try:
        is_dir = False
        formatted_stat = utils.format_prefix(fn, utils.get_stat(path, fn))
        if stat.S_ISDIR(utils.get_stat(path, fn).st_mode):
          is_dir = True
        file_stats[fn] = {
            "formatted_stat": formatted_stat,
            "is_dir": is_dir,
            "path": tornado.escape.url_escape(os.path.join(path, fn)),
        }
        if fn == "..":
          path_fragments = path.split("/")
          if not path_fragments:
            file_stats[fn]["path"] = "."
          else:
            file_stats[fn]["path"] = tornado.escape.url_escape("/".join(path_fragments[:-1]))
      except:
        continue
    await self.finish(json.dumps(file_stats))


text:
namespace drift
{
	namespace schemy
	{
		struct environment
		{
			environment() = default;

			environment(environment* parent) : parent(parent) { }
			environment(environment&&);
			std::unordered_map<string, variant_ptr> symbols;
			std::unordered_map<string, variant_ptr> user_fn;
			environment* parent = nullptr;
			variant_ptr& lookup(const string& name) {
				try {
					variant_ptr& sym = symbols.at(name);
					return sym;
				} catch(std::out_of_range&) { }
				try {
					return user_fn.at(name);
				} catch(std::out_of_range&) { }
				//auto sym = symbols.find(name);
				//if(sym != symbols.end())
				//	return sym->second;
				//auto fn = user_fn.find(name);
				//if(fn != user_fn.end())
				//	return fn->second; //return user_fn.at(name); //(*fn).second;
				if(parent != nullptr)
					return parent->lookup(name);
				throw std::out_of_range(name + " evironment could not find identifier.");
			}
			void add_function(const string& n, function f);
		};
		environment std_env();
		struct method
		{
			method() = default;
			method(method&&);
			environment* env;
			std::vector<variant_ptr> expressions;

		};
	}
}


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

// script to destroy enemies once they are defeated

public class DefeatEnemy : MonoBehaviour {

    EnemyHealthController enemy;

	// Use this for initialization
	void Start () {
        enemy = GetComponentInParent<EnemyHealthController>();
    }

    // Update is called once per frame
    void Update () {
		if (enemy.enemyDefeated)
        {
            Destroy(gameObject);
        }
	}
}


text:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.uicd.backend.recorder.coverter.roboscript;

import com.google.uicd.backend.core.constants.StrategyType;
import com.google.uicd.backend.core.uicdactions.ClickAction;
import com.google.uicd.backend.core.utils.ImageUtil;
import com.google.uicd.backend.recorder.coverter.ActionConverter;

/** Implements the convert logic for click action to RoboScript */
public class ClickActionRoboConverter implements ActionConverter<ClickAction, RoboConvertContext> {
  private static final int HOST_SCREEN_WIDTH = 360;
  private static final int HOST_SCREEN_HEIGHT = 640;

  @Override
  public boolean canConvert(ClickAction action, RoboConvertContext context) {
    if (action.isRawXYClick() || action.isByElement()) {
      return true;
    }
    context.appendToDetailsLog("Click based NodeContext, can not convert. ");
    return false;
  }

  @Override
  public void convert(ClickAction action, RoboConvertContext context) {
    if (!canConvert(action, context)) {
      return;
    }
    RoboAction roboAction = new RoboAction();
    roboAction.eventType = RoboEventType.VIEW_CLICKED;
    RoboElementDescriptor roboElementDescriptor = new RoboElementDescriptor();
    if (action.isByElement()) {
      if (action.getStrategy() == StrategyType.RESOURCEID) {
        roboElementDescriptor.resourceId = action.getSelector();
        roboAction.elementDescriptors.add(roboElementDescriptor);
      } else if (action.getStrategy() == StrategyType.TEXT) {
        roboElementDescriptor.text = action.getSelector();
        roboAction.elementDescriptors.add(roboElementDescriptor);
      } else if (action.getStrategy() == StrategyType.XPATH) {
        context.appendToDetailsLog("Not support xpath, can not convert. ");
        return;
      }
    } else if (action.isRawXYClick()) {
      roboAction.pointTapXCoordinate =
          ImageUtil.scaleToTargetPx(
              (int) action.getNodeContext().getClickedPos().x,
              HOST_SCREEN_WIDTH,
              context.deviceWidth);
      roboAction.pointTapYCoordinate =
          ImageUtil.scaleToTargetPx(
              (int) action.getNodeContext().getClickedPos().y,
              HOST_SCREEN_HEIGHT,
              context.deviceHeight);
    }
    context.addRoboAcction(roboAction);
    return;
  }
}


text:
package gwt.material.design.addins.client.combobox;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;

/**
 * Client Bundle for ComboBox component
 *
 * @author kevzlou7979
 */
public interface MaterialComboBoxDebugClientBundle extends ClientBundle {

    MaterialComboBoxDebugClientBundle INSTANCE = GWT.create(MaterialComboBoxDebugClientBundle.class);

    @Source("resources/js/select2.js")
    TextResource select2DebugJs();

    @Source("resources/css/select2.css")
    TextResource select2DebugCss();

    @Source("resources/css/select2-dark.css")
    TextResource select2DarkDebugCss();
}


text:
require_relative 'node'

class Build < Node

end


text:
package org.apache.hadoop.hive.serde2;

import junit.framework.TestCase;
import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;

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

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestSerdeWithFieldComments extends TestCase {

  private StructField mockedStructField(String name, String oiTypeName,
                                        String comment) {
    StructField m = mock(StructField.class);
    when(m.getFieldName()).thenReturn(name);

    ObjectInspector oi = mock(ObjectInspector.class);
    when(oi.getTypeName()).thenReturn(oiTypeName);

    when(m.getFieldObjectInspector()).thenReturn(oi);
    when(m.getFieldComment()).thenReturn(comment);

    return m;
  }

  public void testFieldComments() throws MetaException, SerDeException {
    StructObjectInspector mockSOI = mock(StructObjectInspector.class);
    when(mockSOI.getCategory()).thenReturn(ObjectInspector.Category.STRUCT);
    List fieldRefs = new ArrayList<StructField>();
    // Add field with a comment...
    fieldRefs.add(mockedStructField("first", "type name 1", "this is a comment"));
    // ... and one without
    fieldRefs.add(mockedStructField("second", "type name 2", null));

    when(mockSOI.getAllStructFieldRefs()).thenReturn(fieldRefs);

    Deserializer mockDe = mock(Deserializer.class);
    when(mockDe.getObjectInspector()).thenReturn(mockSOI);
    List<FieldSchema> result =
        HiveMetaStoreUtils.getFieldsFromDeserializer("testTable", mockDe);

    assertEquals(2, result.size());
    assertEquals("first", result.get(0).getName());
    assertEquals("this is a comment", result.get(0).getComment());
    assertEquals("second", result.get(1).getName());
    assertEquals("from deserializer", result.get(1).getComment());
  }
}


text:
ossimElevationDatabaseFactory* ossimElevationDatabaseFactory::m_instance = 0;
ossimElevationDatabaseFactory* ossimElevationDatabaseFactory::instance()
{
   if(!m_instance)
   {
      m_instance = new ossimElevationDatabaseFactory();
   }

   return m_instance;
}

ossimElevationDatabase* ossimElevationDatabaseFactory::createDatabase(
   const ossimString& typeName )const
{
   if((typeName == STATIC_TYPE_NAME(ossimDtedElevationDatabase)) ||
      (typeName == "dted")||
      (typeName == "dted_directory"))
   {
      return new ossimDtedElevationDatabase();
   }
   else if((typeName == STATIC_TYPE_NAME(ossimSrtmElevationDatabase)) ||
           (typeName == "srtm")||
           (typeName == "srtm_directory"))
   {
      return new ossimSrtmElevationDatabase();
   }
   else if((typeName == STATIC_TYPE_NAME(ossimGeneralRasterElevationDatabase)) ||
           (typeName == "general_raster")||
           (typeName == "general_raster_directory"))
   {
      return new ossimGeneralRasterElevationDatabase();
   }
   else if( (typeName == "ossimImageElevationDatabase") ||
            (typeName == "image_directory"))
   {
      return new ossimImageElevationDatabase();
   }

   return 0;
}

ossimElevationDatabase* ossimElevationDatabaseFactory::createDatabase(const ossimKeywordlist& kwl,
                                                                      const char* prefix)const
{
   ossimRefPtr<ossimElevationDatabase> result = 0;
   ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW);
   if(!type.empty())
   {
      result = createDatabase(type);
      if(result.valid())
      {
         if(!result->loadState(kwl, prefix))
         {
            result = 0;
         }
      }
   }

   return result.release();
}

ossimElevationDatabase* ossimElevationDatabaseFactory::open(const ossimString& connectionString)const
{
   ossimRefPtr<ossimElevationDatabase> result = 0;
   do
   {
      result = new ossimDtedElevationDatabase();
      if (result->open(connectionString))
         break;

      result = new ossimSrtmElevationDatabase;
      if (result->open(connectionString))
         break;

      result = new ossimGeneralRasterElevationDatabase;
      if (result->open(connectionString))
         break;

      result = new ossimImageElevationDatabase;
      if (result->open(connectionString))
         break;

      // This method will only open individual image files for use as dems. It will not utilize the
      // file walker to search over directories:
      ossimFilename filename (connectionString);
      if (filename.isFile())
      {
         result = new ossimImageElevationDatabase;
         if (result->open(connectionString))
            break;
      }

      result = 0;
   } while (0);

   return result.release();
}

void ossimElevationDatabaseFactory::getTypeNameList(std::vector<ossimString>& typeList)const
{
   typeList.push_back(STATIC_TYPE_NAME(ossimDtedElevationDatabase));
   typeList.push_back(STATIC_TYPE_NAME(ossimSrtmElevationDatabase));
   typeList.push_back(STATIC_TYPE_NAME(ossimGeneralRasterElevationDatabase));
   typeList.push_back(STATIC_TYPE_NAME(ossimImageElevationDatabase));
}


text:
layout: page
title: Moss Industries Show
date: 2016-05-24
author: Daniel Orozco
tags: weekly links, java
status: published
summary: Aliquam consectetur varius risus, vitae.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 08/24/2018
  endDate: 08/26/2018
  ctyhocn: CUUMXHX
  groupCode: MIS
published: true
---
Etiam ultricies quis eros at tristique. Suspendisse metus risus, tristique sed hendrerit vel, aliquet non justo. Suspendisse vel rutrum eros. Nunc finibus ullamcorper ultrices. Phasellus mollis feugiat sem vel volutpat. Etiam eget tempor turpis. Integer mauris justo, varius ut lacinia non, tincidunt non lacus. Duis tincidunt tellus in sapien pulvinar, at pretium ipsum ornare. Quisque laoreet dui ut suscipit consequat. Aliquam ullamcorper neque sapien, in porta sapien semper vel.

* Aliquam eu lorem eu justo posuere condimentum
* Cras nec urna nec ex condimentum placerat sed vitae est
* Morbi luctus lorem a quam fermentum dignissim
* Aliquam hendrerit ligula id dictum tristique.

Cras eleifend diam turpis, vel fermentum nibh ultricies at. Nam dapibus pharetra auctor. Nulla facilisi. Aenean gravida convallis eleifend. Curabitur sed elementum dolor. Proin consequat, ligula nec sodales pharetra, libero sapien sollicitudin leo, consequat rutrum nisl enim vel justo. Nulla facilisi. Suspendisse nibh sem, rutrum in tincidunt sed, consequat egestas sem. Ut ut imperdiet metus, et maximus elit. Aenean ut justo posuere, condimentum ex a, tincidunt sem.


text:
package org.inventivetalent.nbt;

import com.google.gson.JsonElement;
import org.inventivetalent.nbt.stream.NBTInputStream;
import org.inventivetalent.nbt.stream.NBTOutputStream;
import org.inventivetalent.reflection.resolver.minecraft.NMSClassResolver;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import static org.inventivetalent.nbt.TagID.*;

public abstract class NBTTag<V> {

	public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver();

	private final String name;

	public NBTTag(String name) {
		this.name = name;
	}

	public NBTTag(String name, Object nmsTag) {
		this.name = name;

	}

	public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException {
		return forType(type).newInstance();
	}

	public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
		return forType(type).getConstructor(String.class).newInstance(name);
	}

	public static Class<? extends NBTTag> forType(int type) {
		switch (type) {
			case TAG_BYTE_ARRAY:
				return ByteArrayTag.class;
			case TAG_BYTE:
				return ByteTag.class;
			case TAG_COMPOUND:
				return CompoundTag.class;
			case TAG_DOUBLE:
				return DoubleTag.class;
			case TAG_END:
				return EndTag.class;
			case TAG_FLOAT:
				return FloatTag.class;
			case TAG_INT_ARRAY:
				return IntArrayTag.class;
			case TAG_INT:
				return IntTag.class;
			case TAG_LIST:
				return ListTag.class;
			case TAG_LONG:
				return LongTag.class;
			case TAG_SHORT:
				return ShortTag.class;
			case TAG_STRING:
				return StringTag.class;
			case TAG_LONG_ARRAY:
				return LongArrayTag.class;
			default:
				throw new IllegalArgumentException("Invalid NBTTag type " + type);
		}
	}

	public String getName() {
		return name;
	}

	public abstract V getValue();

	public abstract void setValue(V v);

	// getAs methods

	public Number getAsNumber() {
		return 0;
	}

	public byte getAsByte() {
		return getAsNumber().byteValue();
	}

	public short getAsShort() {
		return getAsNumber().shortValue();
	}

	public int getAsInt() {
		return getAsNumber().intValue();
	}

	public long getAsLong() {
		return getAsNumber().longValue();
	}

	public float getAsFloat() {
		return getAsNumber().floatValue();
	}

	public double getAsDouble() {
		return getAsNumber().doubleValue();
	}

	public String getAsString() {
		return String.valueOf(getValue());
	}

	// /getAs methods

	public abstract JsonElement asJson();

	public abstract int getTypeId();

	public abstract String getTypeName();

	public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
	}

	public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
	}

	public String getNMSClass() {
		return "NBTBase";
	}

	public NBTTag fromNMS(Object nms) throws ReflectiveOperationException {
		Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass());
		Field field = clazz.getDeclaredField("data");
		field.setAccessible(true);
		setValue((V) field.get(nms));
		return this;
	}

	public Object toNMS() throws ReflectiveOperationException {
		Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass());
		Constructor constructor = null;
		for (Constructor constr : clazz.getConstructors()) {
			if (constr.getParameterTypes().length == 1) {
				constructor = constr;
				break;
			}
		}
		if (constructor == null) { return null; }
		return constructor.newInstance(getValue());
	}

	@Override
	public String toString() {
		return getTypeName() + "(" + getName() + "): " + getValue();
	}
}


text:
const debug = (process.env.NODE_ENV !== 'production');
const path = require('path');
const webpack = require('webpack');
const devPlugins = [];
const prodPlugins = [
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({
    mangle: false,
    sourcemap: false,
  }),
];

module.exports = {
  context: __dirname,
  devtool: debug ? 'inline-sourcemap' : null,
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'assets/'),
    publicPath: '/assets/',
    filename: debug ? 'app.js' : 'app.min.js',
  },
  devServer: {
    historyApiFallback: true,
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: [
            'react',
            'es2015',
            'stage-0',
          ],
          plugins: [
            'react-html-attrs',
            'transform-class-properties',
            'transform-decorators-legacy',
          ],
        },
      },
    ],
  },
  plugins: debug ? devPlugins : prodPlugins,
};


text:
package org.pac4j.saml.client;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.List;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.NotImplementedException;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.junit.Test;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration;
import org.pac4j.core.client.RedirectAction;
import org.pac4j.core.context.MockWebContext;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.util.TestsConstants;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public final class RedirectSaml2ClientIT extends Saml2ClientIT implements TestsConstants {

    @Test
    public void testCustomSpEntityIdForRedirectBinding() throws Exception {
        Saml2Client client = getClient();
        client.setSpEntityId("http://localhost:8080/callback");
        WebContext context = MockWebContext.create();
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(getInflatedAuthnRequest(action.getLocation())
                .contains(
                        "<saml2:Issuer xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">http://localhost:8080/callback</saml2:Issuer>"));
    }

    @Test
    public void testForceAuthIsSetForRedirectBinding() throws Exception {
        Saml2Client client = getClient();
        client.setForceAuth(true);
        WebContext context = MockWebContext.create();
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(getInflatedAuthnRequest(action.getLocation()).contains("ForceAuthn=\"true\""));
    }

    @Test
    public void testSetComparisonTypeWithRedirectBinding() throws Exception {
        Saml2Client client = getClient();
        client.setComparisonType(AuthnContextComparisonTypeEnumeration.EXACT.toString());
        WebContext context = MockWebContext.create();
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(getInflatedAuthnRequest(action.getLocation()).contains("Comparison=\"exact\""));
    }

    @Test
    public void testNameIdPolicyFormat() throws Exception {
        Saml2Client client = getClient();
        client.setNameIdPolicyFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");
        WebContext context = MockWebContext.create();
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(getInflatedAuthnRequest(action.getLocation())
                .contains(
                        "<saml2p:NameIDPolicy AllowCreate=\"true\" Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"/></saml2p:AuthnRequest>"));
    }

    @Test
    public void testAuthnContextClassRef() throws Exception {
        Saml2Client client = getClient();
        client.setComparisonType(AuthnContextComparisonTypeEnumeration.EXACT.toString());
        client.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
        WebContext context = MockWebContext.create();
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(getInflatedAuthnRequest(action.getLocation())
                .contains(
                        "<saml2p:RequestedAuthnContext Comparison=\"exact\"><saml2:AuthnContextClassRef xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>"));
    }

    @Test
    public void testRelayState() throws Exception {
        Saml2Client client = getClient();
        WebContext context = MockWebContext.create();
        context.setSessionAttribute(Saml2Client.SAML_RELAY_STATE_ATTRIBUTE, "relayState");
        RedirectAction action = client.getRedirectAction(context, true);
        assertTrue(action.getLocation().contains("RelayState=relayState"));
    }

    @Override
    protected String getCallbackUrl() {
        return "http://localhost:8080/callback?client_name=Saml2Client";
    }

    @Override
    protected String getDestinationBindingType() {
        return SAMLConstants.SAML2_REDIRECT_BINDING_URI;
    }

    @Override
    protected String getCallbackUrl(WebClient webClient, HtmlPage authorizationPage) throws Exception {
        throw new NotImplementedException("No callback url in SAML2 Redirect Binding");
    }

    private String getInflatedAuthnRequest(String location) throws Exception {
        List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(location), "UTF-8");
        Inflater inflater = new Inflater(true);
        byte[] decodedRequest = Base64.decodeBase64(pairs.get(0).getValue());
        ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
        InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        return reader.readLine();
    }
}


text:
"""The tests for UVC camera module."""
import socket
import unittest
from unittest import mock

import requests
from uvcclient import camera
from uvcclient import nvr

from homeassistant.components.camera import uvc

class TestUVCSetup(unittest.TestCase):
    """Test the UVC camera platform."""

    @mock.patch('uvcclient.nvr.UVCRemote')
    @mock.patch.object(uvc, 'UnifiVideoCamera')
    def test_setup_full_config(self, mock_uvc, mock_remote):
        """"Test the setup with full configuration."""
        config = {
            'nvr': 'foo',
            'port': 123,
            'key': 'secret',
        }
        fake_cameras = [
            {'uuid': 'one', 'name': 'Front', 'id': 'id1'},
            {'uuid': 'two', 'name': 'Back', 'id': 'id2'},
            {'uuid': 'three', 'name': 'Old AirCam', 'id': 'id3'},
        ]

        def fake_get_camera(uuid):
            """"Create a fake camera."""
            if uuid == 'id3':
                return {'model': 'airCam'}
            else:
                return {'model': 'UVC'}

        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        mock_remote.return_value.index.return_value = fake_cameras
        mock_remote.return_value.get_camera.side_effect = fake_get_camera
        mock_remote.return_value.server_version = (3, 2, 0)
        self.assertTrue(uvc.setup_platform(hass, config, add_devices))
        mock_remote.assert_called_once_with('foo', 123, 'secret')
        add_devices.assert_called_once_with([
            mock_uvc.return_value, mock_uvc.return_value])
        mock_uvc.assert_has_calls([
            mock.call(mock_remote.return_value, 'id1', 'Front'),
            mock.call(mock_remote.return_value, 'id2', 'Back'),
        ])

    @mock.patch('uvcclient.nvr.UVCRemote')
    @mock.patch.object(uvc, 'UnifiVideoCamera')
    def test_setup_partial_config(self, mock_uvc, mock_remote):
        """"Test the setup with partial configuration."""
        config = {
            'nvr': 'foo',
            'key': 'secret',
        }
        fake_cameras = [
            {'uuid': 'one', 'name': 'Front', 'id': 'id1'},
            {'uuid': 'two', 'name': 'Back', 'id': 'id2'},
        ]
        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        mock_remote.return_value.index.return_value = fake_cameras
        mock_remote.return_value.get_camera.return_value = {'model': 'UVC'}
        mock_remote.return_value.server_version = (3, 2, 0)
        self.assertTrue(uvc.setup_platform(hass, config, add_devices))
        mock_remote.assert_called_once_with('foo', 7080, 'secret')
        add_devices.assert_called_once_with([
            mock_uvc.return_value, mock_uvc.return_value])
        mock_uvc.assert_has_calls([
            mock.call(mock_remote.return_value, 'id1', 'Front'),
            mock.call(mock_remote.return_value, 'id2', 'Back'),
        ])

    @mock.patch('uvcclient.nvr.UVCRemote')
    @mock.patch.object(uvc, 'UnifiVideoCamera')
    def test_setup_partial_config_v31x(self, mock_uvc, mock_remote):
        """Test the setup with a v3.1.x server."""
        config = {
            'nvr': 'foo',
            'key': 'secret',
        }
        fake_cameras = [
            {'uuid': 'one', 'name': 'Front', 'id': 'id1'},
            {'uuid': 'two', 'name': 'Back', 'id': 'id2'},
        ]
        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        mock_remote.return_value.index.return_value = fake_cameras
        mock_remote.return_value.get_camera.return_value = {'model': 'UVC'}
        mock_remote.return_value.server_version = (3, 1, 3)
        self.assertTrue(uvc.setup_platform(hass, config, add_devices))
        mock_remote.assert_called_once_with('foo', 7080, 'secret')
        add_devices.assert_called_once_with([
            mock_uvc.return_value, mock_uvc.return_value])
        mock_uvc.assert_has_calls([
            mock.call(mock_remote.return_value, 'one', 'Front'),
            mock.call(mock_remote.return_value, 'two', 'Back'),
        ])

    def test_setup_incomplete_config(self):
        """"Test the setup with incomplete configuration."""
        self.assertFalse(uvc.setup_platform(
            None, {'nvr': 'foo'}, None))
        self.assertFalse(uvc.setup_platform(
            None, {'key': 'secret'}, None))
        self.assertFalse(uvc.setup_platform(
            None, {'port': 'invalid'}, None))

    @mock.patch('uvcclient.nvr.UVCRemote')
    def test_setup_nvr_errors(self, mock_remote):
        """"Test for NVR errors."""
        errors = [nvr.NotAuthorized, nvr.NvrError,
                  requests.exceptions.ConnectionError]
        config = {
            'nvr': 'foo',
            'key': 'secret',
        }
        for error in errors:
            mock_remote.return_value.index.side_effect = error
            self.assertFalse(uvc.setup_platform(None, config, None))

class TestUVC(unittest.TestCase):
    """Test class for UVC."""

    def setup_method(self, method):
        """"Setup the mock camera."""
        self.nvr = mock.MagicMock()
        self.uuid = 'uuid'
        self.name = 'name'
        self.uvc = uvc.UnifiVideoCamera(self.nvr, self.uuid, self.name)
        self.nvr.get_camera.return_value = {
            'model': 'UVC Fake',
            'recordingSettings': {
                'fullTimeRecordEnabled': True,
            },
            'host': 'host-a',
            'internalHost': 'host-b',
            'username': 'admin',
        }
        self.nvr.server_version = (3, 2, 0)

    def test_properties(self):
        """"Test the properties."""
        self.assertEqual(self.name, self.uvc.name)
        self.assertTrue(self.uvc.is_recording)
        self.assertEqual('Ubiquiti', self.uvc.brand)
        self.assertEqual('UVC Fake', self.uvc.model)

    @mock.patch('uvcclient.store.get_info_store')
    @mock.patch('uvcclient.camera.UVCCameraClientV320')
    def test_login(self, mock_camera, mock_store):
        """"Test the login."""
        mock_store.return_value.get_camera_password.return_value = 'seekret'
        self.uvc._login()
        mock_camera.assert_called_once_with('host-a', 'admin', 'seekret')
        mock_camera.return_value.login.assert_called_once_with()

    @mock.patch('uvcclient.store.get_info_store')
    @mock.patch('uvcclient.camera.UVCCameraClient')
    def test_login_v31x(self, mock_camera, mock_store):
        """Test login with v3.1.x server."""
        mock_store.return_value.get_camera_password.return_value = 'seekret'
        self.nvr.server_version = (3, 1, 3)
        self.uvc._login()
        mock_camera.assert_called_once_with('host-a', 'admin', 'seekret')
        mock_camera.return_value.login.assert_called_once_with()

    @mock.patch('uvcclient.store.get_info_store')
    @mock.patch('uvcclient.camera.UVCCameraClientV320')
    def test_login_no_password(self, mock_camera, mock_store):
        """"Test the login with no password."""
        mock_store.return_value.get_camera_password.return_value = None
        self.uvc._login()
        mock_camera.assert_called_once_with('host-a', 'admin', 'ubnt')
        mock_camera.return_value.login.assert_called_once_with()

    @mock.patch('uvcclient.store.get_info_store')
    @mock.patch('uvcclient.camera.UVCCameraClientV320')
    def test_login_tries_both_addrs_and_caches(self, mock_camera, mock_store):
        """"Test the login tries."""
        responses = [0]

        def fake_login(*a):
            try:
                responses.pop(0)
                raise socket.error
            except IndexError:
                pass

        mock_store.return_value.get_camera_password.return_value = None
        mock_camera.return_value.login.side_effect = fake_login
        self.uvc._login()
        self.assertEqual(2, mock_camera.call_count)
        self.assertEqual('host-b', self.uvc._connect_addr)

        mock_camera.reset_mock()
        self.uvc._login()
        mock_camera.assert_called_once_with('host-b', 'admin', 'ubnt')
        mock_camera.return_value.login.assert_called_once_with()

    @mock.patch('uvcclient.store.get_info_store')
    @mock.patch('uvcclient.camera.UVCCameraClientV320')
    def test_login_fails_both_properly(self, mock_camera, mock_store):
        """"Test if login fails properly."""
        mock_camera.return_value.login.side_effect = socket.error
        self.assertEqual(None, self.uvc._login())
        self.assertEqual(None, self.uvc._connect_addr)

    def test_camera_image_tries_login_bails_on_failure(self):
        """"Test retrieving failure."""
        with mock.patch.object(self.uvc, '_login') as mock_login:
            mock_login.return_value = False
            self.assertEqual(None, self.uvc.camera_image())
            mock_login.assert_called_once_with()

    def test_camera_image_logged_in(self):
        """"Test the login state."""
        self.uvc._camera = mock.MagicMock()
        self.assertEqual(self.uvc._camera.get_snapshot.return_value,
                         self.uvc.camera_image())

    def test_camera_image_error(self):
        """"Test the camera image error."""
        self.uvc._camera = mock.MagicMock()
        self.uvc._camera.get_snapshot.side_effect = camera.CameraConnectError
        self.assertEqual(None, self.uvc.camera_image())

    def test_camera_image_reauths(self):
        """"Test the re-authentication."""
        responses = [0]

        def fake_snapshot():
            try:
                responses.pop()
                raise camera.CameraAuthError()
            except IndexError:
                pass
            return 'image'

        self.uvc._camera = mock.MagicMock()
        self.uvc._camera.get_snapshot.side_effect = fake_snapshot
        with mock.patch.object(self.uvc, '_login') as mock_login:
            self.assertEqual('image', self.uvc.camera_image())
            mock_login.assert_called_once_with()
            self.assertEqual([], responses)

    def test_camera_image_reauths_only_once(self):
        """"Test if the re-authentication only happens once."""
        self.uvc._camera = mock.MagicMock()
        self.uvc._camera.get_snapshot.side_effect = camera.CameraAuthError
        with mock.patch.object(self.uvc, '_login') as mock_login:
            self.assertRaises(camera.CameraAuthError, self.uvc.camera_image)
            mock_login.assert_called_once_with()


text:
namespace net {
namespace simulator {

struct Packet {
  Packet();
  ~Packet();
  Packet(const Packet& packet);

  std::string source;
  std::string destination;
  QuicTime tx_timestamp;

  std::string contents;
  QuicByteCount size;
};

// An interface for anything that accepts packets at arbitrary rate.
class UnconstrainedPortInterface {
 public:
  virtual ~UnconstrainedPortInterface() {}
  virtual void AcceptPacket(std::unique_ptr<Packet> packet) = 0;
};

// An interface for any device that accepts packets at a specific rate.
// Typically one would use a Queue object in order to write into a constrained
// port.
class ConstrainedPortInterface {
 public:
  virtual ~ConstrainedPortInterface() {}

  // Accept a packet for a port.  TimeUntilAvailable() must be zero before this
  // method is called.
  virtual void AcceptPacket(std::unique_ptr<Packet> packet) = 0;

  // Time until write for the next port is available.  Cannot be infinite.
  virtual QuicTime::Delta TimeUntilAvailable() = 0;
};

// A convenience class for any network endpoints, i.e. the objects which can
// both accept and send packets.
class Endpoint : public Actor {
 public:
  virtual UnconstrainedPortInterface* GetRxPort() = 0;
  virtual void SetTxPort(ConstrainedPortInterface* port) = 0;

 protected:
  Endpoint(Simulator* simulator, std::string name);
};

}  // namespace simulator
}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_SIMULATOR_PORT_H_


text:
<?php

namespace IBazaar\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use IBazaar\FrontendBundle\Utils\Pagination;

class AppController extends Controller
{

    private static $MAX_RESULTS = 5;

    /**
     * @Route("/app/{id}", name="app_profile", requirements={"id" = "\d+"})
     * @Template()
     */
    public function profileAction($id) {
    	$app = $this->getDoctrine()
					->getRepository('IBazaarDataModelBundle:App')
					->findOneById($id);

    	if (!$app) {
    		throw $this->createNotFoundException('This app does not exist.');
    	}

        return array(
        	'currentApp' => $app
        );
    }

    /**
     * @Route("/top-descargas/{page}", name="app_downloads", requirements={"page" = "\d+"}, defaults={"page" = "1"})
     * @Template()
     */
    public function listByDownloadsAction($page) {
        $query = $this->getDoctrine()
                    ->getRepository('IBazaarDataModelBundle:App')
                    ->getQueryForMostDownloaded();

        $apps = Pagination::getPaginatedResults($query, self::$MAX_RESULTS, $page);

        return array(
            'apps' => $apps
        );
    }

    /**
     * @Route("/nuevas/{page}", name="app_new", requirements={"page" = "\d+"}, defaults={"page" = "1"})
     * @Template()
     */
    public function listByCreationDateAction($page) {
        $query = $this->getDoctrine()
                    ->getRepository('IBazaarDataModelBundle:App')
                    ->getQueryForNewest();

        $apps = Pagination::getPaginatedResults($query, self::$MAX_RESULTS, $page);

        return array(
            'apps' => $apps
        );
    }

    /**
     * @Route("/buscar/{page}", name="app_search", requirements={"page" = "\d+"}, defaults={"page" = "1"})
     * @Template()
     */
    public function searchAction($page, Request $request) {
        $searchTerm = $request->query->get("term");
        $query = $this->getDoctrine()
                    ->getRepository('IBazaarDataModelBundle:App')
                    ->getQueryForSearch($searchTerm);

        $apps = Pagination::getPaginatedResults($query, self::$MAX_RESULTS, $page);

        return array(
            'apps' => $apps,
            'term' => $searchTerm
        );
    }
}
?>


text:
public class Test8 {
    public void myMethod(Object o) {
        System.out.println("My Object");
    }
    public void myMethod(String s) {
        System.out.println("My String");
    }
    public static void main(String args[]) {
        Test8 t = new Test8();
        t.myMethod(null);
    }
}


text:
import inspect
import logging

from pumphouse import task
from taskflow.patterns import graph_flow
from . import utils

LOG = logging.getLogger(__name__)

def get_floatingIp_by(neutron, floatingIp_filter):
    try:
        return neutron.list_floatingips(**floatingIp_filter)["floatingips"]
    except Exception as e:
        raise e

def create_floatingip(neutron, floating_info):
    try:
        return neutron.create_floatingip(
            {'floatingip': floating_info}
        )
    except Exception as e:
        raise e

class RetrieveFloatingIps(task.BaseCloudTask):

    def execute(self):
        return get_floatingIp_by(self.cloud.neutron, {})

class RetrieveFloatingIpById(task.BaseCloudTask):

    def execute(self, all_floatingips, floating_id):
        for floating_ip in all_floatingips:
            if (floating_ip['id'] == floating_id):
                return floating_ip

        return None

class EnsureFloatingIp(task.BaseCloudTask):

    def execute(self, all_floatingips, floating_info,
                network_info, port_info, tenant_info):
        # TODO add router_id to arguments
        for floating_ip in all_floatingips:
            if (floating_ip['floating_ip_address'] ==
                    floating_info['floating_ip_address']):
                return floating_ip

        SKIP_PROPS = ["id", "router_id", "floating_ip_address",
                      "status", "tenant_id", "fixed_ip_address"]

        for prop in SKIP_PROPS:
            if prop in floating_info:
                LOG.info("removed prop: %s" % prop)
                del floating_info[prop]

        floating_info["floating_network_id"] = network_info["id"]
        floating_info["port_id"] = port_info["port-id"]
        floating_info["tenant_id"] = tenant_info["id"]

        return create_floatingip(self.cloud.neutron, floating_info)

def migrate_floatingip(context, floatingip_id, floating_ip_addr,
                       network_info, port_info, tenant_info):

    floatingip_binding = "floating-ip-{}".format(floating_ip_addr)

    floatingip_retrieve = "{}-retrieve".format(
        floatingip_binding)
    floatingip_ensure = "{}-ensure".format(
        floatingip_binding)

    (retrieve, ensure) = utils.generate_binding(
        floatingip_binding, inspect.stack()[0][3])

    if (floatingip_binding in context.store):
        return None, floatingip_retrieve

    context.store[floatingip_retrieve] = floatingip_id

    f = graph_flow.Flow(
        "neutron-floatingip-migration-{}".format(floatingip_binding))

    all_dst, all_src, all_src_retrieve, all_dst_retrieve = \
        utils.generate_retrieve_binding("NeutronAllFloatingIp")

    if (all_src not in context.store):
        f.add(RetrieveFloatingIps(
            context.src_cloud,
            name=all_src,
            provides=all_src_retrieve
        ))
        context.store[all_src] = None

    if (all_dst not in context.store):
        f.add(RetrieveFloatingIps(
            context.dst_cloud,
            name=all_dst,
            provides=all_dst_retrieve
        ))
        context.store[all_dst] = None

    f.add(RetrieveFloatingIpById(context.src_cloud,
                                 name=floatingip_binding,
                                 provides=floatingip_binding,
                                 rebind=[
                                     all_src_retrieve,
                                     floatingip_retrieve,
                                 ]))

    f.add(EnsureFloatingIp(context.dst_cloud,
                           name=floatingip_ensure,
                           provides=floatingip_ensure,
                           rebind=[
                               all_dst_retrieve,
                               floatingip_binding,
                               network_info,
                               port_info,
                               tenant_info
                           ]))

    return f, floatingip_ensure


text:
.form-builder-field-toolbar-toggle,
.form-builder-field-toolbar {
    position: absolute;
    right: 0;
    top: 0;
}

.form-builder-field-toolbar-item {
	display: inline-block;
}

.form-builder-field-toolbar-items {
    display: none;
}

.form-builder-field-toolbar.open .form-builder-field-toolbar-items {
    display: block;
}

.form-builder-field-toolbar-item.layout-builder-move-cut-button.layout-builder-move-cut-col-button {
    background-image: url('');
    height: auto;
    left: 0;
    width: auto;
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Atomic.Loader;
using System.Collections.Generic;

namespace Atomic.UnitTests.Loader
{
    [TestClass]
    public class JsonConverterTests
    {
        private JsonConverter dc = null;

        private ProcessModel InitializeModel(ProcessModel model)
        {
            model.ID = "hello_world";
            model.Name = "Hello World";

            /*
            model.Events = new EventModel[] {
                new EventModel() { ID = "_stop", StartConditionID = "taskDone" }
            };
            model.Tasks = new TaskModel[] {
                new TaskModel() { ID = "display_greeting", Name = "Display Greeting", RunScript="print \"Hello World!\"", StartConditionID = "startDone" };
            };
            model.Conditions = new ConditionModel[] {
                new ConditionModel() { ID = "startDone", TaskID="_start", State = ConditionModel.TaskState.Done },
                new ConditionModel() { ID = "taskDone", TaskID="display_message", State = ConditionModel.TaskState.Done }
            };
            */

            return model;
        }

        private string InitializeJsonText()
        {
            return "";
        }

        [TestInitialize]
        public void InitializeTest()
        {
            dc = new JsonConverter();
        }

        [TestCleanup]
        public void CleanupTest()
        {

        }

        [TestMethod]
        public void ExportJsonInitialStateTest()
        {
            ProcessModel model = (ProcessModel)dc.Model;
            InitializeModel(model);
            string resultText = dc.Export();

            Assert.IsTrue(resultText.StartsWith("{"));
            Assert.IsTrue(resultText.Contains("\"Name\":\"Hello World\""));
            Assert.IsTrue(resultText.Contains("\"ID\":\"hello_world\""));
            Assert.IsTrue(resultText.Contains("\"Events\":[]"));
            Assert.IsTrue(resultText.Contains("\"Tasks\":[]"));
            Assert.IsTrue(resultText.Contains("\"Conditions\":[]"));
            Assert.IsTrue(resultText.EndsWith("}"));
        }

        [TestMethod]
        public void ExportJsonEventTest()
        {
            ProcessModel model = (ProcessModel)dc.Model;
            InitializeModel(model);
            model.Events = new EventModel[] {
                    new EventModel() { ID = "_stop", StartCondition = new RefIdModel() { ID = "taskDone" } }
            };

            string resultText = dc.Export();
            Assert.IsTrue(resultText.Contains("\"Events\":[{"));
            Assert.IsTrue(resultText.Contains("\"ID\":\"_stop\""));
            Assert.IsTrue(resultText.Contains("\"Name\":\"\""));
            Assert.IsTrue(resultText.Contains("\"StartCondition\":{\"ID\":\"taskDone\"}"));
            Assert.IsTrue(resultText.Contains("\"StopCondition\":null}"));
        }

        [TestMethod]
        public void ExportJsonTaskTest()
        {
            ProcessModel model = (ProcessModel)dc.Model;
            InitializeModel(model);
            model.Tasks = new TaskModel[] {
                    new TaskModel() {
                        ID = "display_greeting",
                        Name = "Display Greeting",
                        RunScript="print \"Hello World!\"",
                        StartCondition = new RefIdModel() { ID = "startDone" }
                    }
            };

            string resultText = dc.Export();
            Assert.IsTrue(resultText.Contains("\"Tasks\":[{"));
            Assert.IsTrue(resultText.Contains("\"ID\":\"display_greeting\""));
            Assert.IsTrue(resultText.Contains("\"Name\":\"Display Greeting\""));
            Assert.IsTrue(resultText.Contains("\"StartCondition\":{\"ID\":\"startDone\"}"));
            Assert.IsTrue(resultText.Contains("\"StopCondition\":null"));
            Assert.IsTrue(resultText.Contains("\"RunScript\":\"print \\\"Hello World!\\\"\""));
        }

        [TestMethod]
        public void ExportJsonConditionTest()
        {
            ProcessModel model = (ProcessModel)dc.Model;
            InitializeModel(model);
            model.Conditions = new ConditionModel[] {
                    new ConditionModel() {
                        ID = "startDone",
                        Task = new RefIdModel() { ID = "_start" },
                        State = "Done"
                    },
                    new ConditionModel() {
                        ID = "taskDone",
                        Task = new RefIdModel() { ID = "display_message" },
                        State = "Done"
                    }
            };

            string resultText = dc.Export();
            Assert.IsTrue(resultText.Contains("\"Conditions\":[{"));
            Assert.IsTrue(resultText.Contains("\"ID\":\"startDone\""));
            Assert.IsTrue(resultText.Contains("\"Task\":{\"ID\":\"_start\"}"));
            Assert.IsTrue(resultText.Contains("\"State\":0"));
            Assert.IsTrue(resultText.Contains("\"ID\":\"taskDone\""));
            Assert.IsTrue(resultText.Contains("\"Task\":{\"ID\":\"display_message\"}"));
            Assert.IsTrue(resultText.Contains("\"State\":0"));
        }

        [TestMethod]
        public void ImportJsonInitialStateTest()
        {
            string jsonText = "{\"Name\":\"Hello World\",\"ID\":\"hello_world\",\"Events\":null,\"Tasks\":null,\"Conditions\":null}";
            dc.Import(jsonText);
            ProcessModel model = (ProcessModel)dc.Model;

            Assert.AreEqual(model.ID, "hello_world");
            Assert.AreEqual(model.Name, "Hello World");
            Assert.AreEqual(model.Events.Length, 0);
            Assert.AreEqual(model.Tasks.Length, 0);
            Assert.AreEqual(model.Conditions.Length, 0);
        }

        [TestMethod]
        public void ImportJsonEventTest()
        {
            string jsonText = "{\"Name\":null,\"ID\":null,\"Events\":[{\"ID\":\"_stop\",\"Name\":null,\"StartCondition\":{\"ID\":\"taskDone\"},\"StopCondition\":{\"ID\":\"\"}}],\"Tasks\":null,\"Conditions\":null}";
            dc.Import(jsonText);
            ProcessModel model = (ProcessModel)dc.Model;

            Assert.AreEqual(model.ID, "");
            Assert.AreEqual(model.Name, "");
            Assert.AreEqual(model.Events.Length, 1);
            Assert.AreEqual(model.Events[0].ID, "_stop");
            Assert.AreEqual(model.Events[0].Name, "");
            Assert.AreEqual(model.Events[0].StartCondition.ID, "taskDone");
            Assert.AreEqual(model.Tasks.Length, 0);
            Assert.AreEqual(model.Conditions.Length, 0);
        }

        [TestMethod]
        public void ImportJsonTaskTest()
        {
            string jsonText = "{\"Name\":null,\"ID\":null,\"Events\":null,\"Tasks\":[{\"ID\":\"display_greeting\",\"Name\":\"Display Greeting\",\"StartCondition\":{\"ID\":\"startDone\"},\"StopCondition\":{\"ID\":\"\"},\"RunScript\":\"print \\\"Hello World!\\\"\"}],\"Conditions\":null}";
            dc.Import(jsonText);
            ProcessModel model = (ProcessModel)dc.Model;

            Assert.AreEqual(model.ID, "");
            Assert.AreEqual(model.Name, "");
            Assert.AreEqual(model.Events.Length, 0);
            Assert.AreEqual(model.Tasks.Length, 1);
            Assert.AreEqual(model.Tasks[0].ID, "display_greeting");
            Assert.AreEqual(model.Tasks[0].Name, "Display Greeting");
            Assert.AreEqual(model.Tasks[0].StartCondition.ID, "startDone");
            Assert.AreEqual(model.Tasks[0].StopCondition.ID, "");
            Assert.AreEqual(model.Tasks[0].RunScript, "print \"Hello World!\"");
            Assert.AreEqual(model.Conditions.Length, 0);
        }

        [TestMethod]
        public void ImportJsonConditionTest()
        {
            ProcessModel model = (ProcessModel)dc.Model;
            InitializeModel(model);
            model.Conditions = new ConditionModel[] {
                    new ConditionModel() {
                        ID = "startDone",
                        Task = new RefIdModel() { ID = "_start" },
                        State = "Done"
                    },
                    new ConditionModel() {
                        ID = "taskDone",
                        Task = new RefIdModel() { ID = "display_message" },
                        State = "Done"
                    }
            };

            string jsonText = dc.Export();
            dc.Import(jsonText);

            Assert.AreEqual(model.ID, "hello_world");
            Assert.AreEqual(model.Name, "Hello World");
            Assert.AreEqual(model.Events.Length, 0);
            Assert.AreEqual(model.Tasks.Length, 0);
            Assert.AreEqual(model.Conditions.Length, 2);

            Assert.AreEqual(model.Conditions[0].ID, "startDone");
            Assert.AreEqual(model.Conditions[0].Name, "");
            Assert.AreEqual(model.Conditions[0].Task.ID, "_start");
            Assert.AreEqual(model.Conditions[0].State, "Done");

            Assert.AreEqual(model.Conditions[1].ID, "taskDone");
            Assert.AreEqual(model.Conditions[1].Name, "");
            Assert.AreEqual(model.Conditions[1].Task.ID, "display_message");
            Assert.AreEqual(model.Conditions[1].State, "Done");
        }
    }
}


text:
package japicmp.model;

import java.util.List;

/**
 * Implemented by all elements that have a modifier (access, synthetic, etc.)
 */
public interface JApiHasModifiers extends JApiHasChangeStatus {
	/**
	 * Returns a list of modifiers.
	 *
	 * @return a list of modifiers
	 */
	List<? extends JApiModifier<? extends Enum<? extends Enum<?>>>> getModifiers();
}


text:
'use strict';

require('mocha');
var assert = require('assert');
var cliSchema = require('..');
var App = require('./support');
var app;

describe('.pkg', function() {
  beforeEach(function() {
    app = new App();
  });

  describe('argv', function() {
    it('should convert a boolean to an object with a `show` property', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize(['--pkg']);
      assert.deepEqual(obj, {pkg: {show: true}});
    });

    it('should convert a string to an object', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize(['--pkg=foo']);
      assert.deepEqual(obj, {pkg: {foo: true}});
    });

    it('should expand objects', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize(['--pkg=foo:bar']);
      assert.deepEqual(obj, {pkg: {foo: 'bar'}});
    });
  });

  describe('pkg', function() {
    it('should convert a boolean to an object with a `show` property', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize({pkg: true});
      assert.deepEqual(obj, {pkg: {show: true}});
    });

    it('should convert a string to an object property with a boolean value', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize({pkg: 'foo'});
      assert.deepEqual(obj, {pkg: {foo: true}});
    });

    it('should return objects', function() {
      var schema = cliSchema(app);
      var obj = schema.normalize({pkg: {foo: 'bar'}});
      assert.deepEqual(obj, {pkg: {foo: 'bar'}});
    });
  });
});


text:
package com.googlecode.eyesfree.ocr.intent;

import android.app.Activity;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.googlecode.eyesfree.ocr.client.Intents;
import com.googlecode.eyesfree.opticflow.FrameProducer.Frame;
import com.googlecode.eyesfree.opticflow.FrameProducer.FrameReceiver;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author alanv@google.com (Alan Viverette)
 */
public abstract class CaptureActivity extends CameraActivity {
    private static final String TAG = "CaptureActivity";

    private static final int DEFAULT_JPEG_QUALITY = 85;

    private Uri mSaveUri;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSaveUri = getIntent().getParcelableExtra(Intents.Detect.EXTRA_OUTPUT);
    }

    protected void takePreview() {
        getCameraManager().requestFrame(frameCallback);
    }

    protected void takePicture() {
        getCameraManager().requestPicture(pictureCallback);
    }

    private void writePreview(byte[] yuvData, int format, int width, int height) {
        Log.i(TAG, "Writing preview to " + mSaveUri.toString());

        int result = Activity.RESULT_CANCELED;

        try {
            Rect rectangle = new Rect(0, 0, width, height);

            OutputStream stream = getContentResolver().openOutputStream(mSaveUri);

            YuvImage yuvImage = new YuvImage(yuvData, format, width, height, null);
            yuvImage.compressToJpeg(rectangle, DEFAULT_JPEG_QUALITY, stream);

            stream.close();

            result = Activity.RESULT_OK;
        } catch (IOException e) {
            e.printStackTrace();
        }

        setResult(result);
        finish();
    }

    private void writePicture(byte[] jpegData) {
        Log.i(TAG, "Writing picture to " + mSaveUri.toString());

        int result = Activity.RESULT_CANCELED;

        try {
            OutputStream stream = getContentResolver().openOutputStream(mSaveUri);

            stream.write(jpegData);
            stream.close();

            result = Activity.RESULT_OK;
        } catch (IOException e) {
            e.printStackTrace();
        }

        setResult(result);
        finish();
    }

    private final FrameReceiver frameCallback = new FrameReceiver() {
        @Override
        public void onFrameReceived(Frame frame) {
            writePreview(frame.data, frame.format, frame.width, frame.height);

            frame.recycle();
        }
    };

    private final Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            writePicture(data);
        }
    };
}


text:
var restify = require('restify');

var cb = require('./bin/Bots/BotConnectorBot')

var nursebot = new cb.NurseBot();

var server = restify.createServer();

server.get('/', (req, res, next) => {
  res.send({
    nurse: "remedi is live!",
    isCommandMode: nursebot.isCommandMode
  });
  next();
});

server.post('/api/messages', nursebot.verifyBotFramework(), nursebot.listen());

server.listen(process.env.port || 3978, function () {
    console.log('%s listening to %s', server.name, server.url);
});


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Animations Examples</title>
  <link rel="canonical" href="amps.html" >
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

<amp-animation id="anim1" layout="nodisplay" trigger="visibility">

</amp-animation>

<amp-img id="image"
         src="/test/fixtures/e2e/amphtml-ads/resource/car-engine.jpg"
         width=527 height=193 layout="responsive"></amp-img>

  <button id="restartBtn" on="tap:anim1.restart">Restart</button>
  <button id="cancelBtn" on="tap:anim1.cancel">Cancel</button>


text:
describe('Service: User Service', function() {
  // new instance of the module
  beforeEach(angular.mock.module('frodocms'));

  var $http, User;

  beforeEach(angular.mock.inject(function($injector) {
    $http = $injector.get('$http');
    User = $injector.get('User');
    spyOn(User, 'create').and.callThrough();
    spyOn(User, 'update').and.callThrough();
    spyOn(User, 'all').and.callThrough();
    User.create();
    User.update();
    User.all();
  }));

  it('should verify that allUsers function exists and is called', function() {
    expect(User.create).toBeDefined();
    expect(User.create).toHaveBeenCalled();
  });

  it('should verify that all function exists and is called', function() {
    expect(User.update).toBeDefined();
    expect(User.update).toHaveBeenCalled();
  });

  it('should verify that create function exists and is called', function() {
    expect(User.all).toBeDefined();
    expect(User.all).toHaveBeenCalled();
  });
});


text:
class djmain_state : public driver_device
{
public:
	djmain_state(const machine_config &mconfig, device_type type, const char *tag)
		: driver_device(mconfig, type, tag) { }

	int m_sndram_bank;
	UINT8 *m_sndram;
	int m_turntable_select;
	UINT8 m_turntable_last_pos[2];
	UINT16 m_turntable_pos[2];
	UINT8 m_pending_vb_int;
	UINT16 m_v_ctrl;
	UINT32 m_obj_regs[0xa0/4];
	const UINT8 *m_ide_user_password;
	const UINT8 *m_ide_master_password;
	UINT32 *m_obj_ram;
};

/*----------- defined in video/djmain.c -----------*/

SCREEN_UPDATE( djmain );
VIDEO_START( djmain );

void djmain_tile_callback(running_machine& machine, int layer, int *code, int *color, int *flags);


text:
define(
"dijit/nls/es/loading", //begin v1.x content
({
	loadingState: "Cargando...",
	errorState: "Lo siento, se ha producido un error"
})
//end v1.x content
);


text:
Run tsunami models for all unit-sources
---------------------------------------

The codes in this folder are made to run tsunami propagation models for every
unit-source on the source-zone. The unit-sources themselves must already have
been defined using code in [../EQ_SOURCE/](../EQ_SOURCE/).

**Currently the folder is set-up to run the
[SWALS model](https://github.com/GeoscienceAustralia/ptha/tree/master/propagation/SWALS)
on raijin.nci.org.au. The codes would require significant modification to be
run on another machine, or using another model.**

To run the models, the process is

# Step 1:

Check the variables defined in [config.R](config.R) and see that they point
to the correct unit sources, and that the model output files will go to a location
that you are happy with.

# Step 2

[create_files_for_all_simulations.R](create_files_for_all_simulations.R) is
used to make directory structures for all model runs (using some definitions
in [config.R](config.R)).

We make directories for all model runs by modifying template files in the
[template](template) folder. This allows us to define separate output
directories and initial conditions (i.e. tsunami unit sources) for every model
run. Note that files in the [template](template) folder define other model
configuration options (e.g. resolution), which may need to be modified
depending on your applications.

Once the [template](template) files are ok, to create a separate SWALS model
that runs for each unit-source, do:

    Rscript create_files_for_all_simulations.R

This script is quite light-weight (i.e. you might not need to use the job queue).

# Step 3

[run_16.sh](run_16.sh) is used to submit 16 of the SWALS models (which are not
already slated for running) to the job queue, to be run on a single node. The
number 16 was chosen because that is efficient for the hardware on
raijin.nci.org.au.  Note that significant performance benefits were gained by
using 'numactl' when running multiple jobs on a single node. It is run with:

    qsub run_16.sh

The above needs to be done repeatedly, until all model runs are completed.

**NOTE**: If you are running multiple source-zones, it may be preferable to use the
alternative script [../../run_16.sh](../../run_16.sh). The latter is run from
it's own directory, and has the advantage of being able to run models from more
than one source-zone (if it doesn't find 16 models to run on a single
source-zone).

# Step 4

Perform some basic checks that the models have run correctly.

[check_runs_complete.R](check_runs_complete.R) is used to check that the SWALS
model runs have finished, and to do some basic checks. It is run *from within
R* using:

```r
    # Read the functions into R
    source('check_runs_complete.R')
    # This is used to check for models that seem to have not completed
    check_models_have_been_run()
    # If the above is ok, then try this to check that gauge outputs exist and
    # are correctly ordered
    check_model_gauge_integrity()
```
If there is a problem it should print out an error message. Otherwise it will
be silent (and return NULL, which is what R does for functions that don't return
anything).

Note that this process can be run over multiple source-zones at once, by using
the alternative script [../../checkruns.R](../../checkruns.R).

[check_logfile.R](check_logfile.R) is used to plot the evolution of peak-stage
and mass balance in every tsunami model, using the log-files. To run it, do

    Rscript check_logfile.R

and then visually investigate the resulting pdf file 'tsunami_log_check.pdf',
which will show the time-evolution of peak-stage and mass-balance, for every
model.

# Step 5

[run_permute_netcdf_gauges.sh](run_permute_netcdf_gauges.sh) is used
permutes the dimension of the tide-gauge netcdf output files, to ensure fast
access to single-station data [which is extremely convenient for later
analysis]. It is run with:

    qsub run_permute_netcdf_gauges.sh


text:
package org.apache.derby.iapi.sql.execute;

import org.apache.derby.iapi.services.loader.GeneratedClass;

import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;

import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;

import java.util.List;

/**
 * Execution extends prepared statement to add methods it needs
 * for execution purposes (that should not be on the Database API).
 *
 */
public interface ExecPreparedStatement
	extends PreparedStatement {

	/**
	 * set the statement text
	 *
	 * @param txt the source text
	 */
	void setSource(String txt);

	/**
	 *	Get the Execution constants. This routine is called at Execution time.
	 *
	 *	@return	ConstantAction	The big structure enclosing the Execution constants.
	 */
	ConstantAction	getConstantAction( );

	/**
	 *	Get a saved object by number.  This is called during execution to
	 *  access objects created at compile time.  These are meant to be
	 *  read-only at run time.
	 *
	 *	@return	Object	A saved object.  The caller has to know what
	 *	it is requesting and cast it back to the expected type.
	 */
	Object	getSavedObject(int objectNum);

	/**
	 *	Get all the saved objects.  Used for stored prepared
	 * 	statements.
	 *
	 *	@return	Object[]	the saved objects
	 */
	Object[]	getSavedObjects();

	/**
	 *	Get the saved cursor info.  Used for stored prepared
	 * 	statements.
	 *
	 *	@return	Object	the cursor info
	 */
	Object	getCursorInfo();

	/**
	 *  Get the class generated for this prepared statement.
	 *  Used to confirm compatability with auxilary structures.
	 *
	 * @exception StandardException on error obtaining class
	 *	(probably when a stored prepared statement is loading)
	 */
	GeneratedClass getActivationClass() throws StandardException;

    /**
     *

     * Checks whether this PreparedStatement is up to date and its activation
     * class is identical to the supplied generated class. A call to {@code
     * upToDate(gc)} is supposed to perform the same work as the following code
     * in one atomic operation:
     *

     *
     *

     * getActivationClass() == gc && upToDate()
     *

     *
     * @param gc a generated class that must be identical to {@code
     * getActivationClass()} for this method to return {@code true}
     * @return {@code true} if this statement is up to date and its activation
     * class is identical to {@code gc}, {@code false} otherwise
     * @see PreparedStatement#upToDate()
     * @see #getActivationClass()
     */
    boolean upToDate(GeneratedClass gc) throws StandardException;

	/**
	 *  Mark the statement as unusable, i.e. the system is
	 * finished with it and no one should be able to use it.
	 */
	void finish(LanguageConnectionContext lcc);

	/**
	 * Does this statement need a savpoint
	 *
	 * @return true if needs a savepoint
	 */
	boolean needsSavepoint();

	/**
	 * Get a new prepared statement that is a shallow copy
	 * of the current one.
	 *
	 * @return a new prepared statement
	 *
	 * @exception StandardException on error
	 */
	public ExecPreparedStatement getClone() throws StandardException;

	/* Methods from old CursorPreparedStatement */

	/**
	 * the update mode of the cursor
	 *
	 * @return	The update mode of the cursor
	 */
	int	getUpdateMode();

	/**
	 * the target table of the cursor
	 *
	 * @return	target table of the cursor
	 */
	ExecCursorTableReference getTargetTable();

	/**
	 * the target columns of the cursor; this is a superset of
	 * the updatable columns, describing the row available
	 *
	 * @return	target columns of the cursor as an array of column descriptors
	 */
	ResultColumnDescriptor[]	getTargetColumns();

	/**
	 * the update columns of the cursor
	 *
	 * @return	update columns of the cursor as a string of column names
	 */
	String[]	getUpdateColumns();

	/**
	 * set this parepared statement to be valid
	 */
	void setValid();

	/**
	 * Indicate that the statement represents an SPS action
	 */
	void setSPSAction();

	/**
	 * @return the list of permissions required to execute this statement. May be null if
	 *         the database does not use SQL standard authorization
	 */
	List getRequiredPermissionsList();
}


text:
<!DOCTYPE html>

  <title ng-bind="pageTitle"></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
  <link href="app.less" type="text/css" rel="stylesheet/less">

      <button class="btn btn-default dropdown-toggle">Ryan Milstead </button>

          {{choice.name}}

Ryan Milstead

Former opera singer /
 full time Ruby dev

    Copyright © 2016 Ryan Milstead


text:
describe Metacrunch::Marcxml::Document::Datafield do

  describe "#initialize" do
    it "creates a new data field" do
      field = Metacrunch::Marcxml::Document::Datafield.new("123", ind1: "1", ind2: nil)

      expect(field).to be_instance_of(Metacrunch::Marcxml::Document::Datafield)
      expect(field.tag).to eq("123")
      expect(field.ind1).to eq("1")
      expect(field.ind2).to be_nil
    end
  end

  describe "#subfields" do
    let(:document) { default_test_document }
    let(:datafield) { document.datafields("100").first }

    context "given code=nil" do
      subject { datafield.subfields(nil) }

      it "returns a SubfieldSet" do
        expect(subject).to be_instance_of(Metacrunch::Marcxml::Document::SubfieldSet)
      end

      it "SubfieldfieldSet contains all sub fields" do
        expect(subject.count).to eq(datafield.instance_variable_get("@subfields_map").values.flatten(1).count)
      end
    end

    context "given non existing code" do
      subject { datafield.subfields("_not_existing_code_") }

      it "returns a SubfieldSet" do
        expect(subject).to be_instance_of(Metacrunch::Marcxml::Document::SubfieldSet)
      end

      it "SubfieldSet is empty" do
        expect(subject.empty?).to be(true)
      end
    end

    context "given code=p" do
      subject { datafield.subfields("p") }

      it "returns only sub fields with code=p" do
        expect(subject.all?{|f| f.code=="p"}).to be(true)
      end
    end

    context "given code=p and code=9" do
      subject { datafield.subfields(["p", "9"]) }

      it "returns only sub fields with code=p or code=9" do
        expect(subject.all?{|f| f.code=="p" || f.code=="9"}).to be(true)
      end
    end
  end

  describe "#add_subfield" do
    let(:document) { empty_document }
    let(:datafield) { document.add_datafield(create_datafield("123", ind1: "a", ind2: nil)) }

    it "should add sub field" do
      expect(datafield.subfields("a").count).to eq(0)
      datafield.add_subfield(create_subfield("a", "Lorem Ipsum"))
      expect(datafield.subfields("a").count).to eq(1)
    end
  end

end


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "filter.h"
#include "partition.h"
#include "zigzag.h"

/* The tables below specify how coefficient blocks are translated to
   and from PVQ partition coding scan order for 4x4, 8x8 and 16x16 */
static const int OD_LAYOUT64_OFFSETS[4] = { 0, 512, 1024, 3072 };
const band_layout OD_LAYOUT64 = {
  OD_ZIGZAG64,
  64,
  3,
  OD_LAYOUT64_OFFSETS
};

static const int OD_LAYOUT32_OFFSETS[4] = { 0, 128, 256, 768};
const band_layout OD_LAYOUT32 = {
  OD_ZIGZAG32,
  32,
  3,
  OD_LAYOUT32_OFFSETS
};

static const int OD_LAYOUT16_OFFSETS[4] = { 0, 32, 64, 192 };
const band_layout OD_LAYOUT16 = {
  OD_ZIGZAG16,
  16,
  3,
  OD_LAYOUT16_OFFSETS
};

const int OD_LAYOUT8_OFFSETS[4] = { 0, 8, 16, 48 };
const band_layout OD_LAYOUT8 = {
  OD_ZIGZAG8,
  8,
  3,
  OD_LAYOUT8_OFFSETS
};

static const int OD_LAYOUT4_OFFSETS[2] = { 0, 15 };
const band_layout OD_LAYOUT4 = {
  OD_ZIGZAG4,
  4,
  1,
  OD_LAYOUT4_OFFSETS
};

/* First element is the number of bands, followed by the list all the band
  boundaries. */
static const int OD_BAND_OFFSETS4[] = {1, 1, 16};
static const int OD_BAND_OFFSETS8[] = {4, 1, 16, 24, 32, 64};
static const int OD_BAND_OFFSETS16[] = {7, 1, 16, 24, 32, 64, 96, 128, 256};
static const int OD_BAND_OFFSETS32[] = {10, 1, 16, 24, 32, 64, 96, 128, 256,
 384, 512, 1024};
static const int OD_BAND_OFFSETS64[] = {13, 1, 16, 24, 32, 64, 96, 128, 256,
 384, 512, 1024, 1536, 2048, 4096};

const int *const OD_BAND_OFFSETS[OD_NBSIZES + 1] = {
  OD_BAND_OFFSETS4,
  OD_BAND_OFFSETS8,
  OD_BAND_OFFSETS16,
  OD_BAND_OFFSETS32,
  OD_BAND_OFFSETS64
};

/** Perform a single stage of conversion from a coefficient block in
 * raster order into coding scan order
 *
 * @param [in]     layout  scan order specification
 * @param [out]    dst     destination vector
 * @param [in]     src     source coefficient block
 * @param [int]    int     source vector row stride
 */
static void od_band_from_raster(const band_layout *layout, od_coeff *dst,
 od_coeff *src, int stride) {
  int i;
  int len;
  len = layout->band_offsets[layout->nb_bands];
  for (i = 0; i < len; i++) {
    dst[i] = src[layout->dst_table[i][1]*stride + layout->dst_table[i][0]];
  }
}

/** Perform a single stage of conversion from a vector in coding scan
    order back into a coefficient block in raster order
 *
 * @param [in]     layout  scan order specification
 * @param [out]    dst     destination coefficient block
 * @param [in]     src     source vector
 * @param [int]    stride  destination vector row stride
 */
static void od_raster_from_band(const band_layout *layout, od_coeff *dst,
 int stride, od_coeff *src) {
  int i;
  int len;
  len = layout->band_offsets[layout->nb_bands];
  for (i = 0; i < len; i++) {
    dst[layout->dst_table[i][1]*stride + layout->dst_table[i][0]] = src[i];
  }
}

/** Converts a coefficient block in raster order into a vector in
 * coding scan order with the PVQ partitions laid out one after
 * another.  This works in stages; the 4x4 conversion is applied to
 * the coefficients nearest DC, then the 8x8 applied to the 8x8 block
 * nearest DC that was not already coded by 4x4, then 16x16 following
 * the same pattern.
 *
 * @param [out]    dst        destination vector
 * @param [in]     n          block size (along one side)
 * @param [in]     src        source coefficient block
 * @param [in]     stride     source vector row stride
 * @param [in]     interleave interleaves entries for the scalar
                              (non-pvq) case
 */
void od_raster_to_coding_order(od_coeff *dst,  int n, od_coeff *src,
 int stride) {
  /* TODO - Rewrite these as a loop. */
  od_band_from_raster(&OD_LAYOUT4, dst + 1, src, stride);
  if (n >= 8) {
    od_band_from_raster(&OD_LAYOUT8, dst + 16, src, stride);
  }
  if (n >= 16) {
    od_band_from_raster(&OD_LAYOUT16, dst + 64, src, stride);
  }
  if (n >= 32) {
    od_band_from_raster(&OD_LAYOUT32, dst + 256, src, stride);
  }
  if (n >= 64) {
    od_band_from_raster(&OD_LAYOUT64, dst + 1024, src, stride);
  }
  dst[0] = src[0];
}

/** Converts a vector in coding scan order witht he PVQ partitions
 * laid out one after another into a coefficient block in raster
 * order. This works in stages in the reverse order of raster->scan
 * order; the 16x16 conversion is applied to the coefficients that
 * don't appear in an 8x8 block, then the 8x8 applied to the 8x8 block
 * sans the 4x4 block it contains, then 4x4 is converted sans DC.
 *
 * @param [out]    dst        destination coefficient block
 * @param [in]     stride     destination vector row stride
 * @param [in]     src        source vector
 * @param [in]     n          block size (along one side)
 * @param [in]     interleave de-interleaves entries for
                              the scalar (non-pvq) case
 */
void od_coding_order_to_raster(od_coeff *dst,  int stride, od_coeff *src,
 int n) {
  /* TODO - Rewrite these as a loop. */
  od_raster_from_band(&OD_LAYOUT4, dst, stride, src + 1);
  if (n >= 8) {
    od_raster_from_band(&OD_LAYOUT8, dst, stride, src + 16);
  }
  if (n >= 16) {
    od_raster_from_band(&OD_LAYOUT16, dst, stride, src + 64);
  }
  if (n >= 32) {
    od_raster_from_band(&OD_LAYOUT32, dst, stride, src + 256);
  }
  if (n >= 64) {
    od_raster_from_band(&OD_LAYOUT64, dst, stride, src + 1024);
  }
  dst[0] = src[0];
}


text:
package leap.web.assets;

import java.util.List;
import java.util.Locale;

import leap.core.AppConfigAware;
import leap.core.annotation.Inject;
import leap.core.annotation.M;
import leap.core.cache.Cache;
import leap.lang.Locales;
import leap.lang.Strings;
import leap.lang.path.Paths;
import leap.lang.resource.Resource;

public class DefaultAssetSource extends AbstractCachingAssetSource implements AssetSource,AppConfigAware {

	protected @Inject AssetConfig  config;
    protected @Inject AssetManager manager;

	/** The underlying resolvers to resolve assets*/
	protected @Inject AssetResolver[] resolvers;

    @Inject(name="assets")
    protected @M Cache<Object, Asset> assetCache;

	@Override
    protected Cache<Object, Asset> getAssetCache() {
	    return assetCache;
    }

	public void setAssetCache(Cache<Object, Asset> assetCache) {
		this.assetCache = assetCache;
	}

    protected Asset loadAsset(String assetPath, Locale locale) throws Throwable {
		Asset a;

		for(AssetResolver resolver : resolvers) {
			if((a = resolver.resolveAsset(assetPath, locale)) != null) {
				return a;
			}
		}

		return loadAssetFromExternalFolders(assetPath, locale);
	}

	protected Asset loadAssetFromExternalFolders(String assetPath, Locale locale) throws Throwable {
		List<AssetFolder> folders = config.getFolders();
		if(folders.isEmpty()) {
			return null;
		}

		Asset asset;

		for(AssetFolder folder : folders) {

			if(null != (asset = loadAssetFromExternalFolder(assetPath, locale, folder))) {
				return asset;
			}

		}

		return null;
	}

	protected Asset loadAssetFromExternalFolder(String assetPath, Locale locale, AssetFolder folder) throws Throwable {
        String filepath = assetPath;

        if(!Strings.isEmpty(folder.getPathPrefix())) {

            String prefix = Paths.prefixWithoutSlash(folder.getPathPrefix());

            if(!assetPath.startsWith(prefix)) {
                return null;
            }

            filepath = Strings.removeStart(filepath, prefix);
        }

        String[] filepaths = Locales.getLocaleFilePaths(locale, filepath);

        Resource resource = null;
        for(String path : filepaths) {
            resource = folder.getRelativeResource(path);
            if(null != resource && resource.exists()) {
                break;
            }
        }

        if(null == resource || !resource.exists()) {
            return null;
        }

		return new SimpleAsset(manager, assetPath, resource);
	}
}


text:
import java.util.Map;

/**
 * @author sunxiaoyang
 */
public class _111_Minimum_Depth_of_Binary_Tree {

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null)
            return 1;
        if (root.left == null)
            return 1 + minDepth(root.right);
        if (root.right == null)
            return 1 + minDepth(root.left);
        return 1 + Math.min(minDepth(root.left), minDepth(root.right));
    }

    /**
     * Definition for a binary tree node.
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}