text:
"""Evaluates a TFGAN trained compression model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

import data_provider
import networks
import summaries

flags = tf.flags
FLAGS = flags.FLAGS

flags.DEFINE_string('master', '', 'Name of the TensorFlow master to use.')

flags.DEFINE_string('checkpoint_dir', '/tmp/compression/',
                    'Directory where the model was written to.')

flags.DEFINE_string('eval_dir', '/tmp/compression/',
                    'Directory where the results are saved to.')

flags.DEFINE_integer('max_number_of_evaluations', None,
                     'Number of times to run evaluation. If `None`, run '
                     'forever.')

flags.DEFINE_string('dataset_dir', None, 'Location of data.')

# Compression-specific flags.
flags.DEFINE_integer('batch_size', 32, 'The number of images in each batch.')

flags.DEFINE_integer('patch_size', 32, 'The size of the patches to train on.')

flags.DEFINE_integer('bits_per_patch', 1230,
                     'The number of bits to produce per patch.')

flags.DEFINE_integer('model_depth', 64,
                     'Number of filters for compression model')

def main(_, run_eval_loop=True):
  with tf.name_scope('inputs'):
    images = data_provider.provide_data(
        'validation', FLAGS.batch_size, dataset_dir=FLAGS.dataset_dir,
        patch_size=FLAGS.patch_size)

  # In order for variables to load, use the same variable scope as in the
  # train job.
  with tf.variable_scope('generator'):
    reconstructions, _, prebinary = networks.compression_model(
        images,
        num_bits=FLAGS.bits_per_patch,
        depth=FLAGS.model_depth,
        is_training=False)
  summaries.add_reconstruction_summaries(images, reconstructions, prebinary)

  # Visualize losses.
  pixel_loss_per_example = tf.reduce_mean(
      tf.abs(images - reconstructions), axis=[1, 2, 3])
  pixel_loss = tf.reduce_mean(pixel_loss_per_example)
  tf.summary.histogram('pixel_l1_loss_hist', pixel_loss_per_example)
  tf.summary.scalar('pixel_l1_loss', pixel_loss)

  # Create ops to write images to disk.
  uint8_images = data_provider.float_image_to_uint8(images)
  uint8_reconstructions = data_provider.float_image_to_uint8(reconstructions)
  uint8_reshaped = summaries.stack_images(uint8_images, uint8_reconstructions)
  image_write_ops = tf.write_file(
      '%s/%s'% (FLAGS.eval_dir, 'compression.png'),
      tf.image.encode_png(uint8_reshaped[0]))

  # For unit testing, use `run_eval_loop=False`.
  if not run_eval_loop: return
  tf.contrib.training.evaluate_repeatedly(
      FLAGS.checkpoint_dir,
      master=FLAGS.master,
      hooks=[tf.contrib.training.SummaryAtEndHook(FLAGS.eval_dir),
             tf.contrib.training.StopAfterNEvalsHook(1)],
      eval_ops=image_write_ops,
      max_number_of_evaluations=FLAGS.max_number_of_evaluations)

if __name__ == '__main__':
  tf.app.run()


text:
#import <Foundation/Foundation.h>
#import "ASPObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

#import "ASPBorder.h"
#import "ASPLink.h"
#import "ASPColor.h"

@protocol ASPFont
@end

@interface ASPFont : ASPObject

@property(nonatomic) NSNumber* allCaps;

@property(nonatomic) NSNumber* bidi;

@property(nonatomic) NSNumber* bold;

@property(nonatomic) NSNumber* boldBi;

@property(nonatomic) ASPBorder* border;

@property(nonatomic) ASPColor* color;

@property(nonatomic) NSNumber* complexScript;

@property(nonatomic) NSNumber* doubleStrikeThrough;

@property(nonatomic) NSNumber* emboss;

@property(nonatomic) NSNumber* engrave;

@property(nonatomic) NSNumber* hidden;

@property(nonatomic) ASPColor* highlightColor;

@property(nonatomic) NSNumber* italic;

@property(nonatomic) NSNumber* italicBi;

@property(nonatomic) NSNumber* kerning;

@property(nonatomic) NSNumber* localeId;

@property(nonatomic) NSNumber* localeIdBi;

@property(nonatomic) NSNumber* localeIdFarEast;

@property(nonatomic) NSString* name;

@property(nonatomic) NSString* nameAscii;

@property(nonatomic) NSString* nameBi;

@property(nonatomic) NSString* nameFarEast;

@property(nonatomic) NSString* nameOther;

@property(nonatomic) NSNumber* noProofing;

@property(nonatomic) NSNumber* outline;

@property(nonatomic) NSNumber* position;

@property(nonatomic) NSNumber* scaling;

@property(nonatomic) NSNumber* shadow;

@property(nonatomic) NSNumber* size;

@property(nonatomic) NSNumber* sizeBi;

@property(nonatomic) NSNumber* smallCaps;

@property(nonatomic) NSNumber* spacing;

@property(nonatomic) NSNumber* strikeThrough;

@property(nonatomic) NSString* styleIdentifier;

@property(nonatomic) NSString* styleName;

@property(nonatomic) NSNumber* subscript;

@property(nonatomic) NSNumber* superscript;

@property(nonatomic) NSString* textEffect;

@property(nonatomic) NSString* underline;

@property(nonatomic) ASPColor* underlineColor;

@property(nonatomic) ASPLink* link;

@end

redpajama_set_name: RedPajamaGithub


text:
package net.sansa_stack.spark.cli.impl;

import net.sansa_stack.spark.cli.cmd.CmdMixinSparkPostProcess;
import net.sansa_stack.spark.cli.cmd.CmdSansaMap;
import net.sansa_stack.spark.io.rdf.input.api.RdfSource;
import net.sansa_stack.spark.io.rdf.input.api.RdfSourceCollection;
import net.sansa_stack.spark.io.rdf.input.api.RdfSourceFactory;
import net.sansa_stack.spark.io.rdf.input.impl.RdfSourceFactoryImpl;
import net.sansa_stack.spark.io.rdf.output.RddRdfWriter;
import net.sansa_stack.spark.io.rdf.output.RddRdfWriterFactory;
import net.sansa_stack.spark.rdd.op.rdf.JavaRddOfQuadsOps;
import net.sansa_stack.spark.rdd.op.rdf.JavaRddOfTriplesOps;
import net.sansa_stack.spark.rdd.op.rdf.JavaRddOps;
import org.aksw.jenax.arq.analytics.NodeAnalytics;
import org.aksw.jenax.arq.util.quad.QuadUtils;
import org.aksw.jenax.arq.util.triple.TripleUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.jena.graph.Triple;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.shared.PrefixMapping;
import org.apache.jena.sparql.core.Quad;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.SparkSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Called from the Java class {@link CmdSansaMap}
 */
public class CmdSansaMapImpl {
  private static Logger logger = LoggerFactory.getLogger(CmdSansaMapImpl.class);

  public static int run(CmdSansaMap cmd) throws IOException {

    List<String> inputStrs = cmd.inputFiles;

    SparkSession sparkSession = CmdUtils.newDefaultSparkSessionBuilder()
            .appName("Sansa Sort (" + cmd.inputFiles + ")")
            .getOrCreate();

    Configuration hadoopConf = sparkSession.sparkContext().hadoopConfiguration();

    RddRdfWriterFactory rddRdfWriterFactory = CmdUtils.configureWriter(cmd.outputConfig);
    rddRdfWriterFactory.getPostProcessingSettings().copyFrom(cmd.postProcessConfig);

    CmdUtils.validatePaths(inputStrs, hadoopConf);

    RdfSourceFactory rdfSourceFactory = RdfSourceFactoryImpl.from(sparkSession);

    RdfSourceCollection rdfSources = CmdUtils.createRdfSourceCollection(rdfSourceFactory, cmd.inputFiles, cmd.inputConfig);

    writeOutRdfSources(rdfSources, rddRdfWriterFactory);

    return 0; // exit code
  }

  public static void writeOutRdfSources(RdfSource rdfSources, RddRdfWriterFactory rddRdfWriterFactory) {

    StopWatch stopwatch = StopWatch.createStarted();

    int initialPrefixCount = rddRdfWriterFactory.getGlobalPrefixMapping().numPrefixes();

    Model declaredPrefixes = rdfSources.peekDeclaredPrefixes();
    int declaredPrefixCount = declaredPrefixes.numPrefixes();

    RddRdfWriter<?> rddRdfWriter;

    if (rdfSources.usesQuads()) {
      JavaRDD<Quad> rdd = rdfSources.asQuads().toJavaRDD();
      rddRdfWriter = rddRdfWriterFactory.forQuad(rdd);
    } else {
      JavaRDD<Triple> rdd = rdfSources.asTriples().toJavaRDD();
      rddRdfWriter = rddRdfWriterFactory.forTriple(rdd);
    }
    rddRdfWriter.runUnchecked();

    Map<String, String> usedPm = Optional.ofNullable(rddRdfWriter.getGlobalPrefixMapping())
            .map(PrefixMapping::getNsPrefixMap).orElse(null);
    if (usedPm != null) {
      int usedPmCount = usedPm.size();
      logger.info(String.format("Optimization of prefixes reduced their number from %d to %d (of which %d originated from the sources)", initialPrefixCount, usedPmCount, declaredPrefixCount));
    }

    logger.info("Processing time: " + stopwatch.getTime(TimeUnit.SECONDS) + " seconds");

  }
}


text:
package com.credit.web.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.credit.web.entity.User;
import com.credit.web.util.Constants;
/**
 * 用户登录过滤器
 * @author huixiong
 * @date: 2016年7月19日 下午4:46:58
 * @since:1.0.0
 */
public class UserLoginFilter implements Filter {

    /**
     * Default constructor.
     */
    public UserLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) {
		   try {
			// 获得在下面代码中要用的request,response,session对象
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			HttpSession session = request.getSession();

			String contextPath = request.getContextPath();
			// 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath;

			// 获得用户请求的URI
			String path = request.getRequestURI();

			// 从session里取员工工号信息
			User userInfo = (User) session.getAttribute("userInfo");

			// 空连接时默认跳转到首页
			if(path.equals("")||path.equals("/")||path.equals("/credit_web/")){
				response.sendRedirect(basePath+"/index.html");
				return;
			}
			/*创建类Constants.java,里面写的是无需过滤的页面*/
			for (int i = 0; i < Constants.NoFilter_Pages.length; i++) {
			    if (path.indexOf(Constants.NoFilter_Pages[i]) > -1) {
			    	chain.doFilter(request, response);
			        return;
			    }
			}

			// 过滤无序验证的文件
			if (path.indexOf(".css")>-1
					||path.contains(".css")
					|| path.contains(".js")
					|| path.contains(".jpg")
					|| path.contains(".JPG")
					|| path.contains(".png")
					|| path.contains(".gif")
					|| path.contains(".ttf")
					|| path.contains(".woff")
					|| path.contains(".woff2")
					|| path.contains(".eot")
					|| path.contains(".html")) {
				chain.doFilter(request, response);
				return;
			}

			// 判断如果没有取到员工信息,就跳转到登陆页面
			if (userInfo == null || "".equals(userInfo)) {
			    // 跳转到登陆页面
				response.sendRedirect(basePath+"/user/tologin");
			} else {
			    // 已经登陆,继续此次请求
			    chain.doFilter(servletRequest, servletResponse);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}


text:
/**
 * Contains data I/O functionality.
 *
 *
IO Notes

 *
 *
 *
 * There exists a conceptual hierarchy of random access capabilities for data storage resources, from pure sequential
 * access up to full random access. Each level extends the functionality of the previous. The hierarchy is as
 * follows:

 *
 *

 *
 *
Sequential access

Data can be read or written in order with no ability change position. A input resource
 * would be expected to implement a very simply interface such as {@link java.util.Iterator} or {@link DataSource}

 *
 *
Limited mark/reset

The resource contains some buffer capabilities such a single position can be marked
 * and then returned at a later point within some limit.

 *
 *
Unlimited mark/reset

The single marked position can be returned to after an arbitrary number of
 * access.

 *
 *
Seekable

The resource can be queried for it's current position, returning a value which can be used to
 * return to that position at any point. Any number of positions can be produced and stored externally, and they will
 * remain valid as long as the resource is open. The {@link Seekable} interface implements this behaviour.

 *
 *
Full random access

Every data access method is can be parameterised with a position that will operate on
 * the associated location. The key difference between full random access and seekable that the latter supports seeking
 * at any time (cf. seekable positions are only required to be valid after the position has been reached and the
 * position accessor has been called.)

 *
 *

 *
 * In addition a resource may support a number of other capabilities. These include:
 *
 *

 *
 *
Bidirectionality

 *
 *
Closeable

 *
 *
Flushable

 *
 *

 *
 */
@ParametersAreNonnullByDefault package uk.ac.susx.mlcl.lib.io;

import javax.annotation.ParametersAreNonnullByDefault;


text:
<?php
namespace Gwa\Image;

/**
 * Calculates new image dimensions
 */
class Dimensions
{
    /**
     * @param int $maxwidth
     * @param int $maxheight
     * @return \stdClass
     */
    public function resizeToWithin($width, $height, $maxwidth, $maxheight)
    {
        if ($width <= $maxwidth && $height <= $maxheight) {
            return null;
        }

        // calculate ratio based on widths
        $ratio = $maxwidth / $width;
        if ($height * $ratio > $maxheight) {
            // new height greater than maximum
            $ratio = $maxheight / $height;
        }

        $dimensions = new \stdClass;
        $dimensions->width = max(1, round($width * $ratio));
        $dimensions->height = max(1, round($height * $ratio));

        return $dimensions;
    }

    /**
     * @param int $width
     * @param int $height
     * @param int|null $newwidth
     * @param int|null $newheight
     * @return \stdClass|null
     */
    public function resizeTo($width, $height, $newwidth, $newheight)
    {
        if ($width === $newwidth && $height === $newheight) {
            return null;
        }

        if (!$newheight) {
            return $this->resizeToWidth($width, $height, $newwidth);
        }

        if (!$newwidth) {
            return $this->resizeToHeight($width, $height, $newheight);
        }

        $ratio = $newwidth / $width;

        $dimensions = new \stdClass;
        $dimensions->overhang = false;
        $dimensions->width = $newwidth;
        $dimensions->height = $newheight;

        if ($height * $ratio < $newheight) {
            // - height is too small
            // - resize to height, and crop horizontal overhang
            $ratio = $newheight / $height;
            $dimensions->width = max(1, round($width * $ratio));
            $dimensions->height = $newheight;
            $dimensions->overhang = true;
        } elseif ($height * $ratio > $newheight) {
            // - height is too large
            // - resize to width, and crop vertical overhang
            $dimensions->width = $newwidth;
            $dimensions->height = max(1, round($height * $ratio));
            $dimensions->overhang = true;
        }

        return $dimensions;
    }

    /**
     * @param int $width
     * @param int $height
     * @param int $newwidth
     * @return \stdClass|null
     */
    private function resizeToWidth($width, $height, $newwidth)
    {
        if ($width === $newwidth) {
            return null;
        }

        $ratio = $newwidth / $width;

        $dimensions = new \stdClass;
        $dimensions->width = $newwidth;
        $dimensions->height = max(1, round($height * $ratio));
        $dimensions->overhang = false;

        return $dimensions;
    }

    /**
     * @param int $width
     * @param int $height
     * @param int $newheight
     * @return \stdClass
     */
    private function resizeToHeight($width, $height, $newheight)
    {
        if ($height === $newheight) {
            return null;
        }

        $ratio = $newheight / $height;

        $dimensions = new \stdClass;
        $dimensions->width = max(1, round($width * $ratio));
        $dimensions->height = $newheight;
        $dimensions->overhang = false;

        return $dimensions;
    }
}


text:
Autoplay is the concept of playing media elements without user gesture. On
desktop, autoplay is always allowed. On mobile, only muted video elements are
allowed to autoplay. The autoplay logic follows
the
[HTML spec](https://html.spec.whatwg.org/multipage/embedded-content.html#media-elements).

There are two ways of initiating autoplay:

* Autoplay by attribute: Setting the `autoplay` attribute on the media element.
  The element will try to autoplay when the `readyState` changes to
  HAVE_ENOUGH_DATA.
* Autoplay by `play()` method: Explicitly calling the `play()` method without
  user gesture.

All the autoplay logic is handled by the AutoplayPolicy class. When the media
element wants to perform some action (like unmute, autoplay by attribute or
`play()` method), it will send a request to AutoplayPolicy, and if the request
is approved, the element can autoplay, otherwise it should be paused. Also the
media element should inform the AutoplayPolicy about relevant changes such as
"the element has been moved to a new document".

## User gesture lock

Each media element has a user gesture lock. If the element is allowed to
autoplay, the lock is initialized as `false`, otherwise it's `true`.

When the element is trying to initate autoplay, we check the gesture lock. If
the lock is `false`, it will be allowed. Otherwise autoplay will be blocked. An
exception is that if the element is a muted video element, the gesture lock
check will be bypassed.

To unlock the gesture lock (make it `false`). The page needs to call play() or
load() on the element when responding to a user gesture.

## Autoplay flowchart

The treatments of autoplay by different methods are different. For autoplay by
attribute, it is:

![Autoplay by attribute](autoplay_by_attribute.png)

This means if autoplay is initiated by attribute, it enters the autoplaying
phase, we play it as long as the video is visible. When the page explicitly
calls `play()`, `pause()`, we leave the autoplaying phase. When the page tries
to unmute the video, we check the gesture lock and pause the video if it is
still `true`.

For autoplay by `play()` method, it is:

![Autoplay by play() method](autoplay_by_play_method.png)

This means if autoplay is initiated by `play()` method, we continue playing the
video as normal `play()`. However if the page tries to unmute the video, we check
the gesture lock and pause the video if it is still `true`.


text:
package server

import (
	"context"
	"net/http"

	"github.com/rancher/norman/api/builtin"
	"github.com/rancher/norman/pkg/subscribe"
	rancherapi "github.com/rancher/rancher/pkg/api"
	"github.com/rancher/rancher/pkg/api/controllers/catalog"
	"github.com/rancher/rancher/pkg/api/controllers/dynamicschema"
	"github.com/rancher/rancher/pkg/api/controllers/feature"
	"github.com/rancher/rancher/pkg/api/controllers/k3smetadata"
	"github.com/rancher/rancher/pkg/api/controllers/samlconfig"
	"github.com/rancher/rancher/pkg/api/controllers/settings"
	"github.com/rancher/rancher/pkg/api/controllers/usercontrollers"
	whitelistproxyKontainerDriver "github.com/rancher/rancher/pkg/api/controllers/whitelistproxy/kontainerdriver"
	whitelistproxyNodeDriver "github.com/rancher/rancher/pkg/api/controllers/whitelistproxy/nodedriver"
	"github.com/rancher/rancher/pkg/api/server/managementstored"
	"github.com/rancher/rancher/pkg/api/server/userstored"
	"github.com/rancher/rancher/pkg/clustermanager"
	clusterSchema "github.com/rancher/types/apis/cluster.cattle.io/v3/schema"
	managementSchema "github.com/rancher/types/apis/management.cattle.io/v3/schema"
	projectSchema "github.com/rancher/types/apis/project.cattle.io/v3/schema"
	"github.com/rancher/types/config"
)

func New(ctx context.Context, scaledContext *config.ScaledContext, clusterManager *clustermanager.Manager,
	k8sProxy http.Handler, localClusterEnabled bool) (http.Handler, error) {
	subscribe.Register(&builtin.Version, scaledContext.Schemas)
	subscribe.Register(&managementSchema.Version, scaledContext.Schemas)
	subscribe.Register(&clusterSchema.Version, scaledContext.Schemas)
	subscribe.Register(&projectSchema.Version, scaledContext.Schemas)

	if err := managementstored.Setup(ctx, scaledContext, clusterManager, k8sProxy, localClusterEnabled); err != nil {
		return nil, err
	}

	if err := userstored.Setup(ctx, scaledContext, clusterManager, k8sProxy); err != nil {
		return nil, err
	}

	server, err := rancherapi.NewServer(scaledContext.Schemas)
	if err != nil {
		return nil, err
	}
	server.AccessControl = scaledContext.AccessControl

	catalog.Register(ctx, scaledContext)
	dynamicschema.Register(ctx, scaledContext, server.Schemas)
	feature.Register(ctx, scaledContext)
	whitelistproxyNodeDriver.Register(ctx, scaledContext)
	whitelistproxyKontainerDriver.Register(ctx, scaledContext)
	samlconfig.Register(ctx, scaledContext)
	k3smetadata.Register(ctx, scaledContext)
	usercontrollers.Register(ctx, scaledContext, clusterManager)
	err = settings.Register(scaledContext)

	return server, err
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net;

import org.chromium.base.Log;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

import java.lang.reflect.Method;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.ECParameterSpec;

/**
 * Specifies all the dependencies from the native OpenSSL engine on an Android KeyStore.
 */
@JNINamespace("net::android")
public class AndroidKeyStore {
    private static final String TAG = "AndroidKeyStore";

    /**
     * Returns the public modulus of a given RSA private key as a byte
     * buffer.
     * This can be used by native code to convert the modulus into
     * an OpenSSL BIGNUM object. Required to craft a custom native RSA
     * object where RSA_size() works as expected.
     *
     * @param privateKey A PrivateKey instance, must implement RSAKey.
     * @return A byte buffer corresponding to the modulus. This is
     *         big-endian representation of a BigInteger.
     */
    @CalledByNative
    private static byte[] getRSAKeyModulus(PrivateKey privateKey) {
        if (privateKey instanceof RSAKey) {
            return ((RSAKey) privateKey).getModulus().toByteArray();
        }
        Log.w(TAG, "Not a RSAKey instance!");
        return null;
    }

    /**
     * Returns the 'order' parameter of a given ECDSA private key as a
     * a byte buffer.
     * @param privateKey A PrivateKey instance. Must implement ECKey.
     * @return A byte buffer corresponding to the 'order' parameter.
     * This is a big-endian representation of a BigInteger.
     */
    @CalledByNative
    private static byte[] getECKeyOrder(PrivateKey privateKey) {
        if (privateKey instanceof ECKey) {
            ECParameterSpec params = ((ECKey) privateKey).getParams();
            return params.getOrder().toByteArray();
        }
        Log.w(TAG, "Not an ECKey instance!");
        return null;
    }

    /**
     * Sign a given message with a given PrivateKey object. This method
     * shall only be used to implement signing in the context of SSL
     * client certificate support.
     *
     * The message will actually be a hash, computed by OpenSSL itself,
     * depending on the type of the key. The result should match exactly
     * what the vanilla implementations of the following OpenSSL function
     * calls do:
     *
     *  - For a RSA private key, this should be equivalent to calling
     *    RSA_private_encrypt(..., RSA_PKCS1_PADDING), i.e. it must
     *    generate a raw RSA signature. The message must be either a
     *    combined, 36-byte MD5+SHA1 message digest or a DigestInfo
     *    value wrapping a message digest.
     *
     *  - For a ECDSA private keys, this should be equivalent to calling
     *    ECDSA_sign(0,...). The message must be a hash and the function shall
     *    compute a direct ECDSA signature for it.
     *
     * @param privateKey The PrivateKey handle.
     * @param message The message to sign.
     * @return signature as a byte buffer.
     *
     * Important: Due to a platform bug, this function will always fail on
     *            Android < 4.2 for RSA PrivateKey objects. See the
     *            getOpenSSLHandleForPrivateKey() below for work-around.
     */
    @CalledByNative
    private static byte[] rawSignDigestWithPrivateKey(PrivateKey privateKey, byte[] message) {
        // Get the Signature for this key.
        Signature signature = null;
        // Hint: Algorithm names come from:
        // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
        try {
            String keyAlgorithm = privateKey.getAlgorithm();
            if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
                // IMPORTANT: Due to a platform bug, this will throw NoSuchAlgorithmException
                // on Android 4.1.x. Fixed in 4.2 and higher.
                // See https://android-review.googlesource.com/#/c/40352/
                signature = Signature.getInstance("NONEwithRSA");
            } else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
                signature = Signature.getInstance("NONEwithECDSA");
            }
        } catch (NoSuchAlgorithmException e) {
            // Intentionally do nothing.
        }

        if (signature == null) {
            Log.e(TAG, "Unsupported private key algorithm: " + privateKey.getAlgorithm());
            return null;
        }

        // Sign the message.
        try {
            signature.initSign(privateKey);
            signature.update(message);
            return signature.sign();
        } catch (Exception e) {
            Log.e(TAG, "Exception while signing message with " + privateKey.getAlgorithm()
                    + " private key: " + e);
            return null;
        }
    }

    /**
     * Return the type of a given PrivateKey object. This is an integer
     * that maps to one of the values defined by org.chromium.net.PrivateKeyType,
     * which is itself auto-generated from net/android/private_key_type_list.h
     * @param privateKey The PrivateKey handle
     * @return key type, or PrivateKeyType.INVALID if unknown.
     */
    @CalledByNative
    private static int getPrivateKeyType(PrivateKey privateKey) {
        String keyAlgorithm = privateKey.getAlgorithm();
        if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
            return PrivateKeyType.RSA;
        } else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
            return PrivateKeyType.ECDSA;
        } else {
            return PrivateKeyType.INVALID;
        }
    }

    private static Object getOpenSSLKeyForPrivateKey(PrivateKey privateKey) {
        // Sanity checks
        if (privateKey == null) {
            Log.e(TAG, "privateKey == null");
            return null;
        }
        if (!(privateKey instanceof RSAPrivateKey)) {
            Log.e(TAG, "does not implement RSAPrivateKey");
            return null;
        }
        // First, check that this is a proper instance of OpenSSLRSAPrivateKey
        // or one of its sub-classes.
        Class<?> superClass;
        try {
            superClass =
                    Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLRSAPrivateKey");
        } catch (Exception e) {
            // This may happen if the target device has a completely different
            // implementation of the java.security APIs, compared to vanilla
            // Android. Highly unlikely, but still possible.
            Log.e(TAG, "Cannot find system OpenSSLRSAPrivateKey class: " + e);
            return null;
        }
        if (!superClass.isInstance(privateKey)) {
            // This may happen if the PrivateKey was not created by the "AndroidOpenSSL"
            // provider, which should be the default. That could happen if an OEM decided
            // to implement a different default provider. Also highly unlikely.
            Log.e(TAG, "Private key is not an OpenSSLRSAPrivateKey instance, its class name is:"
                    + privateKey.getClass().getCanonicalName());
            return null;
        }

        try {
            // Use reflection to invoke the 'getOpenSSLKey()' method on the
            // private key. This returns another Java object that wraps a native
            // EVP_PKEY and OpenSSLEngine. Note that the method is final in Android
            // 4.1, so calling the superclass implementation is ok.
            Method getKey = superClass.getDeclaredMethod("getOpenSSLKey");
            getKey.setAccessible(true);
            Object opensslKey = null;
            try {
                opensslKey = getKey.invoke(privateKey);
            } finally {
                getKey.setAccessible(false);
            }
            if (opensslKey == null) {
                // Bail when detecting OEM "enhancement".
                Log.e(TAG, "getOpenSSLKey() returned null");
                return null;
            }
            return opensslKey;
        } catch (Exception e) {
            Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
            return null;
        }
    }

    /**
     * Return the system EVP_PKEY handle corresponding to a given PrivateKey
     * object.
     *
     * This shall only be used when the "NONEwithRSA" signature is not
     * available, as described in rawSignDigestWithPrivateKey(). I.e.
     * never use this on Android 4.2 or higher.
     *
     * This can only work in Android 4.0.4 and higher, for older versions
     * of the platform (e.g. 4.0.3), there is no system OpenSSL EVP_PKEY,
     * but the private key contents can be retrieved directly with
     * the getEncoded() method.
     *
     * This assumes that the target device uses a vanilla AOSP
     * implementation of its java.security classes, which is also
     * based on OpenSSL (fortunately, no OEM has apperently changed to
     * a different implementation, according to the Android team).
     *
     * Note that the object returned was created with the platform version of
     * OpenSSL, and _not_ the one that comes with Chromium. It may not be used
     * with the Chromium version of OpenSSL (BoringSSL). See AndroidEVP_PKEY in
     * net/android/legacy_openssl.h.
     *
     * To better understand what's going on below, please refer to the
     * following source files in the Android 4.0.4 and 4.1 source trees:
     * libcore/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLRSAPrivateKey.java
     * libcore/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
     *
     * @param privateKey The PrivateKey handle.
     * @return The EVP_PKEY handle, as a 32-bit integer (0 if not available)
     */
    @CalledByNative
    private static long getOpenSSLHandleForPrivateKey(PrivateKey privateKey) {
        Object opensslKey = getOpenSSLKeyForPrivateKey(privateKey);
        if (opensslKey == null) return 0;

        try {
            // Use reflection to invoke the 'getPkeyContext' method on the
            // result of the getOpenSSLKey(). This is an 32-bit integer
            // which is the address of an EVP_PKEY object. Note that this
            // method these days returns a 64-bit long, but since this code
            // path is used for older Android versions, it may still return
            // a 32-bit int here. To be on the safe side, we cast the return
            // value via Number rather than directly to Integer or Long.
            Method getPkeyContext;
            try {
                getPkeyContext = opensslKey.getClass().getDeclaredMethod("getPkeyContext");
            } catch (Exception e) {
                // Bail here too, something really not working as expected.
                Log.e(TAG, "No getPkeyContext() method on OpenSSLKey member:" + e);
                return 0;
            }
            getPkeyContext.setAccessible(true);
            long evp_pkey = 0;
            try {
                evp_pkey = ((Number) getPkeyContext.invoke(opensslKey)).longValue();
            } finally {
                getPkeyContext.setAccessible(false);
            }
            if (evp_pkey == 0) {
                // The PrivateKey is probably rotten for some reason.
                Log.e(TAG, "getPkeyContext() returned null");
            }
            return evp_pkey;

        } catch (Exception e) {
            Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
            return 0;
        }
    }

    /**
     * Return the OpenSSLEngine object corresponding to a given PrivateKey
     * object.
     *
     * This shall only be used for Android 4.1 to work around a platform bug.
     * See https://crbug.com/381465.
     *
     * @param privateKey The PrivateKey handle.
     * @return The OpenSSLEngine object (or null if not available)
     */
    @CalledByNative
    private static Object getOpenSSLEngineForPrivateKey(PrivateKey privateKey) {
        // Find the system OpenSSLEngine class.
        Class<?> engineClass;
        try {
            engineClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLEngine");
        } catch (Exception e) {
            // This may happen if the target device has a completely different
            // implementation of the java.security APIs, compared to vanilla
            // Android. Highly unlikely, but still possible.
            Log.e(TAG, "Cannot find system OpenSSLEngine class: " + e);
            return null;
        }

        Object opensslKey = getOpenSSLKeyForPrivateKey(privateKey);
        if (opensslKey == null) return null;

        try {
            // Use reflection to invoke the 'getEngine' method on the
            // result of the getOpenSSLKey().
            Method getEngine;
            try {
                getEngine = opensslKey.getClass().getDeclaredMethod("getEngine");
            } catch (Exception e) {
                // Bail here too, something really not working as expected.
                Log.e(TAG, "No getEngine() method on OpenSSLKey member:" + e);
                return null;
            }
            getEngine.setAccessible(true);
            Object engine = null;
            try {
                engine = getEngine.invoke(opensslKey);
            } finally {
                getEngine.setAccessible(false);
            }
            if (engine == null) {
                // The PrivateKey is probably rotten for some reason.
                Log.e(TAG, "getEngine() returned null");
            }
            // Sanity-check the returned engine.
            if (!engineClass.isInstance(engine)) {
                Log.e(TAG, "Engine is not an OpenSSLEngine instance, its class name is:"
                        + engine.getClass().getCanonicalName());
                return null;
            }
            return engine;

        } catch (Exception e) {
            Log.e(TAG, "Exception while trying to retrieve OpenSSLEngine object: " + e);
            return null;
        }
    }
}


text:
package com.yudeyang.vistor;

/**
 * Created by deyang on 2017/1/3.
 */
public class SecondReader implements NovelReader {
    @Override
    public void read(Hamlet hamlet) {
        System.out.println(this.getClass().getSimpleName()+" think "+hamlet.getName() +" is BAD!");
    }

    @Override
    public void read(RedAndBlack redAndBlack) {
        System.out.println(this.getClass().getSimpleName()+" think "+redAndBlack.getName() +" is BAD!");
    }
}


text:
package org.onosproject.net.intent;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.onosproject.core.ApplicationId;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Key class for Intents.
 */
// TODO maybe pull this up to utils
public abstract class Key {

    //TODO consider making this a HashCode object (worry about performance)
    private final long hash;
    private static final HashFunction HASH_FN = Hashing.md5();

    protected Key(long hash) {
        this.hash = hash;
    }

    public long hash() {
        return hash;
    }

    @Override
    public int hashCode() {
        return Long.hashCode(hash);
    }

    @Override
    public abstract boolean equals(Object obj);

    /**
     * Creates a key based on the provided string.
     *

     * Note: Two keys with equal value, but different appId, are not equal.
     *

     *
     * @param key the provided string
     * @param appId application id to associate with this key
     * @return the key for the string
     */
    public static Key of(String key, ApplicationId appId) {
        return new StringKey(key, appId);
    }

    /**
     * Creates a key based on the provided long.
     *

     * Note: Two keys with equal value, but different appId, are not equal.
     * Also, "10" and 10L are different.
     *

     *
     * @param key the provided long
     * @param appId application id to associate with this key
     * @return the key for the long
     */
    public static Key of(long key, ApplicationId appId) {
        return new LongKey(key, appId);
    }

    private static final class StringKey extends Key {

        private final ApplicationId appId;
        private final String key;

        private StringKey(String key, ApplicationId appId) {
            super(HASH_FN.newHasher()
                          .putShort(appId.id())
                          .putString(key, StandardCharsets.UTF_8)
                          .hash().asLong());
            this.key = key;
            this.appId = appId;
        }

        @Override
        public String toString() {
            return key;
        }

        // checkstyle requires this
        @Override
        public int hashCode() {
            return super.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || getClass() != obj.getClass()) {
                return false;
            }
            final StringKey other = (StringKey) obj;
            return this.hash() == other.hash() &&
                    Objects.equals(this.appId, other.appId) &&
                    Objects.equals(this.key, other.key);
        }
    }

    private static final class LongKey extends Key {

        private final ApplicationId appId;
        private final long key;

        private LongKey(long key, ApplicationId appId) {
            super(HASH_FN.newHasher()
                          .putShort(appId.id())
                          .putLong(key)
                          .hash().asLong());
            this.key = key;
            this.appId = appId;
        }

        @Override
        public String toString() {
            return "0x" + Long.toHexString(key);
        }

        // checkstyle requires this
        @Override
        public int hashCode() {
            return super.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || getClass() != obj.getClass()) {
                return false;
            }
            final LongKey other = (LongKey) obj;
            return this.hash() == other.hash() &&
                    this.key == other.key &&
                    Objects.equals(this.appId, other.appId);
        }
    }
}


text:
layout: page
title: Academic Work
---
***

## PhD Thesis ##

[**The Practicalities of Scaling Bayesian Neural Networks to Real-World Applications**](https://ora.ox.ac.uk/objects/uuid:4b738b70-28bc-4545-86a6-6078861e7d13)

"Adam D. Cobb"
University of Oxford 2020.

## Book Chapters

[**Toward Safe Decision-Making via Uncertainty Quantification in Machine Learning**](https://link.springer.com/chapter/10.1007/978-3-030-77283-3_19)

"Adam D. Cobb, Brian Jalaian, Nathaniel D. Bastian, Stephen Russell"
Systems Engineering and Artificial Intelligence 2021.

## Papers ##

[**Principal Component Flows**](https://arxiv.org/abs/2202.07037)

"Edmond Cunningham, Adam D. Cobb, Susmit Jha"
ICML 2022.

[**On Diverse System-Level Design Using Manifold Learning and Partial Simulated Annealing**](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/58C33505893DE15D2D6589E98C5F55BA/S2732527X22001560a.pdf/div-class-title-on-diverse-system-level-design-using-manifold-learning-and-partial-simulated-annealing-div.pdf)

"Adam D. Cobb, Anirban Roy, Daniel Elenius, Kaushik Koneripalli, Susmit Jha"
Proceedings of the Design Society (DESIGN) 2022.
 **Paper was in top 10 % of accepted conference papers.**

[**URSABench: A System for Comprehensive Benchmarking of Bayesian Deep Neural Network Models and Inference methods**](https://proceedings.mlsys.org/paper/2022/file/3ef815416f775098fe977004015c6193-Paper.pdf)

"Meet Vadera, Jinyang Li, Adam D. Cobb, Brian Jalaian, Tarek Abdelzaher, Benjamin Marlin"
Proceedings of Machine Learning and Systems (MLSys) 2022.

[**Can Sequential Bayesian Inference Solve Continual Learning?**](https://openreview.net/pdf?id=2Ann7eaLBEv)

"Samuel Kessler, Adam D. Cobb, Stefan Zohren, Stephen J. Roberts"
Fourth Symposium on Advances in Approximate Bayesian Inference 2022.

[**Robust decision-making in the internet of battlefield things using Bayesian neural networks**](https://dl.acm.org/doi/abs/10.5555/3522802.3522943)

"Adam D. Cobb, Brian A. Jalaian, Nathaniel D. Bastian, Stephen Russell"
Winter Simulation Conference (WSC) 2021.

[**HumBugDB: A Large-scale Acoustic Mosquito Dataset**](https://ieeexplore.ieee.org/abstract/document/9504792)

"Ivan Kiskin, Marianne Sinka, Adam D Cobb, Waqas Rafique, Lawrence Wang, Davide Zilli, Benjamin Gutteridge, Rinita Dam, Theodoros Marinos, Yunpeng Li, Dickson Msaky, Emmanuel Kaindoa, Gerard Killeen, Eva Herreros-Moya, Kathy J Willis, Stephen J Roberts"
Neural Information Processing Systems Track on Datasets and Benchmarks 2021.

[**Improving differential evolution through Bayesian hyperparameter optimization**](https://ieeexplore.ieee.org/abstract/document/9504792)

"Subhodip Biswas, Debanjan Saha, Shuvodeep De, Adam D Cobb, Swagatam Das, Brian Jalaian"
IEEE Congress on Evolutionary Computation (CEC) 2021.

[**Scaling Hamiltonian Monte Carlo Inference for Bayesian Neural Networks with Symmetric Splitting**](https://arxiv.org/pdf/2010.06772.pdf)

"Adam D. Cobb, Brian Jalaian"
UAI 2021.

[**BayesOpt Adversarial Attack**](https://openreview.net/forum?id=Hkem-lrtvH)

"Binxin Ru, Adam D. Cobb, Arno Blaas, Yarin Gal"
ICLR 2020.

[**Semi-separable Hamiltonian Monte Carlo for inference in Bayesian neural networks**](http://bayesiandeeplearning.org/2019/papers/21.pdf)

"Adam D. Cobb, Atılım Güneş Baydin, Ivan Kiskin, Andrew Markham, Stephen J. Roberts"
Fourth workshop on Bayesian Deep Learning (NeurIPS 2019), Vancouver, Canada.

[**Introducing an Explicit Symplectic Integration Scheme for Riemannian Manifold Hamiltonian Monte Carlo**](https://arxiv.org/pdf/1910.06243.pdf)

"Adam D. Cobb, Atılım Güneş Baydin, Andrew Markham, Stephen J. Roberts"
Under review.

[**An Ensemble of Bayesian Neural Networks for Exoplanetary Atmospheric Retrieval**](https://arxiv.org/pdf/1905.10659.pdf)

"Adam D. Cobb, Michael D. Himes, Frank Soboczenski, Simone Zorzan, Molly D. O'Beirne, Atılım Güneş Baydin, Yarin Gal, Shawn D. Domagal-Goldman, Giada N. Arney, Daniel Angerhausen"
The Astronomical Journal, 2019.

[**Optimising Worlds to Evaluate and Influence Reinforcement Learning Agents**]({{ site.url }}/documents/Everett_World_Agent.pdf)

"Richard Everett, Adam Cobb, Andrew Markham, Stephen Roberts"
Proceedings of the 18th International Conference on Autonomous Agents and MultiAgent Systems.

[**Bayesian deep neural networks for low-cost neurophysiological markers of Alzheimer's disease severity**](https://arxiv.org/pdf/1812.04994.pdf)

"Wolfgang Fruehwirt, Adam D. Cobb, Martin Mairhofer, Leonard Weydemann, Heinrich Garn, Reinhold Schmidt, Thomas Benke, Peter Dal-Bianco, Gerhard Ransmayr, Markus Waser, Dieter Grossegger, Pengfei Zhang, Georg Dorffner, Stephen Roberts"
Machine Learning for Health (ML4H) Workshop at NeurIPS 2018.

[**Bayesian Deep Learning for Exoplanet Atmospheric Retrieval**](https://arxiv.org/pdf/1811.03390.pdf)

"Frank Soboczenski, Michael D. Himes, Molly D. O'Beirne, Simone Zorzan, Atılım Güneş Baydin, Adam D. Cobb, Yarin Gal, Daniel Angerhausen, Massimo Mascaro, Giada N. Arney, Shawn D. Domagal-Goldman"
Third workshop on Bayesian Deep Learning (NeurIPS 2018), Montreal, Canada.

[**Scalable Bounding of Predictive Uncertainty in Regression Problems with SLAC**]({{ site.url }}/documents/Blaas2018_Chapter_ScalableBoundingOfPredictiveUn.pdf)

"Arno Blaas, Adam D. Cobb, Jan-Peter Calliess, Stephen J. Roberts"
International Conference on Scalable Uncertainty Management, Sep 2018.

[**Loss-Calibrated Approximate Inference in Bayesian Neural Networks**]({{ site.url }}/documents/Cobb2018_LCBNN.pdf)

"Adam D. Cobb, Stephen J. Roberts, Yarin Gal"
Theory of deep learning workshop, ICML, May 2018. [Code](https://github.com/AdamCobb/LCBNN)

[**Identifying Sources and Sinks in the Presence of Multiple Agents with Gaussian Process Vector Calculus**]({{ site.url }}/documents/Cobb2018_GP_vec_calc.pdf)

"Adam D. Cobb, Richard Everett, Andrew Markham, Stephen J. Roberts"
Accepted KDD 2018. [Code](https://github.com/AdamCobb/GP-LAPLACE) Video

[**Learning from lions: inferring the utility of agents from their trajectories**]({{ site.url }}/documents/Cobb2017_Learning_from_lions.pdf)

"Adam D. Cobb, Andrew Markham, Stephen J. Roberts"
September 2017. Paper

[**Adaptive sampling of lion accelerometer data**]({{ site.url }}/documents/Cobb2016_lion_acc.pdf)

"Adam D. Cobb, Andrew Markham"
September 2016. CDT in AIMS mini-project

[**Active sampling to increase the battery life of mosquito-detecting sensor networks**]({{ site.url }}/documents/Cobb2016_mosq.pdf)

"Adam D. Cobb, Stephen J. Roberts"
June 2016. CDT in AIMS mini-project

[**Exoplanet Detection in Large Astronomical Data Sets**]({{ site.url }}/documents/Cobb2015_exoplanet.pdf)

"Adam D. Cobb, Stephen J. Roberts"
June 2015. Master's Thesis

## Presentations ##

Our final presentation on modelling the 3D shapes of asteroids during [NASA FDL 2017](http://www.frontierdevelopmentlab.org/#/).

## Additional Paper Materials ##

A high level video summarising our paper [**Identifying Sources and Sinks in the Presence of Multiple Agents with Gaussian Process Vector Calculus**]({{ site.url }}/documents/Cobb2018_GP_vec_calc.pdf). Submitted to KDD 2018 video competition.


text:
cask "opera-developer" do
  version "83.0.4232.0"
  sha256 "9822fb4cab3fca9187b6bde5dea93b6ffc5add05976003859669abaf381a1bfc"

  url "https://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg"
  name "Opera Developer"
  desc "Web browser"
  homepage "https://www.opera.com/computer/beta"

  livecheck do
    url "https://get.geo.opera.com/pub/opera-developer/"
    strategy :page_match
    regex(/href="(\d+(?:\.\d+)+)/i)
  end

  auto_updates true

  app "Opera Developer.app"

  zap trash: [
    "~/Library/Application Support/com.operasoftware.OperaDeveloper",
    "~/Library/Caches/com.operasoftware.OperaDeveloper",
    "~/Library/Cookies/com.operasoftware.OperaDeveloper.binarycookies",
    "~/Library/Preferences/com.operasoftware.OperaDeveloper.plist",
    "~/Library/Saved Application State/com.operasoftware.OperaDeveloper.savedState",
  ]
end


text:
cask 'navicat-for-sql-server' do
  version '15.0.15'
  sha256 '3d61a5e507ce8f17f71b065f7a37eac5639b14b7f2b1d73810d7112028e370d6'

  url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_sqlserver_en.dmg"
  appcast 'https://updater.navicat.com/mac/navicat_updates.php?appName=Navicat%20for%20SQL%20Server&appLang=en'
  name 'Navicat for SQL Server'
  homepage 'https://www.navicat.com/products/navicat-for-sqlserver'

  app 'Navicat For SQL Server.app'
end


text:
Function with Dependencies

If your function depends on library(ies), thread needs to know path to the library(ies).

//function "_.union()" belongs to "Underscore" library.
function bar(arr1,arr2){
	return _.union(arr1,arr2);
}

<input type="button" value="Run in Page" onclick="run_bar()" />

	<input value="clear" type="button" onclick="document.getElementById('demo_result').innerHTML =''"/>

var foo = bar([1,2,3],[2,3,4]);

console.log(foo);

	<input type="button" value="Run in Thread" onclick="run_bar_in_thread()" />

	<input value="clear"  type="button"  onclick="document.getElementById('demo_result_thread').innerHTML =''"/>

/* Callback style */
vkthread.exec(bar, //function to run in a thread;
		[[1,2,3],[2,3,4]], //arguments for the function;
		function(data){ // callback function;
			var foo = data;
			console.log(foo);
		},
		['../js/underscore-min.js'] /* dependency */
	);

/* Promise style */
vkthread.run(bar, //function to run in a thread;
	    [[1,2,3],[2,3,4]], //arguments for the function;
	    ['../js/underscore-min.js'] /* dependency */
	).then(function(data){
		var foo = data;
		console.log(foo);
	});


text:
import "@tsed/ajv";
import {BodyParams, Controller, Err, Get, Middleware, PlatformTest, Post, UseAfter} from "@tsed/common";
import {Env} from "@tsed/core";
import {BadRequest, InternalServerError} from "@tsed/exceptions";
import {Description, Name, Required, Returns, Summary} from "@tsed/schema";
import {expect} from "chai";
import SuperTest from "supertest";
import {CustomBadRequest} from "../errors/CustomBadRequest";
import {CustomInternalError} from "../errors/CustomInternalError";
import {PlatformTestOptions} from "../interfaces";

class CustomModel {
  @Required() name: string;
}

class CustomPropModel {
  @Name("role_item")
  @Required()
  roleItem: string;
}

@Middleware()
class ErrorMiddleware {
  use(@Err() error: any) {
    return {
      message: "no error"
    };
  }
}

@Middleware()
class FakeMiddleware {
  use() {
    return {
      message: "should not be called by the platform when endpoint throw an error"
    };
  }
}

@Controller("/errors")
export class ErrorsCtrl {
  @Get("/scenario-1")
  @(Returns(500, InternalServerError).Description("Custom Bad Request"))
  public scenario1() {
    throw new CustomBadRequest("Custom Bad Request");
  }

  @Get("/scenario-2")
  @(Returns(500).Description("Internal Server Error"))
  public scenario2() {
    throw new Error("My error");
  }

  @Get("/scenario-3")
  @(Returns(400, CustomInternalError).Description("Bad request"))
  public scenario3() {
    throw new CustomInternalError("My custom error");
  }

  @Post("/scenario-4")
  @Returns(400)
  public scenario4(@Required() @BodyParams("name") name: string) {
    return name;
  }

  @Post("/scenario-5")
  @(Returns(400, BadRequest).Description("Bad request"))
  public scenario5(
    @Required()
    @BodyParams()
    model: CustomModel
  ) {
    return model;
  }

  @Post("/scenario-6")
  @Summary("Throw a Required prop if prop name is required")
  @Description(`Return a required error`)
  @(Returns(400).Description("Bad request"))
  public scenario6(
    @Required()
    @BodyParams()
    model: CustomPropModel
  ) {
    return model;
  }

  @Get("/scenario-7")
  @(Returns(400).Description("Bad request"))
  @UseAfter(FakeMiddleware)
  @UseAfter(ErrorMiddleware)
  public scenario7() {
    throw new CustomInternalError("My custom error");
  }
}

export function testErrors(options: PlatformTestOptions) {
  let request: SuperTest.SuperTest<SuperTest.Test>;
  before(
    PlatformTest.bootstrap(options.server, {
      ...options,
      env: Env.TEST,
      mount: {
        "/rest": [ErrorsCtrl]
      }
    })
  );
  before(() => {
    request = SuperTest(PlatformTest.callback());
  });
  after(PlatformTest.reset);

  it("Scenario 1: GET /rest/errors/scenario-1", async () => {
    const response: any = await request.get("/rest/errors/scenario-1").expect(400);

    expect(response.headers["x-header-error"]).to.eq("deny");
    expect(response.body).to.deep.eq({
      name: "CUSTOM_BAD_REQUEST",
      message: "Custom Bad Request",
      status: 400,
      errors: ["test"]
    });
  });

  it("Scenario 2: GET /rest/errors/scenario-2", async () => {
    const response: any = await request.get("/rest/errors/scenario-2").expect(500);

    expect(response.body).to.deep.eq({
      errors: [],
      message: "My error",
      name: "Error",
      status: 500
    });
  });

  it("Scenario 3: GET /rest/errors/scenario-3", async () => {
    const response: any = await request.get("/rest/errors/scenario-3").expect(500);

    expect(response.headers["x-header-error"]).to.eq("deny");
    expect(response.body).to.deep.eq({
      name: "CUSTOM_INTERNAL_SERVER_ERROR",
      message: "My custom error",
      status: 500,
      errors: ["test"]
    });
  });

  it("Scenario 4: POST /rest/errors/scenario-4", async () => {
    const response: any = await request.post("/rest/errors/scenario-4").expect(400);

    expect(response.body).to.deep.eq({
      errors: [
        {
          dataPath: "",
          keyword: "required",
          message: "It should have required parameter 'name'",
          modelName: "body",
          params: {
            missingProperty: "name"
          },
          schemaPath: "#/required"
        }
      ],
      message: "Bad request on parameter \"request.body.name\".\nIt should have required parameter 'name'",
      name: "REQUIRED_VALIDATION_ERROR",
      status: 400
    });
  });

  it("Scenario 5: POST /rest/errors/scenario-5", async () => {
    const response: any = await request.post("/rest/errors/scenario-5").expect(400);

    expect(response.body).to.deep.eq({
      errors: [
        {
          dataPath: "",
          instancePath: "",
          keyword: "required",
          message: "must have required property 'name'",
          modelName: "CustomModel",
          params: {
            missingProperty: "name"
          },
          schemaPath: "#/required"
        }
      ],
      message: 'Bad request on parameter "request.body".\nCustomModel must have required property \'name\'. Given value: "undefined"',
      name: "AJV_VALIDATION_ERROR",
      status: 400
    });
  });

  it("Scenario 6: POST /rest/errors/scenario-6", async () => {
    const response: any = await request.post(`/rest/errors/scenario-6`).send({}).expect(400);

    expect(response.body).to.deep.eq({
      errors: [
        {
          dataPath: "",
          instancePath: "",
          keyword: "required",
          message: "must have required property 'role_item'",
          modelName: "CustomPropModel",
          params: {
            missingProperty: "role_item"
          },
          schemaPath: "#/required"
        }
      ],
      message:
        'Bad request on parameter "request.body".\nCustomPropModel must have required property \'role_item\'. Given value: "undefined"',
      name: "AJV_VALIDATION_ERROR",
      status: 400
    });
  });

  it("Scenario 7: GET /rest/errors/scenario-7", async () => {
    const response: any = await request.get("/rest/errors/scenario-7").expect(200);

    expect(response.body).to.deep.eq({
      message: "no error"
    });
  });
}


text:
<?php
// WARNING, this is a read only file created by import scripts
// WARNING
// WARNING,  Changes made to this file will be clobbered
// WARNING
// WARNING,  Please make changes on poeditor instead of here
//
//
?>
En gjeste-invitasjon gir tilgang til tjenesten for å sende en fil.

Skriv inn epost-adressen til gjesten og klikk på Send invitasjon. En epost vil bli sendt med en lenke som gir gjesten mulighet til å sende 1 fil.


text:
/*
 * DLCI		Implementation of Frame Relay protocol for Linux, according to
 *		RFC 1490.  This generic device provides en/decapsulation for an
 *		underlying hardware driver.  Routes & IPs are assigned to these
 *		interfaces.  Requires 'dlcicfg' program to create usable
 *		interfaces, the initial one, 'dlci' is for IOCTL use only.
 *
 * Version:	@(#)dlci.c	0.35	4 Jan 1997
 *
 * Author:	Mike McLagan <mike.mclagan@linux.org>
 *
 * Changes:
 *
 *		0.15	Mike Mclagan	Packet freeing, bug in kmalloc call
 *					DLCI_RET handling
 *		0.20	Mike McLagan	More conservative on which packets
 *					are returned for retry and which are
 *					are dropped.  If DLCI_RET_DROP is
 *					returned from the FRAD, the packet is
 *				 	sent back to Linux for re-transmission
 *		0.25	Mike McLagan	Converted to use SIOC IOCTL calls
 *		0.30	Jim Freeman	Fixed to allow IPX traffic
 *		0.35	Michael Elizabeth	Fixed incorrect memcpy_fromfs
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 */

#include <linux/config.h> /* for CONFIG_DLCI_COUNT */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/if_frad.h>
#include <linux/bitops.h>

#include <net/sock.h>

#include <asm/system.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/uaccess.h>

static const char version[] = "DLCI driver v0.35, 4 Jan 1997, mike.mclagan@linux.org";

static LIST_HEAD(dlci_devs);

static void dlci_setup(struct net_device *);

/*
 * these encapsulate the RFC 1490 requirements as well as
 * deal with packet transmission and reception, working with
 * the upper network layers
 */

static int dlci_header(struct sk_buff *skb, struct net_device *dev,
                           unsigned short type, void *daddr, void *saddr,
                           unsigned len)
{
	struct frhdr		hdr;
	struct dlci_local	*dlp;
	unsigned int		hlen;
	char			*dest;

	dlp = dev->priv;

	hdr.control = FRAD_I_UI;
	switch(type)
	{
		case ETH_P_IP:
			hdr.IP_NLPID = FRAD_P_IP;
			hlen = sizeof(hdr.control) + sizeof(hdr.IP_NLPID);
			break;

		/* feel free to add other types, if necessary */

		default:
			hdr.pad = FRAD_P_PADDING;
			hdr.NLPID = FRAD_P_SNAP;
			memset(hdr.OUI, 0, sizeof(hdr.OUI));
			hdr.PID = htons(type);
			hlen = sizeof(hdr);
			break;
	}

	dest = skb_push(skb, hlen);
	if (!dest)
		return(0);

	memcpy(dest, &hdr, hlen);

	return(hlen);
}

static void dlci_receive(struct sk_buff *skb, struct net_device *dev)
{
	struct dlci_local *dlp;
	struct frhdr		*hdr;
	int					process, header;

	dlp = dev->priv;
	if (!pskb_may_pull(skb, sizeof(*hdr))) {
		printk(KERN_NOTICE "%s: invalid data no header\n",
		       dev->name);
		dlp->stats.rx_errors++;
		kfree_skb(skb);
		return;
	}

	hdr = (struct frhdr *) skb->data;
	process = 0;
	header = 0;
	skb->dev = dev;

	if (hdr->control != FRAD_I_UI)
	{
		printk(KERN_NOTICE "%s: Invalid header flag 0x%02X.\n", dev->name, hdr->control);
		dlp->stats.rx_errors++;
	}
	else
		switch(hdr->IP_NLPID)
		{
			case FRAD_P_PADDING:
				if (hdr->NLPID != FRAD_P_SNAP)
				{
					printk(KERN_NOTICE "%s: Unsupported NLPID 0x%02X.\n", dev->name, hdr->NLPID);
					dlp->stats.rx_errors++;
					break;
				}

				if (hdr->OUI[0] + hdr->OUI[1] + hdr->OUI[2] != 0)
				{
					printk(KERN_NOTICE "%s: Unsupported organizationally unique identifier 0x%02X-%02X-%02X.\n", dev->name, hdr->OUI[0], hdr->OUI[1], hdr->OUI[2]);
					dlp->stats.rx_errors++;
					break;
				}

				/* at this point, it's an EtherType frame */
				header = sizeof(struct frhdr);
				/* Already in network order ! */
				skb->protocol = hdr->PID;
				process = 1;
				break;

			case FRAD_P_IP:
				header = sizeof(hdr->control) + sizeof(hdr->IP_NLPID);
				skb->protocol = htons(ETH_P_IP);
				process = 1;
				break;

			case FRAD_P_SNAP:
			case FRAD_P_Q933:
			case FRAD_P_CLNP:
				printk(KERN_NOTICE "%s: Unsupported NLPID 0x%02X.\n", dev->name, hdr->pad);
				dlp->stats.rx_errors++;
				break;

			default:
				printk(KERN_NOTICE "%s: Invalid pad byte 0x%02X.\n", dev->name, hdr->pad);
				dlp->stats.rx_errors++;
				break;
		}

	if (process)
	{
		/* we've set up the protocol, so discard the header */
		skb->mac.raw = skb->data;
		skb_pull(skb, header);
		dlp->stats.rx_bytes += skb->len;
		netif_rx(skb);
		dlp->stats.rx_packets++;
		dev->last_rx = jiffies;
	}
	else
		dev_kfree_skb(skb);
}

static int dlci_transmit(struct sk_buff *skb, struct net_device *dev)
{
	struct dlci_local *dlp;
	int					ret;

	ret = 0;

	if (!skb || !dev)
		return(0);

	dlp = dev->priv;

	netif_stop_queue(dev);

	ret = dlp->slave->hard_start_xmit(skb, dlp->slave);
	switch (ret)
	{
		case DLCI_RET_OK:
			dlp->stats.tx_packets++;
			ret = 0;
			break;
			case DLCI_RET_ERR:
			dlp->stats.tx_errors++;
			ret = 0;
			break;
			case DLCI_RET_DROP:
			dlp->stats.tx_dropped++;
			ret = 1;
			break;
	}
	/* Alan Cox recommends always returning 0, and always freeing the packet */
	/* experience suggest a slightly more conservative approach */

	if (!ret)
	{
		dev_kfree_skb(skb);
		netif_wake_queue(dev);
	}
	return(ret);
}

static int dlci_config(struct net_device *dev, struct dlci_conf __user *conf, int get)
{
	struct dlci_conf	config;
	struct dlci_local	*dlp;
	struct frad_local	*flp;
	int			err;

	dlp = dev->priv;

	flp = dlp->slave->priv;

	if (!get)
	{
		if(copy_from_user(&config, conf, sizeof(struct dlci_conf)))
			return -EFAULT;
		if (config.flags & ~DLCI_VALID_FLAGS)
			return(-EINVAL);
		memcpy(&dlp->config, &config, sizeof(struct dlci_conf));
		dlp->configured = 1;
	}

	err = (*flp->dlci_conf)(dlp->slave, dev, get);
	if (err)
		return(err);

	if (get)
	{
		if(copy_to_user(conf, &dlp->config, sizeof(struct dlci_conf)))
			return -EFAULT;
	}

	return(0);
}

static int dlci_dev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
	struct dlci_local *dlp;

	if (!capable(CAP_NET_ADMIN))
		return(-EPERM);

	dlp = dev->priv;

	switch(cmd)
	{
		case DLCI_GET_SLAVE:
			if (!*(short *)(dev->dev_addr))
				return(-EINVAL);

			strncpy(ifr->ifr_slave, dlp->slave->name, sizeof(ifr->ifr_slave));
			break;

		case DLCI_GET_CONF:
		case DLCI_SET_CONF:
			if (!*(short *)(dev->dev_addr))
				return(-EINVAL);

			return(dlci_config(dev, ifr->ifr_data, cmd == DLCI_GET_CONF));
			break;

		default:
			return(-EOPNOTSUPP);
	}
	return(0);
}

static int dlci_change_mtu(struct net_device *dev, int new_mtu)
{
	struct dlci_local *dlp;

	dlp = dev->priv;

	return((*dlp->slave->change_mtu)(dlp->slave, new_mtu));
}

static int dlci_open(struct net_device *dev)
{
	struct dlci_local	*dlp;
	struct frad_local	*flp;
	int			err;

	dlp = dev->priv;

	if (!*(short *)(dev->dev_addr))
		return(-EINVAL);

	if (!netif_running(dlp->slave))
		return(-ENOTCONN);

	flp = dlp->slave->priv;
	err = (*flp->activate)(dlp->slave, dev);
	if (err)
		return(err);

	netif_start_queue(dev);

	return 0;
}

static int dlci_close(struct net_device *dev)
{
	struct dlci_local	*dlp;
	struct frad_local	*flp;
	int			err;

	netif_stop_queue(dev);

	dlp = dev->priv;

	flp = dlp->slave->priv;
	err = (*flp->deactivate)(dlp->slave, dev);

	return 0;
}

static struct net_device_stats *dlci_get_stats(struct net_device *dev)
{
	struct dlci_local *dlp;

	dlp = dev->priv;

	return(&dlp->stats);
}

static int dlci_add(struct dlci_add *dlci)
{
	struct net_device	*master, *slave;
	struct dlci_local	*dlp;
	struct frad_local	*flp;
	int			err = -EINVAL;

	/* validate slave device */
	slave = dev_get_by_name(dlci->devname);
	if (!slave)
		return -ENODEV;

	if (slave->type != ARPHRD_FRAD || slave->priv == NULL)
		goto err1;

	/* create device name */
	master = alloc_netdev( sizeof(struct dlci_local), "dlci%d",
			      dlci_setup);
	if (!master) {
		err = -ENOMEM;
		goto err1;
	}

	/* make sure same slave not already registered */
	rtnl_lock();
	list_for_each_entry(dlp, &dlci_devs, list) {
		if (dlp->slave == slave) {
			err = -EBUSY;
			goto err2;
		}
	}

	err = dev_alloc_name(master, master->name);
	if (err < 0)
		goto err2;

	*(short *)(master->dev_addr) = dlci->dlci;

	dlp = (struct dlci_local *) master->priv;
	dlp->slave = slave;
	dlp->master = master;

	flp = slave->priv;
	err = (*flp->assoc)(slave, master);
	if (err < 0)
		goto err2;

	err = register_netdevice(master);
	if (err < 0)
		goto err2;

	strcpy(dlci->devname, master->name);

	list_add(&dlp->list, &dlci_devs);
	rtnl_unlock();

	return(0);

 err2:
	rtnl_unlock();
	free_netdev(master);
 err1:
	dev_put(slave);
	return(err);
}

static int dlci_del(struct dlci_add *dlci)
{
	struct dlci_local	*dlp;
	struct frad_local	*flp;
	struct net_device	*master, *slave;
	int			err;

	/* validate slave device */
	master = __dev_get_by_name(dlci->devname);
	if (!master)
		return(-ENODEV);

	if (netif_running(master)) {
		return(-EBUSY);
	}

	dlp = master->priv;
	slave = dlp->slave;
	flp = slave->priv;

	rtnl_lock();
	err = (*flp->deassoc)(slave, master);
	if (!err) {
		list_del(&dlp->list);

		unregister_netdevice(master);

		dev_put(slave);
	}
	rtnl_unlock();

	return(err);
}

static int dlci_ioctl(unsigned int cmd, void __user *arg)
{
	struct dlci_add add;
	int err;

	if (!capable(CAP_NET_ADMIN))
		return(-EPERM);

	if(copy_from_user(&add, arg, sizeof(struct dlci_add)))
		return -EFAULT;

	switch (cmd)
	{
		case SIOCADDDLCI:
			err = dlci_add(&add);

			if (!err)
				if(copy_to_user(arg, &add, sizeof(struct dlci_add)))
					return -EFAULT;
			break;

		case SIOCDELDLCI:
			err = dlci_del(&add);
			break;

		default:
			err = -EINVAL;
	}

	return(err);
}

static void dlci_setup(struct net_device *dev)
{
	struct dlci_local *dlp = dev->priv;

	dev->flags		= 0;
	dev->open		= dlci_open;
	dev->stop		= dlci_close;
	dev->do_ioctl		= dlci_dev_ioctl;
	dev->hard_start_xmit	= dlci_transmit;
	dev->hard_header	= dlci_header;
	dev->get_stats		= dlci_get_stats;
	dev->change_mtu		= dlci_change_mtu;
	dev->destructor		= free_netdev;

	dlp->receive		= dlci_receive;

	dev->type		= ARPHRD_DLCI;
	dev->hard_header_len	= sizeof(struct frhdr);
	dev->addr_len		= sizeof(short);

}

/* if slave is unregistering, then cleanup master */
static int dlci_dev_event(struct notifier_block *unused,
			  unsigned long event, void *ptr)
{
	struct net_device *dev = (struct net_device *) ptr;

	if (event == NETDEV_UNREGISTER) {
		struct dlci_local *dlp;

		list_for_each_entry(dlp, &dlci_devs, list) {
			if (dlp->slave == dev) {
				list_del(&dlp->list);
				unregister_netdevice(dlp->master);
				dev_put(dlp->slave);
				break;
			}
		}
	}
	return NOTIFY_DONE;
}

static struct notifier_block dlci_notifier = {
	.notifier_call = dlci_dev_event,
};

static int __init init_dlci(void)
{
	dlci_ioctl_set(dlci_ioctl);
	register_netdevice_notifier(&dlci_notifier);

	printk("%s.\n", version);

	return 0;
}

static void __exit dlci_exit(void)
{
	struct dlci_local	*dlp, *nxt;

	dlci_ioctl_set(NULL);
	unregister_netdevice_notifier(&dlci_notifier);

	rtnl_lock();
	list_for_each_entry_safe(dlp, nxt, &dlci_devs, list) {
		unregister_netdevice(dlp->master);
		dev_put(dlp->slave);
	}
	rtnl_unlock();
}

module_init(init_dlci);
module_exit(dlci_exit);

MODULE_AUTHOR("Mike McLagan");
MODULE_DESCRIPTION("Frame Relay DLCI layer");
MODULE_LICENSE("GPL");


text:
package io.netty.handler.codec.compression;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ThreadLocalRandom;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import static org.junit.Assert.*;

public abstract class ZlibTest {

    private static final byte[] BYTES_SMALL = new byte[128];
    private static final byte[] BYTES_LARGE = new byte[1024 * 1024];
    static {
        ThreadLocalRandom rand = ThreadLocalRandom.current();
        rand.nextBytes(BYTES_SMALL);
        rand.nextBytes(BYTES_LARGE);
    }

    protected abstract ZlibEncoder createEncoder(ZlibWrapper wrapper);
    protected abstract ZlibDecoder createDecoder(ZlibWrapper wrapper);

    @Test
    public void testGZIP2() throws Exception {
        ByteBuf data = Unpooled.wrappedBuffer("message".getBytes(CharsetUtil.UTF_8));
        ByteBuf deflatedData = Unpooled.wrappedBuffer(gzip("message"));

        EmbeddedChannel chDecoderGZip = new EmbeddedChannel(createDecoder(ZlibWrapper.GZIP));
        chDecoderGZip.writeInbound(deflatedData.copy());
        assertTrue(chDecoderGZip.finish());
        ByteBuf buf = chDecoderGZip.readInbound();
        assertEquals(buf, data);
        assertNull(chDecoderGZip.readInbound());
        data.release();
        deflatedData.release();
        buf.release();
    }

    private void testCompress0(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper, byte[] bytes) throws Exception {
        ByteBuf data = Unpooled.wrappedBuffer(bytes);
        EmbeddedChannel chEncoder = new EmbeddedChannel(createEncoder(encoderWrapper));

        chEncoder.writeOutbound(data.copy());
        chEncoder.flush();

        EmbeddedChannel chDecoderZlib = new EmbeddedChannel(createDecoder(decoderWrapper));
        for (;;) {
            ByteBuf deflatedData = chEncoder.readOutbound();
            if (deflatedData == null) {
                break;
            }
            chDecoderZlib.writeInbound(deflatedData);
        }

        byte[] decompressed = new byte[bytes.length];
        int offset = 0;
        for (;;) {
            ByteBuf buf = chDecoderZlib.readInbound();
            if (buf == null) {
                break;
            }
            int length = buf.readableBytes();
            buf.readBytes(decompressed, offset, length);
            offset += length;
            buf.release();
            if (offset == decompressed.length) {
                break;
            }
        }
        assertArrayEquals(bytes, decompressed);
        assertNull(chDecoderZlib.readInbound());

        // Closing an encoder channel will generate a footer.
        assertTrue(chEncoder.finish());
        for (;;) {
            Object msg = chEncoder.readOutbound();
            if (msg == null) {
                break;
            }
            ReferenceCountUtil.release(msg);
        }
        // But, the footer will be decoded into nothing. It's only for validation.
        assertFalse(chDecoderZlib.finish());

        data.release();
    }

    private void testCompressNone(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper) throws Exception {
        EmbeddedChannel chEncoder = new EmbeddedChannel(createEncoder(encoderWrapper));

        // Closing an encoder channel without writing anything should generate both header and footer.
        assertTrue(chEncoder.finish());

        EmbeddedChannel chDecoderZlib = new EmbeddedChannel(createDecoder(decoderWrapper));
        for (;;) {
            ByteBuf deflatedData = chEncoder.readOutbound();
            if (deflatedData == null) {
                break;
            }
            chDecoderZlib.writeInbound(deflatedData);
        }

        // Decoder should not generate anything at all.
        for (;;) {
            ByteBuf buf = chDecoderZlib.readInbound();
            if (buf == null) {
                break;
            }

            buf.release();
            fail("should decode nothing");
        }

        assertFalse(chDecoderZlib.finish());
    }

    private void testCompressSmall(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper) throws Exception {
        testCompress0(encoderWrapper, decoderWrapper, BYTES_SMALL);
    }

    private void testCompressLarge(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper) throws Exception {
        testCompress0(encoderWrapper, decoderWrapper, BYTES_LARGE);
    }

    @Test
    public void testZLIB() throws Exception {
        testCompressNone(ZlibWrapper.ZLIB, ZlibWrapper.ZLIB);
        testCompressSmall(ZlibWrapper.ZLIB, ZlibWrapper.ZLIB);
        testCompressLarge(ZlibWrapper.ZLIB, ZlibWrapper.ZLIB);
    }

    @Test
    public void testNONE() throws Exception {
        testCompressNone(ZlibWrapper.NONE, ZlibWrapper.NONE);
        testCompressSmall(ZlibWrapper.NONE, ZlibWrapper.NONE);
        testCompressLarge(ZlibWrapper.NONE, ZlibWrapper.NONE);
    }

    @Test
    public void testGZIP() throws Exception {
        testCompressNone(ZlibWrapper.GZIP, ZlibWrapper.GZIP);
        testCompressSmall(ZlibWrapper.GZIP, ZlibWrapper.GZIP);
        testCompressLarge(ZlibWrapper.GZIP, ZlibWrapper.GZIP);
    }

    @Test
    public void testZLIB_OR_NONE() throws Exception {
        testCompressNone(ZlibWrapper.NONE, ZlibWrapper.ZLIB_OR_NONE);
        testCompressSmall(ZlibWrapper.NONE, ZlibWrapper.ZLIB_OR_NONE);
        testCompressLarge(ZlibWrapper.NONE, ZlibWrapper.ZLIB_OR_NONE);
    }

    @Test
    public void testZLIB_OR_NONE2() throws Exception {
        testCompressNone(ZlibWrapper.ZLIB, ZlibWrapper.ZLIB_OR_NONE);
        testCompressSmall(ZlibWrapper.ZLIB, ZlibWrapper.ZLIB_OR_NONE);
        testCompressLarge(ZlibWrapper.GZIP, ZlibWrapper.ZLIB_OR_NONE);
    }

    @Test
    public void testZLIB_OR_NONE3() throws Exception {
        testCompressNone(ZlibWrapper.GZIP, ZlibWrapper.ZLIB_OR_NONE);
        testCompressSmall(ZlibWrapper.GZIP, ZlibWrapper.ZLIB_OR_NONE);
        testCompressLarge(ZlibWrapper.GZIP, ZlibWrapper.ZLIB_OR_NONE);
    }

    private static byte[] gzip(String message) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream stream = new GZIPOutputStream(out);
        stream.write(message.getBytes(CharsetUtil.UTF_8));
        stream.close();
        return out.toByteArray();
    }

}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('swiper-container',
                   'Integration | Component | swiper-container',
                   { integration: true });

test('it doesn\'t allow inline rendering', function(assert) {
  this.render(hbs`{{swiper-container}}`);

  assert.equal(this.$().text().trim(),
               `This component only support block rendering, inline rendering will be useless.
    这个组件仅支持块级方式渲染,内联方式渲染将毫无作用。`,
               'inline rendering should print out friendly warning');
});

test('it provides the basic required html structures', function(assert) {
  this.render(hbs`
    {{#swiper-container}}

anything

    {{/swiper-container}}
  `);

  const $component = this.$(':first-child');

  assert.ok($component.hasClass('swiper-container'),
            '.swiper-container should be existed on 1st level div');
  assert.ok($component.find(':first-child').hasClass('swiper-wrapper'),
            '.swiper-wrapper should be existed on 2nd level div');
  assert.equal($component.find('.swiper-slide').text().trim(), 'anything');
});

test('it renders extra sturctures by options hash w/ default value', function(assert) {
  this.render(hbs`
    {{#swiper-container options=(hash
      prevButton=".swiper-button-prev"
      nextButton=".swiper-button-next"
      scrollbar=".swiper-scrollbar"
      pagination=".swiper-pagination"
    )}}

anything

    {{/swiper-container}}
  `);

  const $container = this.$(':first-child');

  assert.ok($container.find('.swiper-scrollbar').length > 0,
            'check for .swiper-scrollbar');
  assert.ok($container.find('.swiper-button-prev').length > 0,
            'check for .swiper-button-prev');
  assert.ok($container.find('.swiper-button-next').length > 0,
            'check for .swiper-button-next');
  assert.ok($container.find('.swiper-pagination').length > 0,
            'check for .swiper-pagination');
});

test('it also allows customized class name for extra sturctures', function(assert) {
  this.render(hbs`
    {{#swiper-container options=(hash
      prevButton=".custom-button-prev"
      nextButton=".custom-button-next"
      scrollbar=".custom-scrollbar"
      pagination=".custom-pagination"
    )}}

anything

    {{/swiper-container}}
  `);

  const $container = this.$(':first-child');

  assert.ok($container.find('.custom-button-prev').length > 0,
            'check for .custom-button-prev');
  assert.ok($container.find('.custom-button-next').length > 0,
            'check for .custom-button-next');
  assert.ok($container.find('.custom-scrollbar').length > 0,
            'check for .custom-scrollbar');
  assert.ok($container.find('.custom-pagination').length > 0,
            'check for .custom-pagination');
});

test('even customized class names still have the default class name', function(assert) {
  this.render(hbs`
    {{#swiper-container options=(hash
      prevButton=".custom-button-prev"
      nextButton=".custom-button-next"
      scrollbar=".custom-scrollbar"
      pagination=".custom-pagination"
    )}}

anything

    {{/swiper-container}}
  `);

  const $container = this.$(':first-child');

  assert.ok(
    $container.find('.custom-button-prev').hasClass('swiper-button-prev'),
    'check for .*-button-prev'
  );
  assert.ok(
    $container.find('.custom-button-next').hasClass('swiper-button-next'),
    'check for .*-button-next'
  );
  assert.ok(
    $container.find('.custom-scrollbar').hasClass('swiper-scrollbar'),
    'check for .*-scrollbar'
  );
  assert.ok(
    $container.find('.custom-pagination').hasClass('swiper-pagination'),
    'check for .*-pagination'
  );
});

test('it yields swiper.slide component with customizable structures', function(assert) {
  this.render(hbs`
    {{#swiper-container as |swiper|}}
      {{#swiper.slide class="custom-slide"}}A{{/swiper.slide}}
      {{#swiper.slide}}B{{/swiper.slide}}
      {{#swiper.slide}}C{{/swiper.slide}}
    {{/swiper-container}}
  `);

  const $component = this.$(':first-child');

  assert.ok($component.find('.swiper-slide').length === 3);
  assert.ok($component.find('.custom-slide').length === 1);
});

test('it initializ Swiper properlly', function(assert) {
  this.render(hbs`
    {{#swiper-container as |swiper|}}
      {{#swiper.slide}}A{{/swiper.slide}}
      {{#swiper.slide}}B{{/swiper.slide}}
      {{#swiper.slide}}C{{/swiper.slide}}
    {{/swiper-container}}
  `);

  const $component = this.$(':first-child');

  assert.ok($component.hasClass('swiper-container-horizontal'));
});


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^receiver/submit/$', 'receiver.views.raw_submit', name='raw_submit'),
    url(r'^receiver/submit/(?P<domain_name>.*)$', 'receiver.views.domain_submit', name='domain_submit'),
    url(r'^receiver/resubmit/(?P<domain_name>.*)$', 'receiver.views.domain_resubmit', name='domain_resubmit'),
    url(r'^receiver/review/?$', 'receiver.views.show_submits', name='show_submits'),
    url(r'^receiver/review/dupes/(?P<submission_id>\d+)/?$', 'receiver.views.show_dupes', name='show_dupes'),
    url(r'^receiver/review/(?P<submission_id>\d+)/delete/?$', 'receiver.views.delete_submission', name='delete_submission'),
    url(r'^receiver/review/(?P<submission_id>\d+)/?$', 'receiver.views.single_submission', name='single_submission'),
    url(r'^receiver/attachment/(?P<attachment_id>\d+)/?$', 'receiver.views.single_attachment', name='single_attachment'),
    url(r'^receiver/annotations/new/?$', 'receiver.views.new_annotation', name='new_annotation'),
    url(r'^receiver/annotations/(?P<attachment_id>\d+)/?$', 'receiver.views.annotations', name='annotations'),
    url(r'^receiver/orphaned_data/$', 'receiver.views.orphaned_data', name='orphaned_data'),
    url(r'^receiver/orphaned_data/xml/?$', 'receiver.views.orphaned_data_xml', name='orphaned_data_xml'),
    (r'', include('receiver.api_.urls')),
)


text:
require 'rails_admin/abstract_model'

module RailsAdmin
  class ApplicationController < ::ApplicationController
    newrelic_ignore if defined?(NewRelic)

    before_filter :_authenticate!
    before_filter :_authorize!
    before_filter :set_plugin_name

    helper_method :_current_user

    def get_model
      model_name = to_model_name(params[:model_name])
      @abstract_model = RailsAdmin::AbstractModel.new(model_name)
      @model_config = RailsAdmin.config(@abstract_model)
      not_found if @model_config.excluded?
      @properties = @abstract_model.properties
    end

    def to_model_name(param)
      parts = param.split("~")
      parts[-1] = parts.last.singularize
      parts.map(&:camelize).join("::")
    end

    def get_object
      @object = @abstract_model.get(params[:id])
      not_found unless @object
    end

    private

    def _authenticate!
      instance_eval &RailsAdmin::Config.authenticate_with
    end

    def _authorize!
      instance_eval &RailsAdmin::Config.authorize_with
    end

    def _current_user
      instance_eval &RailsAdmin::Config.current_user_method
    end

    def set_plugin_name
      @plugin_name = "RailsAdmin"
    end

    def not_found
      render :file => Rails.root.join('public', '404.html'), :layout => false, :status => 404
    end

    def rails_admin_controller?
      true
    end
  end
end


text:
enum ChronoLineUnit {
    cluAuto,
    cluHour,
    cluDay,
    cluWeek,
    cluMonth,
    cluQuarter,
    cluYear,
    cluNone // not using
};

enum ChronoLineFlagType {
    clftEvent,
    clftPairBeg,
    clftPairEnd
};

// Months in quarter - really constant
#define MONTHS_IN_QUARTER 3

// Margin (in pixels) of left scale division
#define LEFT_DIV_MARGIN      25
// Margin (in pixels) of right scale division (minimal)
#define RIGHT_DIV_MARGIN     25
// Height (in pixels) of main scale divisions
#define MAIN_DIV_HEIGHT      15
// Height (in pixels) of auxiliary scale divisions
#define AUX_DIV_HEIGHT        8
// Y coordinate for text output
#define TEXT_Y               15
// Step for scale zoom in and zoom out (relatively to full scale range)
#define ZOOM_STEP 0.1
// Minimum number of units per scale for valid view
#define MIN_UNITS_NUM 2
// Maximum number of years per scale
#define MAX_YEARS_NUM 4

// Base height of period view
#define BASE_PERIOD_HEIGHT   20
// Shift of height for each next period
#define PERIOD_HEIGHT_SHIFT   5

// Full height of flag view
#define FLAG_HEIGHT 60
// Width of flag view
#define FLAG_WIDTH 25
// Height of upper flag view part
#define FLAG_SUBHEIGHT 20

// Datetime shift (in main units) while flag dragging outside scale
// Minimal units
#define MIN_FLAGDRAG_DATE_SHIFT 0.02
// Maximal units
#define MAX_FLAGDRAG_DATE_SHIFT 0.1
// Shift period, msec
#define FLAGDRAG_DATE_SHIFT_PERIOD 50

#define ODATE(d) (d).toString().toLocal8Bit().data()

#endif // CLDEFS_H


text:
package org.hillview.utils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hillview.dataset.api.IJson;
import org.hillview.dataset.api.PartialResult;

import javax.annotation.Nullable;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * This class has some useful static helper methods.
 */
public class Utilities {
    /**
     * Convert a shell-type filename wildcard pattern into a Java
     * regular expression string.
     * @param wildcard  Simple filename wildcard string.
     * @return          A String that represents a regular expression
     *                  with the same semantics as the wildcard pattern.
     */
    @Nullable
    public static String wildcardToRegex(@Nullable String wildcard) {
        if (wildcard == null)
            return null;
        StringBuilder s = new StringBuilder(wildcard.length());
        s.append('^');
        for (int i = 0; i < wildcard.length(); i++) {
            char c = wildcard.charAt(i);
            switch(c) {
                case '*':
                    s.append(".*");
                    break;
                case '?':
                    s.append(".");
                    break;
                case '(': case ')': case '[': case ']': case '$':
                case '.': case '{': case '}': case '|':
                case '\\':
                    s.append("\\");
                    s.append(c);
                    break;
                default:
                    s.append(c);
                    break;
            }
        }
        s.append('$');
        return(s.toString());
    }

    /**
     * A string describing the current stack trace.
     */
    public static String stackTraceString() {
        return ExceptionUtils.getStackTrace(new Throwable());
    }

    /**
     * Return a prefix of the argument if it is too long.
     */
    @Nullable
    public static String truncateString(@Nullable String s) {
        if (s == null || s.length() < 100)
            return s;
        return s.substring(0, 99) + "...";
    }

    /**
     * Checks if the argument string is null or empty.
     */
    public static boolean isNullOrEmpty(@Nullable String s) {
        return s == null || s.isEmpty();
    }

    /**
     * Converts an array of strings into a Map string->string.
     * The array must have an even number of elements, and
     * the elements are in order key-value pairs.
     */
    @Nullable
    public static HashMap<String, String> arrayToMap(@Nullable String[] array) {
        if (array == null)
            return null;
        HashMap<String, String> result = new HashMap<String, String>();
        if (array.length % 2 != 0)
            throw new IllegalArgumentException("Array must have an even number of elements");
        for (int index = 0; index < array.length; index += 2)
            result.put(array[index], array[index+1]);
        return result;
    }

    /**
     * Converts a throwable to a string.
     */
    @Nullable
    public static String throwableToString(@Nullable Throwable t) {
        if (t == null)
            return null;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        return sw.toString();
    }

    /**
     * Gets the name of the local machine.
     */
    public static String getHostName() {
        try {
            java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
            return localMachine.getHostName();
        } catch (java.net.UnknownHostException e) {
            HillviewLogger.instance.error("Cannot get host name");
            return "?";
        }
    }

    /**
     * PartialResult does not implement IJson, but some variants of it do.
     * @param pr  Partial result.
     * @param <T> Type of data in partial result.
     * @return    The JSON representation of the partial result.
     */
    public static <T extends IJson> JsonElement toJsonTree(PartialResult<T> pr) {
        JsonObject json = new JsonObject();
        json.addProperty("done", pr.deltaDone);
        if (pr.deltaValue == null)
            json.add("data", null);
        else
            json.add("data", pr.deltaValue.toJsonTree());
        return json;
    }

    public static String[] toArray(List<String> list) {
        // Apparently using an empty array is fast enough, we don't need
        // to pre-allocate the array.
        return list.toArray(new String[0]);
    }

    private static final List<String> compressionSuffixes = Arrays.asList(
            "gz", "bz", "bzip2", "xz", "Z", "arj");

    /**
     * Detect whether a file is compressed based on the file name.
     */
    public static boolean isCompressed(String filename) {
        String suffix = FilenameUtils.getExtension(filename).toLowerCase();
        return compressionSuffixes.contains(suffix);
    }

    /**
     * This function strips the path and the extension of a file name.
     * It also removes known compression suffixes.
     */
    public static String getBasename(String filename) {
        String basename = FilenameUtils.getBaseName(filename);
        if (isCompressed(basename))
            basename = FilenameUtils.removeExtension(basename);
        return FilenameUtils.removeExtension(basename);
    }
}


text:
package images

import (
    "crypto/sha256"
    "encoding/hex"
    "os"
    "io"
)

func GetHashFile(file *os.File) string {
    hash := sha256.New()

    io.Copy(hash, file)

    return hex.EncodeToString(hash.Sum(nil))
}

func GetHashFileA(address string) string {
    file, err := os.Open(address)
    if err != nil {
        return ""
    }
    defer file.Close()

    hash := sha256.New()

    io.Copy(hash, file)

    return hex.EncodeToString(hash.Sum(nil))
}


text:
Shindo.tests('HP::Network | networking security group requests', ['hp', 'networking', 'securitygroup']) do

  @security_group_format = {
    'id'                    => String,
    'name'                  => String,
    'description'           => String,
    'tenant_id'             => String,
    'security_group_rules'  => [Hash]
  }

  tests('success') do

    @sec_group_id = nil

    tests("#create_security_group('fog_security_group', 'tests group')").formats(@security_group_format) do
      attributes = {:name => 'fog_security_group', :description => 'tests group'}
      data = HP[:network].create_security_group(attributes).body['security_group']
      @sec_group_id = data['id']
      data
    end

    tests("#get_security_group('#{@sec_group_id}')").formats(@security_group_format) do
      HP[:network].get_security_group(@sec_group_id).body['security_group']
    end

    tests("#list_security_groups").formats('security_groups' => [@security_group_format]) do
      HP[:network].list_security_groups.body
    end

    tests("#delete_security_group('#{@sec_group_id}')").succeeds do
      HP[:network].delete_security_group(@sec_group_id)
    end

  end

  tests('failure') do

    tests("#get_security_group(0)").raises(Fog::HP::Network::NotFound) do
      HP[:network].get_security_group(0)
    end

    tests("#delete_security_group(0)").raises(Fog::HP::Network::NotFound) do
      HP[:network].delete_security_group(0)
    end

  end

end


text:
#pragma once
#include <Doremi/Core/Include/Streamers/Streamer.hpp>

namespace Doremi
{
    namespace Core
    {
        /**
            Abstract class for objects that are needed to be abele to write or read to a stream
        */
        class Serializable
        {
        public:
            /**
                Write object to stream
            */
            virtual void Write(Streamer* p_streamer, uint32_t& op_bitsWritten) = 0;

            /**
                Read object from stream
            */
            virtual void Read(Streamer* p_streamer, uint32_t& op_bitsRead) = 0;
        };
    }
}


text:
.class Lcom/sec/android/app/camera/Camera$34;
.super Ljava/lang/Object;
.source "Camera.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/sec/android/app/camera/Camera;->showFaceZoomGuideDialog()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/sec/android/app/camera/Camera;

# direct methods
.method constructor <init>(Lcom/sec/android/app/camera/Camera;)V
    .locals 0
    .parameter

    .prologue
    .line 6917
    iput-object p1, p0, Lcom/sec/android/app/camera/Camera$34;->this$0:Lcom/sec/android/app/camera/Camera;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 0
    .parameter "dialog"
    .parameter "whichButton"

    .prologue
    .line 6919
    return-void
.end method


text:
<!DOCTYPE HTML>

    <title>globalization.getDateNames</title>
	<link rel="stylesheet" type="text/css" href="style.css">

← Back

    <button onclick="checkDateNames()">Click for date names</button>


text:
<?php

class RSS_Import {

	var $posts = array ();
	var $file;

	function header() {
		echo '
';
		echo '
'.__('Import RSS').'
';
	}

	function footer() {
		echo '
';
	}

	function unhtmlentities($string) { // From php.net for < 4.3 compat
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
		$trans_tbl = array_flip($trans_tbl);
		return strtr($string, $trans_tbl);
	}

	function greet() {
		echo '
';
		echo '
'.__('Howdy! This importer allows you to extract posts from an RSS 2.0 file into your blog. This is useful if you want to import your posts from a system that is not handled by a custom import tool. Pick an RSS file to upload and click Import.').'
';
		wp_import_upload_form("admin.php?import=rss&step=1");
		echo '
';
	}

	function get_posts() {
		global $wpdb;

		set_magic_quotes_runtime(0);
		$datalines = file($this->file); // Read the file into an array
		$importdata = implode('', $datalines); // squish it
		$importdata = str_replace(array ("\r\n", "\r"), "\n", $importdata);

		preg_match_all('|<item>(.*?)</item>|is', $importdata, $this->posts);
		$this->posts = $this->posts[1];
		$index = 0;
		foreach ($this->posts as $post) {
			preg_match('|<title>(.*?)</title>|is', $post, $post_title);
			$post_title = str_replace(array('<![CDATA[', ']]>'), '', $wpdb->escape( trim($post_title[1]) ));

			preg_match('|<pubdate>(.*?)</pubdate>|is', $post, $post_date_gmt);

			if ($post_date_gmt) {
				$post_date_gmt = strtotime($post_date_gmt[1]);
			} else {
				// if we don't already have something from pubDate
				preg_match('|<dc:date>(.*?)</dc:date>|is', $post, $post_date_gmt);
				$post_date_gmt = preg_replace('|([-+])([0-9]+):([0-9]+)$|', '\1\2\3', $post_date_gmt[1]);
				$post_date_gmt = str_replace('T', ' ', $post_date_gmt);
				$post_date_gmt = strtotime($post_date_gmt);
			}

			$post_date_gmt = gmdate('Y-m-d H:i:s', $post_date_gmt);
			$post_date = get_date_from_gmt( $post_date_gmt );

			preg_match_all('|<category>(.*?)</category>|is', $post, $categories);
			$categories = $categories[1];

			if (!$categories) {
				preg_match_all('|<dc:subject>(.*?)</dc:subject>|is', $post, $categories);
				$categories = $categories[1];
			}

			$cat_index = 0;
			foreach ($categories as $category) {
				$categories[$cat_index] = $wpdb->escape($this->unhtmlentities($category));
				$cat_index++;
			}

			preg_match('|<guid.*?>(.*?)</guid>|is', $post, $guid);
			if ($guid)
				$guid = $wpdb->escape(trim($guid[1]));
			else
				$guid = '';

			preg_match('|<content:encoded>(.*?)</content:encoded>|is', $post, $post_content);
			$post_content = str_replace(array ('<![CDATA[', ']]>'), '', $wpdb->escape(trim($post_content[1])));

			if (!$post_content) {
				// This is for feeds that put content in description
				preg_match('|<description>(.*?)</description>|is', $post, $post_content);
				$post_content = $wpdb->escape($this->unhtmlentities(trim($post_content[1])));
			}

			// Clean up content
			$post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
			$post_content = str_replace('
', '
', $post_content);
			$post_content = str_replace('
', '
', $post_content);

			$post_author = 1;
			$post_status = 'publish';
			$this->posts[$index] = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_status', 'guid', 'categories');
			$index++;
		}
	}

	function import_posts() {
		echo '
';

		foreach ($this->posts as $post) {
			echo "
".__('Importing post...');

			extract($post);

			if ($post_id = post_exists($post_title, $post_content, $post_date)) {
				_e('Post already imported');
			} else {
				$post_id = wp_insert_post($post);
				if ( is_wp_error( $post_id ) )
					return $post_id;
				if (!$post_id) {
					_e("Couldn't get post ID");
					return;
				}

				if (0 != count($categories))
					wp_create_categories($categories, $post_id);
				_e('Done !');
			}
			echo '
';
		}

		echo '
';

	}

	function import() {
		$file = wp_import_handle_upload();
		if ( isset($file['error']) ) {
			echo $file['error'];
			return;
		}

		$this->file = $file['file'];
		$this->get_posts();
		$result = $this->import_posts();
		if ( is_wp_error( $result ) )
			return $result;
		wp_import_cleanup($file['id']);
		do_action('import_done', 'rss');

		echo '
';
		printf(__('All done. Have fun!'), get_option('home'));
		echo '
';
	}

	function dispatch() {
		if (empty ($_GET['step']))
			$step = 0;
		else
			$step = (int) $_GET['step'];

		$this->header();

		switch ($step) {
			case 0 :
				$this->greet();
				break;
			case 1 :
				check_admin_referer('import-upload');
				$result = $this->import();
				if ( is_wp_error( $result ) )
					echo $result->get_error_message();
				break;
		}

		$this->footer();
	}

	function RSS_Import() {
		// Nothing.
	}
}

$rss_import = new RSS_Import();

register_importer('rss', __('RSS'), __('Import posts from an RSS feed.'), array ($rss_import, 'dispatch'));
?>


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=2009/02/03/opera-web-standards-curriculum-translations-available/index.html"><TITLE>Page has moved</TITLE>

Click here...