text:
import argparse
import os
import time

from torch.utils.data import DataLoader
import torch.optim
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from torch.autograd import Variable

from tensorboardX import SummaryWriter

import humanpose_net
import humanpose_data
from humanpose_eval import evaluation
from utils import tools

parser = argparse.ArgumentParser(description='PyTorch human pose detection')
parser.add_argument('--lsp-root', metavar='DIR',
                    help='path to root of lsp dataset')
parser.add_argument('--cuda', action='store_true', default=False,
                    help='enables CUDA training')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=1500, type=int, metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=45, type=int,
                    metavar='N', help='mini-batch size (default: 45)')
parser.add_argument('--lr', '--learning-rate', default=2e-3, type=float,
                    metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                    help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
                    metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=30, type=int,
                    metavar='N', help='print batch frequency (default: 30)')
parser.add_argument('--save-freq', '-s', default=300, type=int,
                    metavar='N', help='save batch frequency (default: 300)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
                    help='path to latest checkpoint (default: none)')
parser.add_argument('--lr-decay-rate', default=0.8, type=float,
                    help='decay rate of learning rate (default: 0.8)')
parser.add_argument('--lr-epoch-per-decay', default=150, type=int,
                    help='epoch of per decay of learning rate (default: 150)')
parser.add_argument('--ckpt-dir', metavar='DIR',
                    help='path to save checkpoints')
parser.add_argument('--summary-dir', metavar='DIR',
                    help='path to save summary')
parser.add_argument('--weighted-loss', '--wl', action='store_true', default=False,
                    help='weighted loss')
parser.add_argument('--weighted-bandwidth', '--wb', default=0.6, type=float,
                    help='bandwidth for loss weight kde')
parser.add_argument('--epochs-per-eval', default=None, type=int,
                    metavar='N', help='Interval of epochs for a testing data evaluation.')
parser.add_argument('--epoch-start-weight', default=None, type=int,
                    metavar='N', help='Epoch on which start weighted loss')

args = parser.parse_args()
args.cuda = (args.cuda and torch.cuda.is_available())
image_w = 224
image_h = 224

def train():
    train_data = humanpose_data.LSPDataset(args.lsp_root,
                                           transform=transforms.Compose([humanpose_data.Scale(image_h, image_w),
                                                                         humanpose_data.RandomHSV((0.8, 1.2),
                                                                                (0.8, 1.2),
                                                                                (25, 25)),
                                                                         humanpose_data.ToTensor(),
                                                                         humanpose_data.Normalize()]),
                                           phase_train=True,
                                           weighted_loss=args.weighted_loss,
                                           bandwidth=args.weighted_bandwidth)
    train_loader = DataLoader(train_data, batch_size=args.batch_size, shuffle=True,
                              num_workers=args.workers, pin_memory=True if args.cuda else False)
    if args.epochs_per_eval:
        if not os.path.exists(os.path.join(args.ckpt_dir, 'logfile')):
            os.mkdir(os.path.join(args.ckpt_dir, 'logfile'))
        test_data = humanpose_data.LSPDataset(args.lsp_root,
                                              transform=transforms.Compose([humanpose_data.Scale(image_h, image_w),
                                                                            humanpose_data.ToTensor(),
                                                                            humanpose_data.Normalize()]),
                                              phase_train=False,
                                              weighted_loss=False)
        test_loader = DataLoader(test_data, batch_size=args.batch_size, shuffle=False,
                                 num_workers=args.workers, pin_memory=True if args.cuda else False)
    num_alldata = len(train_data)

    model = humanpose_net.HumanPoseNet(train_data.num_keypoints * 2)
    model.train()
    if args.cuda:
        model.cuda()
    optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)

    count = 0
    global_step = 0
    if args.resume:
        count, global_step, args.start_epoch = load_ckpt(model, optimizer, args.resume)

    writer = SummaryWriter(args.summary_dir)

    for epoch in range(int(args.start_epoch), args.epochs):
        adjust_learning_rate(optimizer, epoch, args.lr,
                             args.lr_decay_rate, args.lr_epoch_per_decay)
        if args.epochs_per_eval:
            if epoch % args.epochs_per_eval == 0:
                model.eval()
                evaluation(model, test_loader, epoch, args.ckpt_dir, phase_cuda=args.cuda,
                           writer=writer, testing_data=True, phase_eval_log=True)
                model.train()
        for batch_idx, sample in enumerate(train_loader):

            image = Variable(sample['image'].cuda() if args.cuda else sample['image'])
            lm = Variable(sample['landmarks'].cuda() if args.cuda else sample['landmarks'])
            weight = Variable(sample['weight'].cuda() if args.cuda else sample['weight'])
            optimizer.zero_grad()
            pred = model(image)
            loss_log = humanpose_net.mse_loss(pred, lm, weight)
            if args.epoch_start_weight is None or args.epoch_start_weight < epoch:
                loss = humanpose_net.mse_loss(pred, lm, weight, weighted_loss=args.weighted_loss)
            else:
                loss = humanpose_net.mse_loss(pred, lm, weight, weighted_loss=False)
            loss.backward()
            optimizer.step()
            count += image.data.shape[0]
            global_step += 1
            if global_step % args.print_freq == 0:
                try:
                    time_inter = time.time() - end_time
                    count_inter = count - last_count
                    print_log(global_step, epoch, count, count_inter,
                              num_alldata, loss_log, time_inter)
                    end_time = time.time()
                    for name, param in model.named_parameters():
                        writer.add_histogram(name, param.clone().cpu().data.numpy(), global_step)
                    grid_image = make_grid(tools.joint_painter(image[:9], pred[:9],
                                                               image_h, image_w), 3)
                    writer.add_image('Predicted image', grid_image, global_step)
                    grid_image = make_grid(tools.joint_painter(image[:9], lm[:9],
                                                               image_h, image_w), 3)
                    writer.add_image('Groundtruth image', grid_image, global_step)
                    writer.add_scalar('MSELoss', loss_log.data[0], global_step=global_step)
                    writer.add_scalar('Weighted MSELoss', loss.data[0], global_step=global_step)
                    last_count = count
                except NameError:
                    end_time = time.time()
                    last_count = count
            if global_step % args.save_freq == 0 or global_step == 1:
                save_ckpt(model, optimizer, global_step, batch_idx, count, args.batch_size,
                          num_alldata, args.weighted_loss, args.weighted_bandwidth)
    save_ckpt(model, optimizer, global_step, batch_idx, count, args.batch_size,
              num_alldata, args.weighted_loss, args.weighted_bandwidth)
    model.eval()
    evaluation(model, test_loader, epoch, args.ckpt_dir, phase_cuda=args.cuda,
               writer=writer, testing_data=True, phase_eval_log=True)

    print("Training completed ")

def adjust_learning_rate(optimizer, epoch, init_lr, lr_decay_rate, lr_epoch_per_decay):
    """Sets the learning rate to the initial LR decayed by lr_decay_rate every lr_epoch_per_decay epochs"""
    lr = init_lr * (lr_decay_rate ** (epoch // lr_epoch_per_decay))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

def print_log(global_step, epoch, count, count_inter, dataset_size, loss, time_inter):
    num_data = count % dataset_size
    num_all = dataset_size
    print('Step: {:>5} Train Epoch: {:>3} [{:>4}/{:>4} ({:3.1f}%)]    Loss: {:.6f} [{:.2f}s every {:>4} data]'.format(
        global_step, epoch, num_data, num_all,
                     100. * num_data / num_all, loss.data[0], time_inter, count_inter))

def save_ckpt(model, optimizer, global_step, batch_idx, count,
              batch_size, num_alldata, weighted, bandwidth):
    state = {
        'global_step': global_step,
        'epoch': count / num_alldata,
        'count': count,
        'batch_size': batch_size,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
        'weighted': weighted,
        'bandwidth': bandwidth,
        'dataset_size': num_alldata,
    }
    ckpt_model_filename = "ckpt_epoch_{:0.2f}.pth".format(count / num_alldata)
    path = os.path.join(args.ckpt_dir, ckpt_model_filename)
    torch.save(state, path)
    print('{:>35} has been successfully saved'.format(path))

def load_ckpt(model, optimizer, model_file):
    if os.path.isfile(model_file):
        print("=> loading checkpoint '{}'".format(model_file))
        if args.cuda:
            checkpoint = torch.load(model_file)
        else:
            checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage)
        model.load_state_dict(checkpoint['state_dict'])
        optimizer.load_state_dict(checkpoint['optimizer'])
        args.weighted_loss = checkpoint['weighted']
        args.weighted_bandwidth = checkpoint['bandwidth']
        print("=> loaded checkpoint '{}' (epoch {})"
              .format(model_file, checkpoint['epoch']))
        return checkpoint['count'], checkpoint['global_step'], checkpoint['epoch']
    else:
        print("=> no checkpoint found at '{}'".format(model_file))
        os._exit(0)

if __name__ == '__main__':
    if not os.path.exists(args.ckpt_dir):
        os.mkdir(args.ckpt_dir)
    train()


text:
package filters

import (
	"sigs.k8s.io/kustomize/kyaml/kio"
	"sigs.k8s.io/kustomize/kyaml/yaml"
	"sigs.k8s.io/kustomize/kyaml/yaml/merge2"
)

// MergeFilter merges Resources with the Group/Version/Kind/Namespace/Name together using
// a 2-way merge strategy.
//
// - Fields set to null in the source will be cleared from the destination
// - Fields with matching keys will be merged recursively
// - Lists with an associative key (e.g. name) will have their elements merged using the key
// - List without an associative key will have the dest list replaced by the source list
type MergeFilter struct {
	Reverse bool
}

var _ kio.Filter = MergeFilter{}

type mergeKey struct {
	apiVersion string
	kind       string
	namespace  string
	name       string
}

// MergeFilter implements kio.Filter by merging Resources with the same G/V/K/NS/N
func (c MergeFilter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) {
	// invert the merge precedence
	if c.Reverse {
		for i, j := 0, len(input)-1; i < j; i, j = i+1, j-1 {
			input[i], input[j] = input[j], input[i]
		}
	}

	// index the Resources by G/V/K/NS/N
	index := map[mergeKey][]*yaml.RNode{}
	// retain the original ordering
	var order []mergeKey
	for i := range input {
		meta, err := input[i].GetMeta()
		if err != nil {
			return nil, err
		}
		key := mergeKey{
			apiVersion: meta.APIVersion,
			kind:       meta.Kind,
			namespace:  meta.Namespace,
			name:       meta.Name,
		}
		if _, found := index[key]; !found {
			order = append(order, key)
		}
		index[key] = append(index[key], input[i])
	}

	// merge each of the G/V/K/NS/N lists
	var output []*yaml.RNode
	var err error
	for _, k := range order {
		var merged *yaml.RNode
		resources := index[k]
		for i := range resources {
			patch := resources[i]
			if merged == nil {
				// first resources, don't merge it
				merged = resources[i]
			} else {
				merged, err = merge2.Merge(patch, merged, yaml.MergeOptions{
					ListIncreaseDirection: yaml.MergeOptionsListPrepend,
				})
				if err != nil {
					return nil, err
				}
			}
		}
		output = append(output, merged)
	}
	return output, nil
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<meta charset="utf-8" />
<title>input type=password Invalid maxlength</title>

	Try type "foobar" in the password field below.  As the password field has an
	invalid <var>maxlength</var> attribute, you should be able to type the whole
	word.  Click submit.  The whole word "foobar" should be returned on the
	following page.

<form action="../res/return_single_post.php" method="post">

		<input name="test" type="password" maxlength="foobar" />
		<input name="submit" type="submit" />

</form>


text:
use strict;
use warnings;

use File::Basename;
use File::Spec;
use Test::More;

use Bio::EnsEMBL::Test::MultiTestDB;

diag 'Starting database and files cleaning up...';

my $curr_file = __FILE__;
my $db_conf = Bio::EnsEMBL::Test::MultiTestDB->get_db_conf(dirname(__FILE__));

foreach my $species ( keys %{ $db_conf->{'databases'} } ) {
  my $multi = Bio::EnsEMBL::Test::MultiTestDB->new($species);
}

note "Deleting $curr_file";
my $result = unlink $curr_file;
ok($result, 'Unlink of '.$curr_file.' worked');

done_testing();


text:
package com.streamsets.pipeline.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class TestHadoopMapReduceBinding {

  @Test
  public void testJavaOptsArgs() {
    Configuration conf = new Configuration();
    conf.set(HadoopMapReduceBinding.MAPREDUCE_MAP_MEMORY_MB, "1024");
    // Xmx with m option
    String javaOpts = "-Xmx1024m -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertEquals(Integer.valueOf(1280), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    // Xmx with g option
    javaOpts = "-Xmx1g -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertEquals(Integer.valueOf(1280), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    // Xmx with k option
    javaOpts = "-Xmx1048576K -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertEquals(Integer.valueOf(1280), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    // Xmx only bytes
    javaOpts = "-Xmx1073741824 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertEquals(Integer.valueOf(1280), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    // last -Xmx wins
    javaOpts = "-Xmx512m -Xmx1024m -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertEquals(Integer.valueOf(1280), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    conf.set(HadoopMapReduceBinding.MAPREDUCE_MAP_MEMORY_MB, "2048");
    // default config > passed java_opts
    assertEquals(Integer.valueOf(2048), HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));
    // no Xmx option
    javaOpts = "-XX:+UseConcMarkSweepGC -XX:+UseParNewGC -Dlog4j.debug";
    assertNull(HadoopMapReduceBinding.getMapMemoryMb(javaOpts, conf));

  }
}


text:
package org.canova.nlp.tokenization.tokenizer;

/**
 * Token preprocessing
 * @author Adam Gibson
 *
 */
public interface TokenPreProcess {

	/**
	 * Pre process a token
	 * @param token the token to pre process
	 * @return the preprocessed token
	 */
	String preProcess(String token);

}


text:
package com.dfrz.news.service.impl;

import com.dfrz.news.dao.UserDAO;
import com.dfrz.news.dao.impl.UserDAOImpl;
import com.dfrz.news.domain.User;
import com.dfrz.news.exception.UserExitException;
import com.dfrz.news.service.UserService;

public class UserServiceImpl implements UserService {

	private UserDAO userDao = new UserDAOImpl();

	public void regist(User user) throws UserExitException {
		User _user = userDao.findUser(user.getUsername());
		if(_user!=null)
			throw new UserExitException("用户已存在");
		userDao.save(user);
	}

	public User login(String username, String password) {
		return userDao.findUser(username, password);
	}

	@Override
	public void midifyPwd(User user) {
		userDao.update(user);
	}

}


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.editor.ui.textrender;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.archimatetool.model.IAccessRelationship;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IDiagramModelArchimateConnection;
import com.archimatetool.model.IInfluenceRelationship;

import junit.framework.JUnit4TestAdapter;

/**
 * RelationshipRenderer Tests
 *
 * @author Phillip Beauvoir
 */
@SuppressWarnings("nls")
public class RelationshipRendererTests extends AbstractTextRendererTests {

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(RelationshipRendererTests.class);
    }

    private RelationshipRenderer renderer = new RelationshipRenderer();

    @Override
    protected RelationshipRenderer getRenderer() {
        return renderer;
    }

    @Test
    public void render_Strength() {
        IInfluenceRelationship relation = IArchimateFactory.eINSTANCE.createInfluenceRelationship();
        relation.setStrength("+++");
        IDiagramModelArchimateConnection dmc = IArchimateFactory.eINSTANCE.createDiagramModelArchimateConnection();
        dmc.setArchimateConcept(relation);
        String result = renderer.render(dmc, "${strength}");
        assertEquals("+++", result);
    }

    @Test
    public void render_AccessType() {
        IAccessRelationship relation = IArchimateFactory.eINSTANCE.createAccessRelationship();
        relation.setAccessType(IAccessRelationship.READ_WRITE_ACCESS);
        IDiagramModelArchimateConnection dmc = IArchimateFactory.eINSTANCE.createDiagramModelArchimateConnection();
        dmc.setArchimateConcept(relation);
        String result = renderer.render(dmc, "${accessType}");
        assertEquals("Read/Write", result);
    }
}


text:
package org.kc7bfi.jflac.frame;

public class EntropyPartitionedRiceContents {

    protected int[] parameters; // The Rice parameters for each context.
    protected int[] rawBits; // Widths for escape-coded partitions.

    /**
     * The capacity of the parameters and raw_bits arrays specified as an order.
     * i.e. the number of array elements allocated is 2 ^ capacity_by_order.
     */
    protected int capacityByOrder = 0;

    /**
     * Ensure enough menory has been allocated.
     * @param maxPartitionOrder The maximum partition order
     */
    public void ensureSize(int maxPartitionOrder) {
        if (capacityByOrder >= maxPartitionOrder) return;
        parameters = new int[(1 << maxPartitionOrder)];
        rawBits = new int[(1 << maxPartitionOrder)];
        capacityByOrder = maxPartitionOrder;
    }
}


text:
CREATE USER 'yourname'@'IPGOESHERE' IDENTIFIED BY 'yourpasswordhere';
GRANT ALL ON *.* TO 'yourname'@'IPGOESHERE';

# My example would be
# CREATE USER 'worker'@'192.168.1.239' IDENTIFIED BY 'ilovebunnies';
# GRANT ALL ON *.* TO 'worker'@'192.168.1.239';


text:
package commands

import (
	"fmt"
	"os"

	"github.com/pivotal-cf/go-pivnet"
	"github.com/pivotal-cf/jhanda"
	"github.com/pivotal-cf/om/configtemplate/generator"
	"github.com/pivotal-cf/om/configtemplate/metadata"
)

type ConfigTemplate struct {
	environFunc   func() []string
	buildProvider buildProvider
	Options       struct {
		OutputDirectory   string `long:"output-directory"    description:"a directory to create templates under. must already exist."                       required:"true"`
		PivnetApiToken    string `long:"pivnet-api-token"                                                                                required:"true"`
		PivnetProductSlug string `long:"pivnet-product-slug" description:"the product name in pivnet"                                                       required:"true"`
		ProductVersion    string `long:"product-version"     description:"the version of the product from which to generate a template"                     required:"true"`
		ProductFileGlob   string `long:"product-file-glob"   description:"a glob to match exactly one file in the pivnet product slug"  default:"*.pivotal" `
		ExcludeVersion    bool   `long:"exclude-version"     description:"if set, will not output a version-specific directory"`
	}
}

//go:generate counterfeiter -o ./fakes/metadata_provider.go --fake-name MetadataProvider . MetadataProvider
type MetadataProvider interface {
	MetadataBytes() ([]byte, error)
}

var pivnetHost = pivnet.DefaultHost
var DefaultProvider = func() func(c *ConfigTemplate) MetadataProvider {
	return func(c *ConfigTemplate) MetadataProvider {
		options := c.Options
		return metadata.NewPivnetProvider(
			pivnetHost,
			options.PivnetApiToken,
			options.PivnetProductSlug,
			options.ProductVersion,
			options.ProductFileGlob,
		)
	}
}

type buildProvider func(*ConfigTemplate) MetadataProvider

func NewConfigTemplate(bp buildProvider) *ConfigTemplate {
	return &ConfigTemplate{
		environFunc:   os.Environ,
		buildProvider: bp,
	}
}

//Execute - generates config template and ops files
func (c *ConfigTemplate) Execute(args []string) error {
	_, err := jhanda.Parse(
		&c.Options,
		args)
	if err != nil {
		return fmt.Errorf("could not parse config-template flags: %s", err.Error())
	}

	_, err = os.Stat(c.Options.OutputDirectory)
	if os.IsNotExist(err) {
		return fmt.Errorf("output-directory does not exist: %s", c.Options.OutputDirectory)
	}

	metadataSource := c.newMetadataSource()
	metadataBytes, err := metadataSource.MetadataBytes()
	if err != nil {
		return fmt.Errorf("error getting metadata for %s at version %s: %s", c.Options.PivnetProductSlug, c.Options.ProductVersion, err)
	}

	return generator.NewExecutor(
		metadataBytes,
		c.Options.OutputDirectory,
		c.Options.ExcludeVersion,
		true,
	).Generate()
}

func (c *ConfigTemplate) newMetadataSource() (metadataSource MetadataProvider) {
	return c.buildProvider(c)
}

func (c *ConfigTemplate) Usage() jhanda.Usage {
	return jhanda.Usage{
		Description:      "**EXPERIMENTAL** this command generates a product configuration template from a .pivotal file on Pivnet",
		ShortDescription: "**EXPERIMENTAL** generates a config template from a Pivnet product",
		Flags:            c.Options,
	}
}


text:
package org.caleydo.core.io;

import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.EDataType;
import org.caleydo.core.data.collection.column.container.CategoricalClassDescription;

/**
 * Container for all meta-data on the data. Can be set on a whole-dataset level or on a column-by-column level.
 *
 * @author Alexander Lex
 *
 */
public class DataDescription {

	/**
	 * The dataClass of the column, must be one equivalent to those listed in {@link EDataClass}. Defaults to real
	 * numbers.
	 */
	private EDataClass dataClass = EDataClass.REAL_NUMBER;

	/**
	 * The data type of the {@link #dataClass}. If the dataClass has only one possible rawDataType (see
	 * {@link EDataClass}) this is automatically set. Defaults to float.
	 */
	private EDataType rawDataType = EDataType.FLOAT;

	/**
	 * Set this if your data is homogeneous (i.e. all the columns in the file are of the same semantic data type, i.e.
	 * they have the same value ranges, etc.) and numerical. If this is set, the data scale used is the same for all
	 * columns. This member can not be set at the same time as {@link #categoricalClassDescription}. Defaults to null.
	 */
	private NumericalProperties numericalProperties = null;

	/**
	 * Set this if your data is homogeneous (i.e. all the columns in the file are of the same semantic data type, i.e.
	 * they have the same value ranges, etc.) and categorical. If this is set, the data scale used is the same for all
	 * columns. This member can not be set at the same time as {@link #numericalProperties}. Defaults to null.
	 */
	private CategoricalClassDescription<?> categoricalClassDescription = null;

	/**
	 *
	 */
	public DataDescription() {

	}

	/**
	 * Constructor specifying the class of column and infers the data type from the class if possible. *
	 *
	 * @param dataClass
	 * @throws IllegalArgumentException
	 *             if inference is not obvious.
	 */
	public DataDescription(EDataClass dataClass) {
		if (dataClass.getSupportedDataType() == null)
			throw new IllegalArgumentException("Cannot infer data type for data class " + dataClass);
		this.dataClass = dataClass;
		this.rawDataType = dataClass.getSupportedDataType();
	}

	public DataDescription(EDataClass dataClass, EDataType dataType) {
		init(dataClass, dataType);
	}

	public DataDescription(EDataClass dataClass, EDataType dataType, NumericalProperties numericalProperties) {
		init(dataClass, dataType);
		this.numericalProperties = numericalProperties;

	}

	public DataDescription(EDataClass dataClass, EDataType dataType,
			CategoricalClassDescription<?> categoricalClassDescription) {
		this.categoricalClassDescription = categoricalClassDescription;
		init(dataClass, dataType);

	}

	private void init(EDataClass dataClass, EDataType dataType) {
		this.dataClass = dataClass;
		if (!dataClass.supports(dataType))
			throw new IllegalArgumentException("DataClass " + dataClass + " doesn't support rawDataType " + dataType);
		this.rawDataType = dataType;
	}

	/**
	 * @param dataClass
	 *            setter, see {@link dataClass}
	 */
	public void setDataClass(EDataClass dataClass) {
		this.dataClass = dataClass;
		if (dataClass.getSupportedDataType() != null)
			rawDataType = dataClass.getSupportedDataType();
	}

	/**
	 * @return the dataClass, see {@link #dataClass}
	 */
	public EDataClass getDataClass() {
		return dataClass;
	}

	/**
	 * @param rawDataType
	 *            setter, see {@link rawDataType}
	 */
	public void setRawDataType(EDataType rawDataType) {
		this.rawDataType = rawDataType;
	}

	/**
	 * @return the rawDataType, see {@link #rawDataType}
	 */
	public EDataType getRawDataType() {
		return rawDataType;
	}

	// /**
	// * @param defaultDataTransformation
	// * setter, see {@link defaultDataTransformation}
	// */
	// public void setDefaultDataTransformation(String defaultDataTransformation) {
	// this.defaultDataTransformation = defaultDataTransformation;
	// }
	//
	// /**
	// * @return the defaultDataTransformation, see {@link #defaultDataTransformation}
	// */
	// public String getDefaultDataTransformation() {
	// return defaultDataTransformation;
	// }

	/**
	 * @param numericalProperties
	 *            setter, see {@link numericalProperties}
	 */
	public void setNumericalProperties(NumericalProperties numericalProperties) {
		if (categoricalClassDescription != null)
			throw new IllegalStateException(
					"Cannot set both numerical and categorical data set description at the same time");
		this.numericalProperties = numericalProperties;
	}

	/**
	 * @return the numericalProperties, see {@link #numericalProperties}
	 */
	public NumericalProperties getNumericalProperties() {
		return numericalProperties;
	}

	/**
	 * @param categoricalClassDescription
	 *            setter, see {@link categoricalClassDescription}
	 */
	public void setCategoricalClassDescription(CategoricalClassDescription<?> categoricalClassDescription) {
		if (numericalProperties != null)
			throw new IllegalStateException(
					"Cannot set both numerical and categorical data set description at the same time");
		this.categoricalClassDescription = categoricalClassDescription;
	}

	/**
	 * @return the categoricalClassDescription, see {@link #categoricalClassDescription}
	 */
	public CategoricalClassDescription<?> getCategoricalClassDescription() {
		return categoricalClassDescription;
	}

	@Override
	public String toString() {
		String data = "";
		if (numericalProperties != null)
			data += "(numerical)";
		else if (categoricalClassDescription != null)
			data += "(categorical)";
		else
			data += "(hybrid/inhomogeneous)";

		return data;
	}

}


text:
<!DOCTYPE html>

<link href="resources/grid.css" rel="stylesheet">

This test checks that the grid items are shifted by the grid container's paddings before and start.


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

    <EditText
        android:id="@+id/multi_edit_text_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:gravity="start|top"
        android:layout_marginBottom="@dimen/padding_bottom"
        android:layout_marginLeft="@dimen/padding_left"
        android:layout_marginRight="@dimen/padding_right"
        android:layout_marginTop="@dimen/padding_top"
        android:inputType="textMultiLine">
    </EditText>

    <include android:id="@+id/separator" layout="@layout/separator" />

</LinearLayout>


text:
<?php
/**
 * General setup hooks and filters
 *
 * @package boutique
 */

/**
 * Styles / scripts
 */
add_action( 'wp_enqueue_scripts', 'boutique_enqueue_styles' );
add_action( 'wp_enqueue_scripts', 'boutique_enqueue_child_styles', 999 );

/**
 * Customizer default color tweaks
 */
add_filter( 'storefront_default_heading_color', 				'boutique_color_charcoal' );
add_filter( 'storefront_default_footer_heading_color', 			'boutique_color_charcoal' );
add_filter( 'storefront_default_button_text_color', 			'boutique_color_charcoal' );
add_filter( 'storefront_default_header_background_color', 		'boutique_color_charcoal' );
add_filter( 'storefront_default_footer_background_color', 		'boutique_color_charcoal' );

add_filter( 'storefront_default_header_link_color', 			'boutique_color_white' );
add_filter( 'storefront_default_header_text_color', 			'boutique_color_white' );
add_filter( 'storefront_default_button_alt_text_color', 		'boutique_color_white' );

add_filter( 'storefront_default_accent_color', 					'boutique_color_black' );
add_filter( 'storefront_default_footer_link_color', 			'boutique_color_black' );

add_filter( 'storefront_default_text_color', 					'boutique_color_english_winter' );
add_filter( 'storefront_default_footer_text_color', 			'boutique_color_english_winter' );

add_filter( 'storefront_default_accent_color', 					'boutique_color_gold' );
add_filter( 'storefront_default_button_alt_background_color', 	'boutique_color_gold' );

add_filter( 'storefront_default_background_color', 				'boutique_color_asphalt' );

add_filter( 'storefront_default_button_background_color', 		'boutique_color_newspaper' );


text:
import os
import sys
import tarfile

import requests
import tensorflow as tf
import tensorrt as trt
import graphsurgeon as gs
import uff

from utils.paths import PATHS

# UFF conversion functionality

# This class contains converted (UFF) model metadata
class ModelData(object):
    # Name of input node
    INPUT_NAME = "Input"
    # CHW format of model input
    INPUT_SHAPE = (3, 300, 300)
    # Name of output node
    OUTPUT_NAME = "NMS"

    @staticmethod
    def get_input_channels():
        return ModelData.INPUT_SHAPE[0]

    @staticmethod
    def get_input_height():
        return ModelData.INPUT_SHAPE[1]

    @staticmethod
    def get_input_width():
        return ModelData.INPUT_SHAPE[2]

def ssd_unsupported_nodes_to_plugin_nodes(ssd_graph):
    """Makes ssd_graph TensorRT comparible using graphsurgeon.

    This function takes ssd_graph, which contains graphsurgeon
    DynamicGraph data structure. This structure describes frozen Tensorflow
    graph, that can be modified using graphsurgeon (by deleting, adding,
    replacing certain nodes). The graph is modified by removing
    Tensorflow operations that are not supported by TensorRT's UffParser
    and replacing them with custom layer plugin nodes.

    Note: This specific implementation works only for
    ssd_inception_v2_coco_2017_11_17 network.

    Args:
        ssd_graph (gs.DynamicGraph): graph to convert
    Returns:
        gs.DynamicGraph: UffParser compatible SSD graph
    """
    # Create TRT plugin nodes to replace unsupported ops in Tensorflow graph
    channels = ModelData.get_input_channels()
    height = ModelData.get_input_height()
    width = ModelData.get_input_width()

    Input = gs.create_plugin_node(name="Input",
        op="Placeholder",
        dtype=tf.float32,
        shape=[1, channels, height, width])
    PriorBox = gs.create_plugin_node(name="GridAnchor", op="GridAnchor_TRT",
        minSize=0.2,
        maxSize=0.95,
        aspectRatios=[1.0, 2.0, 0.5, 3.0, 0.33],
        variance=[0.1,0.1,0.2,0.2],
        featureMapShapes=[19, 10, 5, 3, 2, 1],
        numLayers=6
    )
    NMS = gs.create_plugin_node(
        name="NMS",
        op="NMS_TRT",
        shareLocation=1,
        varianceEncodedInTarget=0,
        backgroundLabelId=0,
        confidenceThreshold=1e-8,
        nmsThreshold=0.6,
        topK=100,
        keepTopK=100,
        numClasses=91,
        inputOrder=[0, 2, 1],
        confSigmoid=1,
        isNormalized=1
    )
    concat_priorbox = gs.create_node(
        "concat_priorbox",
        op="ConcatV2",
        dtype=tf.float32,
        axis=2
    )
    concat_box_loc = gs.create_plugin_node(
        "concat_box_loc",
        op="FlattenConcat_TRT",
        dtype=tf.float32,
    )
    concat_box_conf = gs.create_plugin_node(
        "concat_box_conf",
        op="FlattenConcat_TRT",
        dtype=tf.float32,
    )

    # Create a mapping of namespace names -> plugin nodes.
    namespace_plugin_map = {
        "MultipleGridAnchorGenerator": PriorBox,
        "Postprocessor": NMS,
        "Preprocessor": Input,
        "ToFloat": Input,
        "image_tensor": Input,
        "MultipleGridAnchorGenerator/Concatenate": concat_priorbox,
        "MultipleGridAnchorGenerator/Identity": concat_priorbox,
        "concat": concat_box_loc,
        "concat_1": concat_box_conf
    }

    # Create a new graph by collapsing namespaces
    ssd_graph.collapse_namespaces(namespace_plugin_map)
    # Remove the outputs, so we just have a single output node (NMS).
    # If remove_exclusive_dependencies is True, the whole graph will be removed!
    ssd_graph.remove(ssd_graph.graph_outputs, remove_exclusive_dependencies=False)
    return ssd_graph

def model_to_uff(model_path, output_uff_path, silent=False):
    """Takes frozen .pb graph, converts it to .uff and saves it to file.

    Args:
        model_path (str): .pb model path
        output_uff_path (str): .uff path where the UFF file will be saved
        silent (bool): if True, writes progress messages to stdout

    """
    dynamic_graph = gs.DynamicGraph(model_path)
    dynamic_graph = ssd_unsupported_nodes_to_plugin_nodes(dynamic_graph)

    uff.from_tensorflow(
        dynamic_graph.as_graph_def(),
        [ModelData.OUTPUT_NAME],
        output_filename=output_uff_path,
        text=True
    )

# Model download functionality

def maybe_print(should_print, print_arg):
    """Prints message if supplied boolean flag is true.

    Args:
        should_print (bool): if True, will print print_arg to stdout
        print_arg (str): message to print to stdout
    """
    if should_print:
        print(print_arg)

def maybe_mkdir(dir_path):
    """Makes directory if it doesn't exist.

    Args:
        dir_path (str): directory path
    """
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

def download_file(file_url, file_dest_path, silent=False):
    """Downloads file from supplied URL and puts it into supplied directory.

    Args:
        file_url (str): URL with file to download
        file_dest_path (str): path to save downloaded file in
        silent (bool): if True, writes progress messages to stdout
    """
    with open(file_dest_path, "wb") as f:
        maybe_print(not silent, "Downloading {}".format(file_dest_path))
        response = requests.get(file_url, stream=True)
        total_length = response.headers.get('content-length')

        if total_length is None or silent: # no content length header or silent, just write file
            f.write(response.content)
        else: # not silent, print progress
            dl = 0
            total_length = int(total_length)
            for data in response.iter_content(chunk_size=4096):
                dl += len(data)
                f.write(data)
                done = int(50 * dl / total_length)
                sys.stdout.write(
                    "\rDownload progress [{}{}] {}%".format(
                        '=' * done, ' ' * (50-done),
                        int(100 * dl / total_length)))
                sys.stdout.flush()
            sys.stdout.write("\n")
            sys.stdout.flush()

def download_model(model_name, silent=False):
    """Downloads model_name from Tensorflow model zoo.

    Args:
        model_name (str): chosen object detection model
        silent (bool): if True, writes progress messages to stdout
    """
    maybe_print(not silent, "Preparing pretrained model")
    model_dir = PATHS.get_models_dir_path()
    maybe_mkdir(model_dir)
    model_url = PATHS.get_model_url(model_name)
    model_archive_path = os.path.join(model_dir, "{}.tar.gz".format(model_name))
    download_file(model_url, model_archive_path, silent)
    maybe_print(not silent, "Download complete\nUnpacking {}".format(model_archive_path))
    with tarfile.open(model_archive_path, "r:gz") as tar:
        tar.extractall(path=model_dir)
    maybe_print(not silent, "Extracting complete\nRemoving {}".format(model_archive_path))
    os.remove(model_archive_path)
    maybe_print(not silent, "Model ready")

def prepare_ssd_model(model_name="ssd_inception_v2_coco_2017_11_17", silent=False):
    """Downloads pretrained object detection model and converts it to UFF.

    The model is downloaded from Tensorflow object detection model zoo.
    Currently only ssd_inception_v2_coco_2017_11_17 model is supported
    due to model_to_uff() using logic specific to that network when converting.

    Args:
        model_name (str): chosen object detection model
        silent (bool): if True, writes progress messages to stdout
    """
    if model_name != "ssd_inception_v2_coco_2017_11_17":
        raise NotImplementedError(
            "Model {} is not supported yet".format(model_name))
    download_model(model_name, silent)
    ssd_pb_path = PATHS.get_model_pb_path(model_name)
    ssd_uff_path = PATHS.get_model_uff_path(model_name)
    model_to_uff(ssd_pb_path, ssd_uff_path, silent)


text:
#import "XCRefactoringFileChangeSet.h"

@interface XCRefactoringFileChangeSet (XCRefactoringModuleFileItem)
- (Class)moduleFileItemClass;
@end


text:
var expect = require('chai').expect

var local_enduro = require('../../index').quick_init()
var helper_handler = require(enduro.enduro_path + '/libs/helper_handler')

describe('Switch helper', function () {

	before(() => {
		return helper_handler.read_helpers()
	})

	it('should output default(last) value if no context is provided', function () {
		expect(enduro.templating_engine.compileSync('{{switch small "a"}}')()).to.equal('a')
	})

	it('should output second value if the context matches first condition', function () {
		expect(enduro.templating_engine.compileSync('{{switch small "5px" medium "10px" large "20px"}}')({medium: true})).to.equal('10px')
	})

	it('should output first value if more values match', function () {
		expect(enduro.templating_engine.compileSync('{{switch small "5px" medium "10px"}}')({small: true, medium: true})).to.equal('5px')
	})

})


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S11.5.2_A3_T2.9;
 * @section: 11.5.2;
 * @assertion: Operator x / y returns ToNumber(x) / ToNumber(y);
 * @description: Type(x) is different from Type(y) and both types vary between Boolean (primitive or object) and Null;
 */

//CHECK#1
if (true / null !== Number.POSITIVE_INFINITY) {
  $ERROR('#1: true / null === +Infinity. Actual: ' + (true / null));
}

//CHECK#2
if (null / true !== 0) {
  $ERROR('#2: null / true === 0. Actual: ' + (null / true));
}

//CHECK#3
if (new Boolean(true) / null !== Number.POSITIVE_INFINITY) {
  $ERROR('#3: new Boolean(true) / null === +Infinity. Actual: ' + (new Boolean(true) / null));
}

//CHECK#4
if (null / new Boolean(true) !== 0) {
  $ERROR('#4: null / new Boolean(true) === 0. Actual: ' + (null / new Boolean(true)));
}


text:
package com.intel.analytics.bigdl.torch

import java.io.PrintWriter

import com.intel.analytics.bigdl.nn._
import com.intel.analytics.bigdl.numeric.NumericDouble
import com.intel.analytics.bigdl.optim.{L2Regularizer, SGD}
import com.intel.analytics.bigdl.tensor.{Storage, Tensor}
import com.intel.analytics.bigdl.utils.RandomGenerator._
import com.intel.analytics.bigdl.utils.T

import scala.sys.process._

@com.intel.analytics.bigdl.tags.Serial
class LSTMSpec  extends TorchSpec {
  override def torchCheck(): Unit = {
    if (!TH.hasTorch()) {
      cancel("Torch is not installed")
    }
    val tmpFile = java.io.File.createTempFile("checkRNN", ".lua")
    val writer = new PrintWriter(tmpFile)
    writer.write("exist = (pcall(require, 'rnn'))\n print(exist)")
    writer.close()

    val existsRNN =
      Seq(System.getProperty("torch_location", "th"), tmpFile.getAbsolutePath).!!.trim
    if (!existsRNN.contains("true")) {
      cancel("Torch rnn is not installed")
    }
  }

  "A LSTM dropout " should "works correctly" in {
    val inputSize = 6
    val hiddenSize = 5
    val batchSize = 2
    val time = 2
    RNG.setSeed(100)
    val input = Tensor[Float](batchSize, time, inputSize)
    println(s"input = ${input}")
    val model = Recurrent[Float]().add(LSTM[Float](inputSize, hiddenSize, p = 0.1))
    val output = model.forward(input)
    println(s"output = ${output}")
  }

  "A LSTM L2 regularizer" should "works correctly" in {
    import com.intel.analytics.bigdl.numeric.NumericDouble
    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val seqLength = 5
    val seed = 100

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(1, seqLength, inputSize))
    val labels = Tensor[Double](Array(1, seqLength))
    for (i <- 1 to seqLength) {
      val rdmLabel = Math.ceil(RNG.uniform(0, 1) * outputSize).toInt
      val rdmInput = Math.ceil(RNG.uniform(0, 1) * inputSize).toInt
      input.setValue(1, i, rdmInput, 1.0)
      labels.setValue(1, i, rdmLabel)
    }

    println(input)
    val rec1 = Recurrent[Double]()
    val rec2 = Recurrent[Double]()

    val model1 = Sequential[Double]()
      .add(rec1
        .add(LSTM[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val model2 = Sequential[Double]()
      .add(rec2
        .add(LSTM[Double](inputSize, hiddenSize, uRegularizer = L2Regularizer(0.1),
          wRegularizer = L2Regularizer(0.1), bRegularizer = L2Regularizer(0.1))))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize,
        wRegularizer = L2Regularizer(0.1), bRegularizer = L2Regularizer(0.1))))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val state1 = T("learningRate" -> 0.1, "learningRateDecay" -> 5e-7,
      "weightDecay" -> 0.1, "momentum" -> 0.002)
    val state2 = T("learningRate" -> 0.1, "learningRateDecay" -> 5e-7,
      "weightDecay" -> 0.0, "momentum" -> 0.002)

    val (weights1, grad1) = model1.getParameters()
    val (weights2, grad2) = model2.getParameters()
    weights2.copy(weights1.clone())
    grad2.copy(grad1.clone())

    val sgd = new SGD[Double]

    def feval1(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model1.forward(input).toTensor[Double]
      val _loss = criterion.forward(output, labels)
      model1.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model1.backward(input, gradInput)
      (_loss, grad1)
    }

    def feval2(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model2.forward(input).toTensor[Double]
      val _loss = criterion.forward(output, labels)
      model2.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model2.backward(input, gradInput)
      (_loss, grad2)
    }

    var loss1: Array[Double] = null
    for (i <- 1 to 100) {
      loss1 = sgd.optimize(feval1, weights1, state1)._2
      println(s"${i}-th loss = ${loss1(0)}")
    }

    var loss2: Array[Double] = null
    for (i <- 1 to 100) {
      loss2 = sgd.optimize(feval2, weights2, state2)._2
      println(s"${i}-th loss = ${loss2(0)}")
    }

    weights1 should be(weights2)
    loss1 should be(loss2)
  }

  "A LSTM " should "has same loss as torch rnn" in {
    torchCheck()

    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(1, seqLength, inputSize))
    val labels = Tensor[Double](Array(1, seqLength))
    for (i <- 1 to seqLength) {
      val rdmLabel = Math.ceil(RNG.uniform(0, 1) * outputSize).toInt
      val rdmInput = Math.ceil(RNG.uniform(0, 1) * inputSize).toInt
      input.setValue(1, i, rdmInput, 1.0)
      labels.setValue(1, i, rdmLabel)
    }

//    println(input)
    val rec = Recurrent[Double]()

    val model = Sequential[Double]()
      .add(rec
        .add(LSTM[Double](inputSize, hiddenSize)))
      //      .add(LSTM[Double](inputSize, hiddenSize)))
      //      .add(RnnCell[Double](inputSize, hiddenSize, Sigmoid[Double]())))
      //            .add(FastLSTMCell[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double]())
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val code =
      s"""
         |
      |-- 1.4. Combine 1.1 and 1.3 to produce final model
         |require 'rnn'
         |torch.manualSeed($seed)
         |
      |local rm =  nn.Sequential() -- input is {x[t], h[t-1]}
         |         :add(nn.ParallelTable()
         |            :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         |            :add(nn.Linear($hiddenSize, $hiddenSize))) -- recurrent layer
         |         :add(nn.CAddTable()) -- merge
         |         :add(nn.Sigmoid()) -- transfer
         |     --    :add(nn.Tanh()) -- transfer
         |
      | -- local rm1 =  nn.Sequential() -- input is {x[t], h[t-1]}
         | --        :add(nn.ParallelTable()
         | --           :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         | --           :add(nn.Identity())) -- recurrent layer
         | --        :add(nn.CAddTable()) -- merge
         | --        :add(nn.Sigmoid()) -- transfer
         |      rnn = nn.Recurrence(rm, $hiddenSize, 1)
         | --     rnn.userPrevOutput = torch.Tensor(1, $hiddenSize):zero()
         |
      |model = nn.Sequential()
         |:add(nn.SplitTable(1))
         |:add(nn.Sequencer(
         | nn.Sequential()
         |   --:add(nn.LSTM($inputSize, $hiddenSize, 1, true))
         |   :add(nn.FastLSTM($inputSize, $hiddenSize))
         |   :add(nn.Linear($hiddenSize, $outputSize))
         |   ))
         |
         |
         |local parameters, gradParameters = model:getParameters()
         |model:zeroGradParameters()
         |parameters:copy(weights)
         |
         |parameters_initial = parameters : clone()
         |gradParameters_initial = gradParameters : clone()
         |
         |local criterion =  nn.SequencerCriterion(nn.CrossEntropyCriterion())
         |
      |
      |state = {
         |  learningRate = 0.5,
         |  momentum = 0.0,
         |  dampening = 0.0,
         |  weightDecay = 0.0
         |}
         |
      |feval = function(x)
         |model:zeroGradParameters()
         |model_initial = model : clone()
         |
      |local output1 = model:forward(input)
         |local err1 = criterion:forward(output1, labels)
         |local gradOutput1 = criterion:backward(output1, labels)
         |model:backward(input, gradOutput1)
         |return err1, gradParameters
         |end
         |
      |for i = 1,100,1 do
         |   optim.sgd(feval, parameters, state)
         |end
         |
         |err=criterion.output
         |err2=criterion.gradInput
         |gradInput = model.gradInput
    """.stripMargin

    val (luaTime, torchResult) = TH.run(code,
      Map("input" -> input.transpose(1, 2), "weights" -> weights,
        "labels" -> SplitTable[Double](1).forward(labels.t())),
      Array("err", "parameters", "gradParameters", "output2", "gradInput", "err2"))

    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.forward(input).toTensor[Double].clone())
    //
    val luaOutput2 = torchResult("err").asInstanceOf[Double]
    val luaweight = torchResult("parameters").asInstanceOf[Tensor[Double]]

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 100) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    //    println("Element weight: " + luaweight)
    //    println("BigDL weight: " + weights)
    //
    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.output)
    //
    //    println("BigDL labels: " + labels)
    //
    //    val crtnGradInput = criterion.backward(model.output, labels)
    //    println(s"element: criterion gradInput: $err2")
    //    println("BigDL criterion gradInput: " + crtnGradInput)
    //
    //    println(s"element: gradInput: $gradInput1")
    //    println("BigDL: " + model.gradInput.toTensor[Double])
    //
    //    println(s"element: gradWeight: $gradParameters")
    //    println("BigDL: " + model.getParameters()._2)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    luaOutput2 should be(loss(0) +- 1e-5)
  }

  "A LSTM " should "has same loss as torch rnn in batch mode" in {
    torchCheck()

    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100
    val batchSize = 5

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(batchSize, seqLength, inputSize))
    val labels = Tensor[Double](Array(batchSize, seqLength))
    for (b <- 1 to batchSize) {
      for (i <- 1 to seqLength) {
        val rdmInput = Math.ceil(RNG.uniform(0, 1)  * inputSize).toInt
        input.setValue(b, i, rdmInput, 1.0)
        val rdmLabel = Math.ceil(RNG.uniform(0, 1)  * outputSize).toInt
        labels.setValue(b, i, rdmLabel)
      }
    }
    val rec = Recurrent[Double]()

    val model = Sequential[Double]()
      .add(rec
        .add(LSTM[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val code =
      s"""
         |
      |-- 1.4. Combine 1.1 and 1.3 to produce final model
         |require 'rnn'
         |torch.manualSeed($seed)
         |
      |local rm =  nn.Sequential() -- input is {x[t], h[t-1]}
         |         :add(nn.ParallelTable()
         |            :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         |            :add(nn.Linear($hiddenSize, $hiddenSize))) -- recurrent layer
         |         :add(nn.CAddTable()) -- merge
         |         :add(nn.Sigmoid()) -- transfer
         |     --    :add(nn.Tanh()) -- transfer
         |
      |model = nn.Sequential()
         |:add(nn.SplitTable(1))
         |:add(nn.Sequencer(
         | nn.Sequential()
         |   --:add(nn.LSTM($inputSize, $hiddenSize, 1, true))
         |   :add(nn.FastLSTM($inputSize, $hiddenSize, 1))
         |   :add(nn.Linear($hiddenSize, $outputSize))
         |   ))
         |
         |
         |local parameters, gradParameters = model:getParameters()
         |model:zeroGradParameters()
         |parameters:copy(weights)
         |
         |parameters_initial = parameters : clone()
         |gradParameters_initial = gradParameters : clone()
         |
         |local criterion =  nn.SequencerCriterion(nn.CrossEntropyCriterion())
         |
      |
      |state = {
         |  learningRate = 0.5,
         |  momentum = 0.0,
         |  dampening = 0.0,
         |  weightDecay = 0.0
         |}
         |
      |feval = function(x)
         |model:zeroGradParameters()
         |model_initial = model : clone()
         |
      |local output1 = model:forward(input)
         |local err1 = criterion:forward(output1, labels)
         |local gradOutput1 = criterion:backward(output1, labels)
         |model:backward(input, gradOutput1)
         |return err1, gradParameters
         |end
         |
      |for i = 1,100,1 do
         |   optim.sgd(feval, parameters, state)
         |end
         |
         |err=criterion.output
         |err2=criterion.gradInput
         |gradInput = model.gradInput
    """.stripMargin

    val (luaTime, torchResult) = TH.run(code,
      Map("input" -> input.transpose(1, 2), "weights" -> weights,
        "labels" -> SplitTable[Double](1).forward(labels.t())),
      Array("err", "parameters", "gradParameters", "output2", "gradInput", "err2"))

    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.forward(input).toTensor[Double].clone())
    //
    val luaOutput2 = torchResult("err").asInstanceOf[Double]
    val luaweight = torchResult("parameters").asInstanceOf[Tensor[Double]]

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 100) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    //    println("Element weight: " + luaweight)
    //    println("BigDL weight: " + weights)
    //
    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.output)
    //
    //    println("BigDL labels: " + labels)
    //
    //    val crtnGradInput = criterion.backward(model.output, labels)
    //    println(s"element: criterion gradInput: $err2")
    //    println("BigDL criterion gradInput: " + crtnGradInput)
    //
    //    println(s"element: gradInput: $gradInput1")
    //    println("BigDL: " + model.gradInput.toTensor[Double])
    //
    //    println(s"element: gradWeight: $gradParameters")
    //    println("BigDL: " + model.getParameters()._2)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)

    luaOutput2 should be(loss(0) +- 1e-5)
  }

  "A LSTM " should "converge" in {
    torchCheck()

    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100

    val input = Tensor[Double](Array(1, seqLength, inputSize))
    val labels = Tensor[Double](Array(1, seqLength))
    for (i <- 1 to seqLength) {
      val rdmLabel = Math.ceil(RNG.uniform(0, 1) * outputSize).toInt
      val rdmInput = Math.ceil(RNG.uniform(0, 1) * inputSize).toInt
      input.setValue(1, i, rdmInput, 1.0)
      labels.setValue(1, i, rdmLabel)
    }

    println(input)
    RNG.setSeed(seed)
    val rec = Recurrent[Double]()

    val model = Sequential[Double]()
      .add(rec
        .add(LSTM[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 100) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    labels.squeeze() should be (prediction.squeeze())
  }

  "A LSTM " should "converge in batch mode" in {
    torchCheck()

    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val batchSize = 3
    val seqLength = 5
    val seed = 100

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(batchSize, seqLength, inputSize))
    val labels = Tensor[Double](Array(batchSize, seqLength))
    for (b <- 1 to batchSize) {
      for (i <- 1 to seqLength) {
        val rdmInput = Math.ceil(RNG.uniform(0.0, 1.0) * inputSize).toInt
        input.setValue(b, i, rdmInput, 1.0)
        val rdmLabel = Math.ceil(RNG.uniform(0.0, 1.0) * outputSize).toInt
        labels.setValue(b, i, rdmLabel)
      }
    }

    println(input)
    val rec = Recurrent[Double]()

    val model = Sequential[Double]()
      .add(rec
        .add(LSTM[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 300) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    labels.squeeze() should be (prediction.squeeze())
  }
}


text:
service "nginx" do
  enabled true
  running true
  supports :status => true, :restart => true, :reload => true
  action [:start, :enable]
end

cookbook_file "/etc/nginx/conf.d/neverlate.conf" do
  source "neverlate_nginx.conf"
  mode 0640
  owner "root"
  group "root"
  notifies :restart, resources(:service => "nginx")
end


text:
#include <wchar.h>
#include <locale/localeinfo.h>

size_t
wcsftime (wchar_t *s, size_t maxsize, const wchar_t *format,
	  const struct tm *tp)
{
  return __wcsftime_l (s, maxsize, format, tp, _NL_CURRENT_LOCALE);
}
libc_hidden_def (wcsftime)


text:
package com.gs.collections.impl.jmh.domain;

import java.math.BigDecimal;

public final class Position
{
    private final Account account;
    private final Product product;
    private final int quantity;

    public Position(Account account, Product product, int quantity)
    {
        this.account = account;
        this.product = product;
        this.quantity = quantity;
    }

    public Account getAccount()
    {
        return this.account;
    }

    public Product getProduct()
    {
        return this.product;
    }

    public String getCategory()
    {
        return this.product.getCategory();
    }

    public int getQuantity()
    {
        return this.quantity;
    }

    public double getMarketValue()
    {
        return this.quantity * this.product.getPrice();
    }

    public BigDecimal getPreciseMarketValue()
    {
        return BigDecimal.valueOf(this.quantity).multiply(this.product.getPrecisePrice());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Croller">
        <attr name="enabled" format="boolean" />
        <attr name="start_progress" format="integer" />
        <attr name="label" format="string" />
        <attr name="back_circle_color" format="color" />
        <attr name="back_circle_disable_color" format="color" />
        <attr name="main_circle_color" format="color" />
        <attr name="main_circle_disable_color" format="color" />
        <attr name="indicator_color" format="color" />
        <attr name="indicator_disable_color" format="color" />
        <attr name="progress_primary_color" format="color" />
        <attr name="progress_primary_disable_color" format="color" />
        <attr name="progress_secondary_color" format="color" />
        <attr name="progress_secondary_disable_color" format="color" />
        <attr name="label_size" format="dimension" />
        <attr name="label_color" format="color" />
        <attr name="label_font" format="string" />
        <attr name="label_style" format="enum" >
            <enum name="normal" value="0"/>
            <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
            <enum name="bold_italic" value="3"/>
        </attr>
        <attr name="label_disabled_color" format="color" />
        <attr name="indicator_width" format="float" />
        <attr name="is_continuous" format="boolean" />
        <attr name="progress_primary_circle_size" format="float" />
        <attr name="progress_secondary_circle_size" format="float" />
        <attr name="progress_primary_stroke_width" format="float" />
        <attr name="progress_secondary_stroke_width" format="float" />
        <attr name="sweep_angle" format="integer" />
        <attr name="start_offset" format="integer" />
        <attr name="max" format="integer" />
        <attr name="min" format="integer" />
        <attr name="main_circle_radius" format="float" />
        <attr name="back_circle_radius" format="float" />
        <attr name="progress_radius" format="float" />
        <attr name="anticlockwise" format="boolean" />
    </declare-styleable>
</resources>


text:
import { colorify } from "../log";

console.log(colorify.bold(process.argv[2] || "no message"));


text:
<?php

namespace Weserv\Images\Test\Manipulators;

use Jcupitt\Vips\Image;
use Mockery\MockInterface;
use Weserv\Images\Api\Api;
use Weserv\Images\Client;
use Weserv\Images\Manipulators\Helpers\Utils;
use Weserv\Images\Manipulators\Orientation;
use Weserv\Images\Test\ImagesWeservTestCase;

class OrientationTest extends ImagesWeservTestCase
{
    /**
     * @var Client|MockInterface $client
     */
    private $client;

    /**
     * @var Api $api
     */
    private $api;

    /**
     * @var Orientation $manipulator
     */
    private $manipulator;

    public function setUp()
    {
        $this->client = $this->getMockery(Client::class);
        $this->api = new Api($this->client, $this->getManipulators());
        $this->manipulator = new Orientation();
    }

    public function testCreateInstance(): void
    {
        $this->assertInstanceOf(Orientation::class, $this->manipulator);
    }

    /**
     * Rotate by any 90-multiple angle
     */
    public function testRotateBy90MultipleAngle(): void
    {
        $testImage = $this->inputJpg320x240;

        $uri = basename($testImage);

        $this->client->shouldReceive('get')->with($uri)->andReturn($testImage);

        foreach ([-3690, -450, -90, 90, 450, 3690] as $angle) {
            $params = [
                'or' => $angle
            ];

            /** @var Image $image */
            $image = $this->api->run($uri, $params);

            $this->assertEquals(240, $image->width);
            $this->assertEquals(320, $image->height);
            $this->assertFalse($image->hasAlpha());
        }
    }

    /**
     * Rotate by any 180-multiple angle
     */
    public function testRotateBy180MultipleAngle(): void
    {
        $testImage = $this->inputJpg320x240;

        $uri = basename($testImage);

        $this->client->shouldReceive('get')->with($uri)->andReturn($testImage);

        foreach ([-3780, -540, 0, 180, 540, 3780] as $angle) {
            $params = [
                'or' => $angle
            ];

            /** @var Image $image */
            $image = $this->api->run($uri, $params);

            $this->assertEquals(320, $image->width);
            $this->assertEquals(240, $image->height);
            $this->assertFalse($image->hasAlpha());
        }
    }

    /**
     * EXIF Orientation, auto-rotate
     */
    public function testAutoRotate(): void
    {
        foreach (['Landscape', 'Portrait'] as $orientation) {
            foreach ([1, 2, 3, 4, 5, 6, 7, 8] as $exifTag) {
                $fixture = 'inputJpgWith' . $orientation . 'Exif' . $exifTag;

                $testImage = $this->{$fixture};
                $expectedImage = $this->expectedDir . '/' . $orientation . '_' . $exifTag . '-out.jpg';

                $uri = basename($testImage);

                $this->client->shouldReceive('get')->with($uri)->andReturn($testImage);

                $params = [
                    'w' => '320'
                ];

                /** @var Image $image */
                $image = $this->api->run($uri, $params);

                $this->assertEquals(320, $image->width);
                $this->assertEquals($orientation === 'Landscape' ? 240 : 427, $image->height);
                $this->assertFalse($image->hasAlpha());

                // Check if the EXIF orientation header is removed
                $this->assertEquals(0, $image->typeof(Utils::VIPS_META_ORIENTATION));

                $this->assertSimilarImage($expectedImage, $image);
            }
        }
    }
}


text:
export ProxGradParams, fit!

type ProxGradParams<:AbstractParams
    stepsize::Float64 # initial stepsize
    max_iter::Int # maximum number of outer iterations
    inner_iter::Int # how many prox grad steps to take on X before moving on to Y (and vice versa)
    convergence_tol::Float64 # stop if objective decrease upon one outer iteration is less than this
    min_stepsize::Float64 # use a decreasing stepsize, stop when reaches min_stepsize
end
function ProxGradParams(stepsize::Number=1.0; # initial stepsize
				        max_iter::Int=100, # maximum number of outer iterations
				        inner_iter::Int=1, # how many prox grad steps to take on X before moving on to Y (and vice versa)
				        convergence_tol::Number=0.00001, # stop if objective decrease upon one outer iteration is less than this
				        min_stepsize::Number=0.01*stepsize) # stop if stepsize gets this small
    stepsize = convert(Float64, stepsize)
    return ProxGradParams(convert(Float64, stepsize),
                          max_iter,
                          inner_iter,
                          convert(Float64, convergence_tol),
                          convert(Float64, min_stepsize))
end

### FITTING
function fit!(glrm::GLRM, params::ProxGradParams;
			  ch::ConvergenceHistory=ConvergenceHistory("ProxGradGLRM"),
			  verbose=true,
			  kwargs...)
	println(params)
	### initialization
	A = glrm.A # rename these for easier local access
	losses = glrm.losses
	rx = glrm.rx
	ry = glrm.ry
	# at any time, glrm.X and glrm.Y will be the best model yet found, while
	# X and Y will be the working variables
	X = copy(glrm.X); Y = copy(glrm.Y)
	k = glrm.k

	m,n = size(A)
	XY = Array(Float64, (m, n))
	gemm!('T','N',1.0,X,Y,0.0,XY) # XY = X' * Y initial calculation

    # check that we didn't initialize to zero (otherwise we will never move)
    if norm(Y) == 0
    	Y = .1*randn(k,n)
    end

    # step size (will be scaled below to ensure it never exceeds 1/\|g\|_2 or so for any subproblem)
    alpha = params.stepsize
    # stopping criterion: stop when decrease in objective < tol
    tol = params.convergence_tol * mapreduce(length,+,glrm.observed_features)

    # alternating updates of X and Y
    if verbose println("Fitting GLRM") end
    update!(ch, 0, objective(glrm))
    t = time()
    steps_in_a_row = 0
    g = zeros(k)

    # cache views
    ve = ContiguousView{Float64,1,Array{Float64,2}}[view(X,:,e) for e=1:m]
    vf = ContiguousView{Float64,1,Array{Float64,2}}[view(Y,:,f) for f=1:n]

    for i=1:params.max_iter
# STEP 1: X update
        # XY = X' * Y this is computed before the first iteration and subsequently in the objective evaluation
        for inneri=1:params.inner_iter
        for e=1:m # doing this means looping over XY in row-major order, but otherwise we couldn't parallelize over Xᵢs
            scale!(g, 0)# reset gradient to 0
            # compute gradient of L with respect to Xᵢ as follows:
            # ∇{Xᵢ}L = Σⱼ dLⱼ(XᵢYⱼ)/dXᵢ
            for f in glrm.observed_features[e]
                # but we have no function dLⱼ/dXᵢ, only dLⱼ/d(XᵢYⱼ) aka dLⱼ/du
                # by chain rule, the result is: Σⱼ (dLⱼ(XᵢYⱼ)/du * Yⱼ), where dLⱼ/du is our grad() function
                axpy!(grad(losses[f],XY[e,f],A[e,f]), vf[f], g)
            end
            # take a proximal gradient step
            l = length(glrm.observed_features[e]) + 1
            scale!(g, -alpha/l)
            ## gradient step: Xᵢ += -(α/l) * ∇{Xᵢ}L
            axpy!(1,g,ve[e])
            ## prox step: Xᵢ = prox_rx(Xᵢ, α/l)
            prox!(rx,ve[e],alpha/l)
        end
    	end
        gemm!('T','N',1.0,X,Y,0.0,XY) # Recalculate XY using the new X
# STEP 2: Y update
        for inneri=1:params.inner_iter
        for f=1:n
            scale!(g, 0) # reset gradient to 0
            # compute gradient of L with respect to Yⱼ as follows:
            # ∇{Yⱼ}L = Σⱼ dLⱼ(XᵢYⱼ)/dYⱼ
            for e in glrm.observed_examples[f]
                # but we have no function dLⱼ/dYⱼ, only dLⱼ/d(XᵢYⱼ) aka dLⱼ/du
                # by chain rule, the result is: Σⱼ dLⱼ(XᵢYⱼ)/du * Xᵢ, where dLⱼ/du is our grad() function
            	axpy!(grad(losses[f],XY[e,f],A[e,f]), ve[e], g)
            end
            # take a proximal gradient step
            l = length(glrm.observed_examples[f]) + 1
            scale!(g, -alpha/l)
            ## gradient step: Yⱼ += -(α/l) * ∇{Yⱼ}L
            axpy!(1,g,vf[f])
            ## prox step: Yⱼ = prox_ryⱼ(Yⱼ, α/l)
            prox!(ry[f],vf[f],alpha/l)
        end
        end
        gemm!('T','N',1.0,X,Y,0.0,XY) # Recalculate XY using the new Y
# STEP 3: Check objective
        obj = objective(glrm, X, Y, XY)
        # record the best X and Y yet found
        if obj < ch.objective[end]
            t = time() - t
            update!(ch, t, obj)
            copy!(glrm.X, X); copy!(glrm.Y, Y)
            alpha = alpha * 1.05
            steps_in_a_row = max(1, steps_in_a_row+1)
            t = time()
        else
            # if the objective went up, reduce the step size, and undo the step
            alpha = alpha / max(1.5, -steps_in_a_row)
            if verbose println("obj went up to $obj; reducing step size to $alpha") end
            copy!(X, glrm.X); copy!(Y, glrm.Y)
            steps_in_a_row = min(0, steps_in_a_row-1)
            gemm!('T','N',1.0,X,Y,0.0,XY) # Revert back to the old XY (previous best)
        end
# STEP 4: Check stopping criterion
        if i>10 && (steps_in_a_row > 3 && ch.objective[end-1] - obj < tol) || alpha <= params.min_stepsize
            break
        end
        if verbose && i%10==0
            println("Iteration $i: objective value = $(ch.objective[end])")
        end
    end
    t = time() - t
    update!(ch, t, ch.objective[end])

    return glrm.X, glrm.Y, ch
end


text:
@interface ActivityChartView : NSView

- (void)addDataPoint:(NSNumber *)point;

@end


text:
/**
 * Created by carlovespa on 21/07/16.
 */
var should = require('should');
var request = require('supertest');

var PermanentDb = require('../../utils/createDbConnection.js').PermanentDb;
var config = require('../../config.js');

var Person = require('../../model/person.js');
var PeopleDAO = require('../../db/peopleDAO.js');

function getDefaultValidPerson() {
    return new Person(
        'Name', 'Surname', new Date('1990-01-01'),
        'Some notes', 'Hometown', 'XY',
        'Address', 'City', 'YZ'
    );
}

function TestPeopleAPI() {
    describe('getAll', () => {
        it('should return list of people insertInto\'d DB', done => {
            let db = PermanentDb(config.testDbFile);

            let p = getDefaultValidPerson();

            PeopleDAO.createSchema(db)
                .then(() => PeopleDAO.insertInto(db, p))
                .then(() => new Promise((resolve, reject) => {
                        request(config.rootUrl)
                            .get('/api/people/')
                            .expect(200)
                            .end((err, res) => {
                                if (!err) {
                                    res.body.status.should.equal(200);
                                    res.body.people.length.should.equal(1);

                                    resolve();
                                } else {
                                    reject(err);
                                }
                            });
                    }))
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });
    });

    describe('getId', () => {
        it('should return the person insertInto\'d DB', done => {
            let db = PermanentDb(config.testDbFile);

            let p = getDefaultValidPerson();

            PeopleDAO.createSchema(db)
                .then(() => PeopleDAO.insertInto(db, p))
                .then(ID => new Promise((resolve, reject) => {
                    request(config.rootUrl)
                        .get('/api/people/' + ID)
                        .expect(200)
                        .end((err, res) => {
                            if (!err) {
                                res.body.status.should.equal(200);
                                should.exist(res.body.person);

                                resolve();
                            } else {
                                reject(err);
                            }
                        });
                }))
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });

        it('should return 404 if the ID is not found', done => {
            let db = PermanentDb(config.testDbFile);

            let fakeID = 42;

            PeopleDAO.createSchema(db)
                .then(() => new Promise((resolve, reject) => {
                    request(config.rootUrl)
                        .get('/api/people/' + fakeID)
                        .expect(404)
                        .end((err, res) => {
                            if (!err) {
                                res.body.status.should.equal(404);

                                resolve();
                            } else {
                                reject(err);
                            }
                        });
                }))
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });
    });

    describe('insertInto', () => {
        it('should add new person to DB', done => {
            let db = PermanentDb(config.testDbFile);

            let p = getDefaultValidPerson();

            PeopleDAO.createSchema(db)
                .then(() => new Promise((resolve, reject) => {
                    request(config.rootUrl)
                        .post('/api/people/')
                        .send(p)
                        .expect(200)
                        .end((err, res) => {
                            if (!err) {
                                res.body.status.should.equal(200);
                                should.exist(res.body.ID);

                                resolve(res.body.ID);
                            } else {
                                reject(err);
                            }
                        });
                }))
                .then(ID => PeopleDAO.getId(db, ID))
                .then(person => {
                    person.firstname.should.equal(p.firstname);
                    person.lastname.should.equal(p.lastname);
                    person.birthday.should.equal(p.birthday.getTime());
                    person.notes.should.equal(p.notes);
                    person.homecity.should.equal(p.homecity);
                    person.homecountry.should.equal(p.homecountry);
                    person.currentaddress.should.equal(p.currentaddress);
                    person.currentcity.should.equal(p.currentcity);
                    person.currentcountry.should.equal(p.currentcountry);
                })
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });
    });

    describe('update', () => {
        let fields = ['firstname', 'lastname', 'notes', 'homecity', 'homecountry', 'currentaddress', 'currentcity', 'currentcountry'];
        for (let field of fields) {
            it('should update single field ' + field + ' in the DB', done => {
                let db = PermanentDb(config.testDbFile);

                let p = getDefaultValidPerson();

                let updated_p = {};
                updated_p[field] = 'up';

                PeopleDAO.createSchema(db)
                    .then(() => PeopleDAO.insertInto(db, p))
                    .then(ID => new Promise((resolve, reject) => {
                        request(config.rootUrl)
                            .put('/api/people/' + ID)
                            .send(updated_p)
                            .expect(200)
                            .end((err, res) => {
                                if (!err) {
                                    res.body.status.should.equal(200);

                                    resolve(ID);
                                } else {
                                    reject(err);
                                }
                            });
                    }))
                    .then(ID => PeopleDAO.getId(db, ID))
                    .then(person => {
                        person[field].should.equal(updated_p[field]);
                    })
                    .catch(err => err)
                    .then(err => {
                        db.close();
                        done(err);
                    });
            });
        }

        it('should update multiple fields birthday, currentaddress, currentcity in the DB', done => {
            let db = PermanentDb(config.testDbFile);

            let p = getDefaultValidPerson();

            let updated_p = {};
            updated_p.birthday = new Date();
            updated_p.currentaddress = 'new address';
            updated_p.currentcity = 'new city';

            PeopleDAO.createSchema(db)
                .then(() => PeopleDAO.insertInto(db, p))
                .then(ID => new Promise((resolve, reject) => {
                    request(config.rootUrl)
                        .put('/api/people/' + ID)
                        .send(updated_p)
                        .expect(200)
                        .end((err, res) => {
                            if (!err) {
                                res.body.status.should.equal(200);

                                resolve(ID);
                            } else {
                                reject(err);
                            }
                        });
                }))
                .then(ID => PeopleDAO.getId(db, ID))
                .then(person => {
                    person.birthday.should.equal(updated_p.birthday.getTime());
                    person.currentaddress.should.equal(updated_p.currentaddress);
                    person.currentcity.should.equal(updated_p.currentcity);
                })
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });
    });

    describe('deleteFrom', () => {
        it('should remove the insertInto\'d person', done => {
            let db = PermanentDb(config.testDbFile);

            let p = getDefaultValidPerson();

            PeopleDAO.createSchema(db)
                .then(() => PeopleDAO.insertInto(db, p))
                .then(ID => new Promise((resolve, reject) => {
                    request(config.rootUrl)
                        .delete('/api/people/' + ID)
                        .expect(200)
                        .end((err, res) => {
                            if (!err) {
                                res.body.status.should.equal(200);

                                resolve();
                            } else {
                                reject(err);
                            }
                        });
                }))
                .then(() => PeopleDAO.getAll(db))
                .then(people => {
                    people.length.should.equal(0);
                })
                .catch(err => err)
                .then(err => {
                    db.close();
                    done(err);
                });
        });
    })
}

module.exports = TestPeopleAPI;


text:
@CHARSET "ISO-8859-1";

#banner-1 {
	position: absolute;
	top: 0px;
	left: 0px;
	right: 0px;
}

#banner-2 {
	display:none;
	position: absolute;
	bottom: 0px;
	left: 0px;
	right: 0px;
}

.banner-text {
	font-weight: bold;
	width: 250px;
	margin-left: auto;
	margin-right: auto;
	background-color: #C5C3C1; /*#74B446 #C1E0AA*/
	color: white;
	text-align: center;
	white-space: nowrap;
	padding-bottom: 2px;
	z-index: 999999999;
	position: relative;
}

.banner-text:before {
	content: "Semi-Anonymized Snapshot";
}

#banner-1-text {
	-moz-border-radius-bottomleft : 4px;
	-webkit-border-bottom-left-radius : 4px;
	-khtml-border-bottom-left-radius : 4px;
	border-bottom-left-radius : 4px;
	-moz-border-radius-bottomright : 4px;
	-webkit-border-bottom-right-radius : 4px;
	-khtml-border-bottom-right-radius : 4px;
	border-bottom-right-radius : 4px;
}

#banner-2-text {
	-moz-border-radius-topleft : 4px;
	-webkit-border-top-left-radius : 4px;
	-khtml-border-top-left-radius : 4px;
	border-top-left-radius : 4px;
	-moz-border-radius-topright : 4px;
	-webkit-border-top-right-radius : 4px;
	-khtml-border-top-right-radius : 4px;
	border-top-right-radius : 4px;
}

/* When showing a logo you need to hide its fallback children. See next css block */
.app-logo {
	width: 121px;
	height: 64px;
	z-index: 1;
	background-image: url(../img/kiva_summary.png);
	background-repeat: no-repeat;
	margin-bottom: 10px;

}

/* Hide all logo children, otherwise a label will appear */
.app-logo * {
	display: none;
}


text:
import backoff
from google.api_core.exceptions import RetryError
from google.api_core.exceptions import ServiceUnavailable
from google.cloud.storage import Bucket

import posix_request

@backoff.on_exception(backoff.expo, (RetryError, ServiceUnavailable,), max_time=60)
def test_posix_request(
        capsys, project_id: str, job_description_unique: str,
        agent_pool_name: str, posix_root_directory: str,
        destination_bucket: Bucket):

    posix_request.transfer_from_posix_to_gcs(
        project_id=project_id,
        description=job_description_unique,
        source_agent_pool_name=agent_pool_name,
        root_directory=posix_root_directory,
        sink_bucket=destination_bucket.name
    )

    out, _ = capsys.readouterr()

    assert "Created transferJob" in out


text:
module Refinery
  module Core
    describe Engine do
      describe "#refinery_inclusion!" do
        it "should be idempotent" do
          expect { visit(refinery.root_path) }.to_not raise_error
          Engine.refinery_inclusion!
          Engine.refinery_inclusion!
          expect { visit(refinery.root_path) }.to_not raise_error
        end
      end
    end
  end
end