text:
Odnoklassniki.ru
================

Odnoklassniki.ru uses OAuth2 workflow, to use it fill in settings::

    ODNOKLASSNIKI_OAUTH2_CLIENT_KEY = ''
    ODNOKLASSNIKI_OAUTH2_APP_KEY = ''
    ODNOKLASSNIKI_OAUTH2_CLIENT_SECRET = ''


text:
module Part2.Problem55 where

import           Part1.Problem32 (digits, fromDigits)

--
-- Problem 55: Lychrel numbers
--
-- If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
--
-- Not all numbers produce palindromes so quickly. For example,
--
-- 349 + 943 = 1292,
-- 1292 + 2921 = 4213
-- 4213 + 3124 = 7337
--
-- That is, 349 took three iterations to arrive at a palindrome.
--
-- Although no one has proved it yet, it is thought that some numbers, like 196,
-- never produce a palindrome. A number that never forms a palindrome through
-- the reverse and add process is called a Lychrel number. Due to the
-- theoretical nature of these numbers, and for the purpose of this problem, we
-- shall assume that a number is Lychrel until proven otherwise. In addition you
-- are given that for every number below ten-thousand, it will either (i) become
-- a palindrome in less than fifty iterations, or, (ii) no one, with all the
-- computing power that exists, has managed so far to map it to a palindrome.
-- In fact, 10677 is the first number to be shown to require over fifty
-- iterations before producing a palindrome: 4668731596684224866951378664
-- (53 iterations, 28-digits).
--
-- Surprisingly, there are palindromic numbers that are themselves Lychrel
-- numbers; the first example is 4994.
--
-- How many Lychrel numbers are there below ten-thousand?
--
-- NOTE: Wording was modified slightly on 24 April 2007 to emphasise the
-- theoretical nature of Lychrel numbers.

problem55 :: Int
problem55 = length $ filter (isLychrel 49) [1..9999]

isPalindrome :: Integer -> Bool
isPalindrome x = show x == reverse (show x)

isLychrel :: Int -> Integer -> Bool
isLychrel 0 _ = True
isLychrel rec x = not (isPalindrome x') && isLychrel (rec - 1) x' where
  x' = x + fromDigits (reverse (digits x))

redpajama_set_name: RedPajamaGithub


text:
from .base import SSLClientAuthBackend, SSLClientAuthMiddleware
from . import fineid


text:
package de.lmu.mcm.network;

/**
 * Contains enums used in this project.
 *
 * @author Thomas Bornschlegel
 *
 */
public class Enums {

    public static enum InterfaceIdentifier {
        NFC, BLUETOOTH, BARCODES, WIFI, MOBILE_INTERNET, SMS, ARBITRARY;
    }

    public static enum Role {
        CLIENT, SERVER
    }

    public static enum CommunicationModes {
        READ, WRITE, READ_AND_WRITE, NOT_AVAILABLE
    }

    public static enum MessageOrigin {
        SELF, REMOTE
    }

    public static enum HandshakeRole {
        A, B
    }

    public static enum HandshakeNextAction {
        SEND, RECEIVE
    }

}


text:
'use strict';

module.exports = function (req, time) {
	if (req.timeoutTimer) {
		return req;
	}

	var delays = isNaN(time) ? time : {socket: time, connect: time};
	var host = req._headers ? (' to ' + req._headers.host) : '';

	if (delays.connect !== undefined) {
		req.timeoutTimer = setTimeout(function timeoutHandler() {
			req.abort();
			var e = new Error('Connection timed out on request' + host);
			e.code = 'ETIMEDOUT';
			req.emit('error', e);
		}, delays.connect);
	}

	// Clear the connection timeout timer once a socket is assigned to the
	// request and is connected. Abort the request if there is no activity
	// on the socket for more than `time` milliseconds.
	req.on('socket', function assign(socket) {
		socket.on('connect', function connect() {
			clear();

			if (delays.socket !== undefined) {
				socket.setTimeout(delays.socket, function socketTimeoutHandler() {
					req.abort();
					var e = new Error('Socket timed out on request' + host);
					e.code = 'ESOCKETTIMEDOUT';
					req.emit('error', e);
				});
			}
		});
	});

	function clear() {
		if (req.timeoutTimer) {
			clearTimeout(req.timeoutTimer);
			req.timeoutTimer = null;
		}
	}

	return req.on('error', clear);
};


text:
<?php

namespace Teknoo\Tests\States\LifeCycle\StatedClass\Support\AutomatedAcme;

use Teknoo\States\LifeCycle\StatedClass\Automated\Assertion\Assertion;
use Teknoo\States\LifeCycle\StatedClass\Automated\Assertion\AssertionInterface;
use Teknoo\States\LifeCycle\StatedClass\Automated\Assertion\Property\IsEqual;
use Teknoo\States\LifeCycle\StatedClass\Automated\Assertion\Property\IsNull;
use Teknoo\States\LifeCycle\StatedClass\Automated\AutomatedInterface;
use Teknoo\States\LifeCycle\StatedClass\Automated\AutomatedTrait;
use Teknoo\States\Proxy\Standard;
use Teknoo\Tests\States\LifeCycle\StatedClass\Support\AutomatedAcme\States\State1;
use Teknoo\Tests\States\LifeCycle\StatedClass\Support\AutomatedAcme\States\State2;

/**
 * Class AutomatedAcme.
 *
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */
class AutomatedAcme extends Standard implements AutomatedInterface
{
    use AutomatedTrait;

    /**
     * For AssertionTest.
     *
     * @var mixed
     */
    protected $foo;

    /**
     * For AssertionTest.
     *
     * @var mixed
     */
    protected $foo1;

    /**
     * For AssertionTest.
     *
     * @var mixed
     */
    protected $foo2;

    /**
     * @return array
     */
    public static function statesListDeclaration(): array
    {
        return [
            State1::class,
            State2::class,
        ];
    }

    /**
     * @param mixed $foo
     *
     * @return self
     */
    public function setFoo($foo)
    {
        $this->foo = $foo;

        return $this;
    }

    /**
     * @param mixed $foo1
     *
     * @return self
     */
    public function setFoo1($foo1)
    {
        $this->foo1 = $foo1;

        return $this;
    }

    /**
     * @param mixed $foo2
     *
     * @return self
     */
    public function setFoo2($foo2)
    {
        $this->foo2 = $foo2;

        return $this;
    }

    /**
     * @return AssertionInterface[]
     */
    public function getStatesAssertions(): array
    {
        return [
            (new Assertion([State1::class]))->with('foo', 'bar'),
            (new Assertion([State2::class]))->with('foo1', new IsEqual('bar1'))->with('foo2', new IsNull()),
        ];
    }
}


text:
package org.apache.hadoop.hbase.regionserver;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueTestUtil;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.hfile.HFilePrettyPrinter;
import org.apache.hadoop.hbase.regionserver.HRegion.RegionScannerImpl;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Test a multi-column scanner when there is a Bloom filter false-positive.
 * This is needed for the multi-column Bloom filter optimization.
 */
@RunWith(Parameterized.class)
@Category({RegionServerTests.class, SmallTests.class})
public class TestScanWithBloomError {

  private static final Log LOG =
    LogFactory.getLog(TestScanWithBloomError.class);

  private static final String TABLE_NAME = "ScanWithBloomError";
  private static final String FAMILY = "myCF";
  private static final byte[] FAMILY_BYTES = Bytes.toBytes(FAMILY);
  private static final String ROW = "theRow";
  private static final String QUALIFIER_PREFIX = "qual";
  private static final byte[] ROW_BYTES = Bytes.toBytes(ROW);
  private static NavigableSet<Integer> allColIds = new TreeSet<>();
  private HRegion region;
  private BloomType bloomType;
  private FileSystem fs;
  private Configuration conf;

  private final static HBaseTestingUtility TEST_UTIL = HBaseTestingUtility.createLocalHTU();

  @Parameters
  public static final Collection<Object[]> parameters() {
    List<Object[]> configurations = new ArrayList<>();
    for (BloomType bloomType : BloomType.values()) {
      configurations.add(new Object[] { bloomType });
    }
    return configurations;
  }

  public TestScanWithBloomError(BloomType bloomType) {
    this.bloomType = bloomType;
  }

  @Before
  public void setUp() throws IOException{
    conf = TEST_UTIL.getConfiguration();
    fs = FileSystem.get(conf);
  }

  @Test
  public void testThreeStoreFiles() throws IOException {
    region = TEST_UTIL.createTestRegion(TABLE_NAME,
        new HColumnDescriptor(FAMILY)
            .setCompressionType(Compression.Algorithm.GZ)
            .setBloomFilterType(bloomType)
            .setMaxVersions(TestMultiColumnScanner.MAX_VERSIONS));
    createStoreFile(new int[] {1, 2, 6});
    createStoreFile(new int[] {1, 2, 3, 7});
    createStoreFile(new int[] {1, 9});
    scanColSet(new int[]{1, 4, 6, 7}, new int[]{1, 6, 7});

    HBaseTestingUtility.closeRegionAndWAL(region);
  }

  private void scanColSet(int[] colSet, int[] expectedResultCols)
      throws IOException {
    LOG.info("Scanning column set: " + Arrays.toString(colSet));
    Scan scan = new Scan(ROW_BYTES, ROW_BYTES);
    addColumnSetToScan(scan, colSet);
    RegionScannerImpl scanner = region.getScanner(scan);
    KeyValueHeap storeHeap = scanner.getStoreHeapForTesting();
    assertEquals(0, storeHeap.getHeap().size());
    StoreScanner storeScanner =
        (StoreScanner) storeHeap.getCurrentForTesting();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    List<StoreFileScanner> scanners = (List<StoreFileScanner>)
        (List) storeScanner.getAllScannersForTesting();

    // Sort scanners by their HFile's modification time.
    Collections.sort(scanners, new Comparator<StoreFileScanner>() {
      @Override
      public int compare(StoreFileScanner s1, StoreFileScanner s2) {
        Path p1 = s1.getReader().getHFileReader().getPath();
        Path p2 = s2.getReader().getHFileReader().getPath();
        long t1, t2;
        try {
          t1 = fs.getFileStatus(p1).getModificationTime();
          t2 = fs.getFileStatus(p2).getModificationTime();
        } catch (IOException ex) {
          throw new RuntimeException(ex);
        }
        return t1 < t2 ? -1 : t1 == t2 ? 1 : 0;
      }
    });

    StoreFileReader lastStoreFileReader = null;
    for (StoreFileScanner sfScanner : scanners)
      lastStoreFileReader = sfScanner.getReader();

    new HFilePrettyPrinter(conf).run(new String[]{ "-m", "-p", "-f",
        lastStoreFileReader.getHFileReader().getPath().toString()});

    // Disable Bloom filter for the last store file. The disabled Bloom filter
    // will always return "true".
    LOG.info("Disabling Bloom filter for: "
        + lastStoreFileReader.getHFileReader().getName());
    lastStoreFileReader.disableBloomFilterForTesting();

    List<Cell> allResults = new ArrayList<>();

    { // Limit the scope of results.
      List<Cell> results = new ArrayList<>();
      while (scanner.next(results) || results.size() > 0) {
        allResults.addAll(results);
        results.clear();
      }
    }

    List<Integer> actualIds = new ArrayList<>();
    for (Cell kv : allResults) {
      String qual = Bytes.toString(CellUtil.cloneQualifier(kv));
      assertTrue(qual.startsWith(QUALIFIER_PREFIX));
      actualIds.add(Integer.valueOf(qual.substring(
          QUALIFIER_PREFIX.length())));
    }
    List<Integer> expectedIds = new ArrayList<>();
    for (int expectedId : expectedResultCols)
      expectedIds.add(expectedId);

    LOG.info("Column ids returned: " + actualIds + ", expected: "
        + expectedIds);
    assertEquals(expectedIds.toString(), actualIds.toString());
  }

  private void addColumnSetToScan(Scan scan, int[] colIds) {
    for (int colId : colIds) {
      scan.addColumn(FAMILY_BYTES,
          Bytes.toBytes(qualFromId(colId)));
    }
  }

  private String qualFromId(int colId) {
    return QUALIFIER_PREFIX + colId;
  }

  private void createStoreFile(int[] colIds)
      throws IOException {
    Put p = new Put(ROW_BYTES);
    for (int colId : colIds) {
      long ts = Long.MAX_VALUE;
      String qual = qualFromId(colId);
      allColIds.add(colId);
      KeyValue kv = KeyValueTestUtil.create(ROW, FAMILY,
          qual, ts, TestMultiColumnScanner.createValue(ROW, qual, ts));
      p.add(kv);
    }
    region.put(p);
    region.flush(true);
  }

}


text:
require 'headquarters/rails_delivery_method'

module Headquarters
  class Railtie < ::Rails::Railtie
    initializer 'headquaters.add_delivery_method' do
      ActiveSupport.on_load :action_mailer do
        ActionMailer::Base.add_delivery_method :headquarters, Headquarters::RailsDeliveryMethod
      end
    end
  end
end


text:
"""Project_Django URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import url, include
from django.conf.urls.static import static
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views as authviews
from cite import views

router = DefaultRouter()
router.register(r'users', views.CUserViewSet, 'CUser')
router.register(r'quotes', views.CQuoteViewSet, 'CQuote')
router.register(r'hashtags', views.CHashTagViewSet, 'CHashTag')

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^users/register', views.create_user),
    url(r'^me', views.me),
    url(r'^api-token-auth/', authviews.obtain_auth_token),
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


text:
var Movie = require('../models/movie');
var Comment = require('../models/comment');
var Category = require('../models/category');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');

//detail page
exports.detail = function(req,res){
	var id = req.params.id;
	Movie.update({_id:id},{$inc:{pv:1}},function(err){
		if(err) console.log(err);
	})
	Movie.findById(id,function(err,movie){
		Comment
		.find({movie:id})
		.populate('from','name')
		.populate('reply.from reply.to','name')
		.exec(function(err,comments){
			if(err) console.log(err);
			res.render('detail',{
				title:'imooc '+movie.title,
				movie:movie,
				comments:comments
			})
		})
	})
}

//new page
exports.new = function(req,res){
	Category.find({},function(err,categories){
		if(err) console.log(err);
		res.render('movie',{
			title:'imooc 电影录入页',
			categories:categories,
		    movie:{}
		})
	})
}

//update page
exports.update = function(req,res){
	var id = req.params.id;
	if(id){
		Movie.findById(id,function(err,movie){
			Category.find({},function(err,categories){
				if(err) console.log(err);
				res.render('movie',{
					title:'imooc 电影更新页',
					movie:movie,
					categories:categories
				})
			})
		})
	}
}

//poster save
exports.savePoster = function(req,res,next){
	var posterData = req.files.uploadPoster;
	var filePath = posterData.path;
	var originalFilename = posterData.originalFilename;

	if(originalFilename){
		fs.readFile(filePath,function(err,data){
			var timestamp = Date.now();
			var type = posterData.type.split('/')[1];
			var poster = timestamp + '.' + type;
			var newPath = path.join(__dirname,'../../','/public/upload/' + poster);
			fs.writeFile(newPath,data,function(err){
				req.poster = poster;
				next();
			})
		})
	}else{
		next();
	}
}

//save page
exports.save = function(req,res){
	var id = req.body.movie._id;
	var movieObj = req.body.movie;
	var _movie;

	if(req.poster){
		movieObj.poster = req.poster;
	}

	if(id){												//修改
		Movie.findById(id,function(err,movie){
			if(err) console.log(err);
			_movie = _.extend(movie,movieObj);
			Category.findById(movie.category,function(err,category){
				console.log(category);
			})
			_movie.save(function(err,movie){
				if(err) console.log(err);
				res.redirect('/movie/'+movie._id)
			})
		})
	}else{												//新增
		_movie = new Movie(movieObj);
		var categoryId = movieObj.category;
		var categoryName = movieObj.categoryName;

		_movie.save(function(err,movie){
			if(err) console.log(err);
			if(categoryId){
				Category.findById(categoryId,function(err,category){
					category.movies.push(movie._id);
					category.save(function(err,category){
						res.redirect('/movie/'+movie._id)
					})
				})
			}else if(categoryName){
				var category = new Category({
					name:categoryName,
					movies:[movie._id]
				})
				category.save(function(err,category){
					movie.category = category._id;
					movie.save(function(err,movie){
						res.redirect('/movie/'+movie._id)
					})
				})
			}
		})
	}
}

//list page
exports.list = function(req,res){
	Movie.find({}).populate('category','name').exec(function(err,movies){
		if(err) console.log(err);
		res.render('list',{
			title:'imooc 列表',
			movies:movies
		})
	})
}

//delete page
exports.del = function(req,res){
	var id = req.query.id;
	if(id){
		Movie.remove({_id:id},function(err,movie){
			if(err){
				console.log(err);
			}else{
				res.json({success:1});
			}
		})
	}
}


text:
def main():
    ''' ansible module for gcloud compute disk labels'''
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(default='present', type='str',
                       choices=['present', 'absent', 'list']),
            name=dict(default=None, type='str', required=True),
            labels=dict(default=None, type='dict'),
            project=dict(default=None, type='str', required=True),
            zone=dict(default=None, type='str', required=True),
        ),
        #required_together=[['name', 'zone']],
        supports_check_mode=True,
    )

    results = GcloudComputeLabel.run_ansible(module.params, module.check_mode)

    if 'failed' in results:
        module.fail_json(**results)

    module.exit_json(**results)

if __name__ == '__main__':
    main()


text:
title: Setup Instructions
---

# Setup Instructions

You can download the Google OAuth Client Library for Java and its dependencies
in a zip file, or you can use a dependency manager such as Maven or gradle to
install the necessary jars from the Maven Central repository.

## Maven

The Google OAuth Client Library for Java is in the central Maven repository. The
Maven `groupId` for all artifacts for this library is `com.google.oauth-client`.

To ensure all dependency versions work together and to avoid having to manually
choose and specify versions for each dependency, we recommend first importing
the `com.google.cloud:libraries-bom` in the `dependencyManagement` section of
your `pom.xml`:

```xml
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>2.2.0</version>
        <type>pom</type>
        <scope>import</scope>
       </dependency>
     </dependencies>
  </dependencyManagement>
```

Then you add the individual dependencies you need without version numbers to the
`dependencies` section:

```xml
<dependency>
  <groupId>com.google.oauth-client</groupId>
  <artifactId>google-oauth-client</artifactId>
</dependency>
```

On Android, you may need to explicitly exclude unused dependencies:

```xml
<dependency>
  <groupId>com.google.oauth-client</groupId>
  <artifactId>google-oauth-client</artifactId>
  <exclusions>
    <exclusion>
      <artifactId>xpp3</artifactId>
      <groupId>xpp3</groupId>
    </exclusion>
    <exclusion>
      <artifactId>httpclient</artifactId>
      <groupId>org.apache.httpcomponents</groupId>
    </exclusion>
    <exclusion>
      <artifactId>junit</artifactId>
      <groupId>junit</groupId>
    </exclusion>
    <exclusion>
      <artifactId>android</artifactId>
      <groupId>com.google.android</groupId>
    </exclusion>
  </exclusions>
</dependency>
```

## Download the library with dependencies

Download the latest assembly zip file from Maven Central and extract it on your
computer. This zip contains the client library class jar files and the
associated source jar files for each artifact and their dependencies. You can
find dependency graphs and licenses for the different libraries in the
dependencies folder. For more details about the contents of the download, see
the contained `readme.html` file.


text:
<?php

namespace Rs\Issues;

/**
 * Interface for all Tracker
 *
 * @author Robert Schönthal <robert.schoenthal@gmail.com>
 */
interface Tracker
{
    /**
     * @param  string  $username
     * @param  string  $password
     * @param  string  $host
     * @return boolean
     */
    public function connect($username = null, $password = null, $host = null);

    /**
     * @param  string  $name
     * @return Project
     */
    public function getProject($name);

}


text:
/* jshint node: true */
/* jshint esnext: true */
'use strict';

const router = require('express').Router();
const passport = require('passport');

router.get('/', (req, res) =>
  res.render('login', { error: req.flash('error') })
);

router.post('/',
  passport.authenticate('local',
    { successRedirect: '/admin',
      failureRedirect: '/login',
      failureFlash: true }
  )
);

module.exports = router;


text:
from pyspark import SparkContext
sc = SparkContext()

# In[1]:

# import findspark
# findspark.init()
# import pyspark
# sc = pyspark.SparkContext()

# In[6]:

textRDD = sc.newAPIHadoopFile('/data/Moby-Dick.txt',
                              'org.apache.hadoop.mapreduce.lib.input.TextInputFormat',
                              'org.apache.hadoop.io.LongWritable',
                              'org.apache.hadoop.io.Text',
                               conf={'textinputformat.record.delimiter': "\r\n\r\n"}) \
            .map(lambda x: x[1])

sentences=textRDD.flatMap(lambda x: x.split(". ")).map(lambda x: x.encode('utf-8'))

# In[18]:

def find_ngrams(input_list, n):
  return zip(*[input_list[i:] for i in range(n)])

# In[79]:

import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
sentences.map(lambda x: ' '.join(x.split()).lower())    .map(lambda x: x.translate(None, string.punctuation))    .flatMap(lambda x: find_ngrams(x.split(" "), 5))    .map(lambda x: (x,1))    .reduceByKey(lambda x,y: x+y)    .map(lambda x:(x[1],x[0]))     .sortByKey(False)    .take(100)

def printOutput(n,freq_ngramRDD):
    top=freq_ngramRDD.take(5)
    print '\n============ %d most frequent %d-grams'%(5,n)
    print '\nindex\tcount\tngram'
    for i in range(5):
        print '%d.\t%d: \t"%s"'%(i+1,top[i][0],' '.join(top[i][1]))

# In[86]:

for n in range(1,6):
    # Put your logic for generating the sorted n-gram RDD here and store it in freq_ngramRDD variable
    freq_ngramRDD = sentences.map(lambda x: x.lower())    .map(lambda x: x.translate(replace_punctuation))    .flatMap(lambda x: find_ngrams(' '.join(x.split()).split(" "), n))    .map(lambda x: (x,1))    .reduceByKey(lambda x,y: x+y)    .map(lambda x:(x[1],x[0]))     .sortByKey(False)
    printOutput(n,freq_ngramRDD)


text:
description: How to start containers automatically
keywords: containers, restart, policies, automation, administration
redirect_from:
- /engine/articles/host_integration/
- /engine/admin/host_integration/
- /engine/admin/start-containers-automatically/
title: Start containers automatically
---

Docker provides [restart policies](/engine/reference/run.md#restart-policies---restart)
to control whether your containers start automatically when they exit, or when
Docker restarts. Restart policies ensure that linked containers are started in
the correct order. Docker recommends that you use restart policies, and avoid
using process managers to start containers.

Restart policies are different from the `--live-restore` flag of the `dockerd`
command. Using `--live-restore` allows you to keep your containers running
during a Docker upgrade, though networking and user input are interrupted.

## Use a restart policy

To configure the restart policy for a container, use the `--restart` flag
when using the `docker run` command. The value of the `--restart` flag can be
any of the following:

| Flag             | Description                                                                                |
|:-----------------|:------------------------------------------------------------------------------------------------|
| `no`             | Do not automatically restart the container. (the default)                                       |
| `on-failure`     | Restart the container if it exits due to an error, which manifests as a non-zero exit code.     |
| `always`         | Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in [restart policy details](#restart-policy-details)) |
| `unless-stopped` | Similar to `always`, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. |

The following example starts a Redis container and configures it to always
restart unless it is explicitly stopped or Docker is restarted.

```bash
$ docker run -dit --restart unless-stopped redis
```

### Restart policy details

Keep the following in mind when using restart policies:

- A restart policy only takes effect after a container starts successfully. In
  this case, starting successfully means that the container is up for at least
  10 seconds and Docker has started monitoring it. This prevents a container
  which does not start at all from going into a restart loop.

- If you manually stop a container, its restart policy is ignored until the
  Docker daemon restarts or the container is manually restarted. This is another
  attempt to prevent a restart loop.

- Restart policies only apply to _containers_. Restart policies for swarm
  services are configured differently. See the
  [flags related to service restart](/engine/reference/commandline/service_create/).

## Use a process manager

If restart policies don't suit your needs, such as when processes outside
Docker depend on Docker containers, you can use a process manager such as
[upstart](http://upstart.ubuntu.com/),
[systemd](http://freedesktop.org/wiki/Software/systemd/), or
[supervisor](http://supervisord.org/) instead.

> **Warning**: Do not try to combine Docker restart policies with host-level
> process managers, because this creates conflicts.

To use a process manager, configure it to start your container or service using
the same `docker start` or `docker service` command you would normally use to
start the container manually. Consult the documentation for the specific
process manager for more details.

### Using a process manager inside containers

Process managers can also run within the container to check whether a process is
running and starts/restart it if not.

> **Warning**: These are not Docker-aware and just monitor operating system processes within the container.
>
> Docker does not recommend this approach, because it is platform-dependent and even differs within different versions of a given Linux distribution.


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

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;

import org.apache.hadoop.hive.metastore.api.BinaryColumnStatsData;
import org.apache.hadoop.hive.metastore.api.BooleanColumnStatsData;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
import org.apache.hadoop.hive.metastore.api.Date;
import org.apache.hadoop.hive.metastore.api.DateColumnStatsData;
import org.apache.hadoop.hive.metastore.api.Decimal;
import org.apache.hadoop.hive.metastore.api.DecimalColumnStatsData;
import org.apache.hadoop.hive.metastore.api.DoubleColumnStatsData;
import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
import org.apache.hadoop.hive.metastore.api.LongColumnStatsData;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.StringColumnStatsData;
import org.apache.hadoop.hive.metastore.model.MPartition;
import org.apache.hadoop.hive.metastore.model.MPartitionColumnStatistics;
import org.apache.hadoop.hive.metastore.model.MTable;
import org.apache.hadoop.hive.metastore.model.MTableColumnStatistics;

/**
 * This class contains conversion logic that creates Thrift stat objects from
 * JDO stat objects and plain arrays from DirectSQL.
 * It is hidden here so that we wouldn't have to look at it in elsewhere.
 */
public class StatObjectConverter {
  // JDO
  public static MTableColumnStatistics convertToMTableColumnStatistics(MTable table,
      ColumnStatisticsDesc statsDesc, ColumnStatisticsObj statsObj)
          throws NoSuchObjectException, MetaException, InvalidObjectException {
     if (statsObj == null || statsDesc == null) {
       throw new InvalidObjectException("Invalid column stats object");
     }

     MTableColumnStatistics mColStats = new MTableColumnStatistics();
     mColStats.setTable(table);
     mColStats.setDbName(statsDesc.getDbName());
     mColStats.setTableName(statsDesc.getTableName());
     mColStats.setLastAnalyzed(statsDesc.getLastAnalyzed());
     mColStats.setColName(statsObj.getColName());
     mColStats.setColType(statsObj.getColType());

     if (statsObj.getStatsData().isSetBooleanStats()) {
       BooleanColumnStatsData boolStats = statsObj.getStatsData().getBooleanStats();
       mColStats.setBooleanStats(
           boolStats.isSetNumTrues() ? boolStats.getNumTrues() : null,
           boolStats.isSetNumFalses() ? boolStats.getNumFalses() : null,
           boolStats.isSetNumNulls() ? boolStats.getNumNulls() : null);
     } else if (statsObj.getStatsData().isSetLongStats()) {
       LongColumnStatsData longStats = statsObj.getStatsData().getLongStats();
       mColStats.setLongStats(
           longStats.isSetNumNulls() ? longStats.getNumNulls() : null,
           longStats.isSetNumDVs() ? longStats.getNumDVs() : null,
           longStats.isSetLowValue() ? longStats.getLowValue() : null,
           longStats.isSetHighValue() ? longStats.getHighValue() : null);
     } else if (statsObj.getStatsData().isSetDoubleStats()) {
       DoubleColumnStatsData doubleStats = statsObj.getStatsData().getDoubleStats();
       mColStats.setDoubleStats(
           doubleStats.isSetNumNulls() ? doubleStats.getNumNulls() : null,
           doubleStats.isSetNumDVs() ? doubleStats.getNumDVs() : null,
           doubleStats.isSetLowValue() ? doubleStats.getLowValue() : null,
           doubleStats.isSetHighValue() ? doubleStats.getHighValue() : null);
     } else if (statsObj.getStatsData().isSetDecimalStats()) {
       DecimalColumnStatsData decimalStats = statsObj.getStatsData().getDecimalStats();
       String low = decimalStats.isSetLowValue() ? createJdoDecimalString(decimalStats.getLowValue()) : null;
       String high = decimalStats.isSetHighValue() ? createJdoDecimalString(decimalStats.getHighValue()) : null;
       mColStats.setDecimalStats(
           decimalStats.isSetNumNulls() ? decimalStats.getNumNulls() : null,
           decimalStats.isSetNumDVs() ? decimalStats.getNumDVs() : null,
               low, high);
     } else if (statsObj.getStatsData().isSetStringStats()) {
       StringColumnStatsData stringStats = statsObj.getStatsData().getStringStats();
       mColStats.setStringStats(
           stringStats.isSetNumNulls() ? stringStats.getNumNulls() : null,
           stringStats.isSetNumDVs() ? stringStats.getNumDVs() : null,
           stringStats.isSetMaxColLen() ? stringStats.getMaxColLen() : null,
           stringStats.isSetAvgColLen() ? stringStats.getAvgColLen() : null);
     } else if (statsObj.getStatsData().isSetBinaryStats()) {
       BinaryColumnStatsData binaryStats = statsObj.getStatsData().getBinaryStats();
       mColStats.setBinaryStats(
           binaryStats.isSetNumNulls() ? binaryStats.getNumNulls() : null,
           binaryStats.isSetMaxColLen() ? binaryStats.getMaxColLen() : null,
           binaryStats.isSetAvgColLen() ? binaryStats.getAvgColLen() : null);
     } else if (statsObj.getStatsData().isSetDateStats()) {
       DateColumnStatsData dateStats = statsObj.getStatsData().getDateStats();
       mColStats.setDateStats(
           dateStats.isSetNumNulls() ? dateStats.getNumNulls() : null,
           dateStats.isSetNumDVs() ? dateStats.getNumDVs() : null,
           dateStats.isSetLowValue() ? dateStats.getLowValue().getDaysSinceEpoch() : null,
           dateStats.isSetHighValue() ? dateStats.getHighValue().getDaysSinceEpoch() : null);
     }
     return mColStats;
  }

  public static void setFieldsIntoOldStats(
      MTableColumnStatistics mStatsObj, MTableColumnStatistics oldStatsObj) {
    if (mStatsObj.getAvgColLen() != null) {
      oldStatsObj.setAvgColLen(mStatsObj.getAvgColLen());
    }
    if (mStatsObj.getLongHighValue() != null) {
      oldStatsObj.setLongHighValue(mStatsObj.getLongHighValue());
    }
    if (mStatsObj.getLongLowValue() != null) {
      oldStatsObj.setLongLowValue(mStatsObj.getLongLowValue());
    }
    if (mStatsObj.getDoubleLowValue() != null) {
      oldStatsObj.setDoubleLowValue(mStatsObj.getDoubleLowValue());
    }
    if (mStatsObj.getDoubleHighValue() != null) {
      oldStatsObj.setDoubleHighValue(mStatsObj.getDoubleHighValue());
    }
    if (mStatsObj.getDecimalLowValue() != null) {
      oldStatsObj.setDecimalLowValue(mStatsObj.getDecimalLowValue());
    }
    if (mStatsObj.getDecimalHighValue() != null) {
      oldStatsObj.setDecimalHighValue(mStatsObj.getDecimalHighValue());
    }
    if (mStatsObj.getMaxColLen() != null) {
      oldStatsObj.setMaxColLen(mStatsObj.getMaxColLen());
    }
    if (mStatsObj.getNumDVs() != null) {
      oldStatsObj.setNumDVs(mStatsObj.getNumDVs());
    }
    if (mStatsObj.getNumFalses() != null) {
      oldStatsObj.setNumFalses(mStatsObj.getNumFalses());
    }
    if (mStatsObj.getNumTrues() != null) {
      oldStatsObj.setNumTrues(mStatsObj.getNumTrues());
    }
    if (mStatsObj.getNumNulls() != null) {
      oldStatsObj.setNumNulls(mStatsObj.getNumNulls());
    }
    oldStatsObj.setLastAnalyzed(mStatsObj.getLastAnalyzed());
  }

  public static void setFieldsIntoOldStats(
      MPartitionColumnStatistics mStatsObj, MPartitionColumnStatistics oldStatsObj) {
    if (mStatsObj.getAvgColLen() != null) {
          oldStatsObj.setAvgColLen(mStatsObj.getAvgColLen());
    }
    if (mStatsObj.getLongHighValue() != null) {
      oldStatsObj.setLongHighValue(mStatsObj.getLongHighValue());
    }
    if (mStatsObj.getDoubleHighValue() != null) {
      oldStatsObj.setDoubleHighValue(mStatsObj.getDoubleHighValue());
    }
    oldStatsObj.setLastAnalyzed(mStatsObj.getLastAnalyzed());
    if (mStatsObj.getLongLowValue() != null) {
      oldStatsObj.setLongLowValue(mStatsObj.getLongLowValue());
    }
    if (mStatsObj.getDoubleLowValue() != null) {
      oldStatsObj.setDoubleLowValue(mStatsObj.getDoubleLowValue());
    }
    if (mStatsObj.getDecimalLowValue() != null) {
      oldStatsObj.setDecimalLowValue(mStatsObj.getDecimalLowValue());
    }
    if (mStatsObj.getDecimalHighValue() != null) {
      oldStatsObj.setDecimalHighValue(mStatsObj.getDecimalHighValue());
    }
    if (mStatsObj.getMaxColLen() != null) {
      oldStatsObj.setMaxColLen(mStatsObj.getMaxColLen());
    }
    if (mStatsObj.getNumDVs() != null) {
      oldStatsObj.setNumDVs(mStatsObj.getNumDVs());
    }
    if (mStatsObj.getNumFalses() != null) {
      oldStatsObj.setNumFalses(mStatsObj.getNumFalses());
    }
    if (mStatsObj.getNumTrues() != null) {
      oldStatsObj.setNumTrues(mStatsObj.getNumTrues());
    }
    if (mStatsObj.getNumNulls() != null) {
      oldStatsObj.setNumNulls(mStatsObj.getNumNulls());
    }
  }

  public static ColumnStatisticsObj getTableColumnStatisticsObj(
      MTableColumnStatistics mStatsObj) {
    ColumnStatisticsObj statsObj = new ColumnStatisticsObj();
    statsObj.setColType(mStatsObj.getColType());
    statsObj.setColName(mStatsObj.getColName());
    String colType = mStatsObj.getColType().toLowerCase();
    ColumnStatisticsData colStatsData = new ColumnStatisticsData();

    if (colType.equals("boolean")) {
      BooleanColumnStatsData boolStats = new BooleanColumnStatsData();
      boolStats.setNumFalses(mStatsObj.getNumFalses());
      boolStats.setNumTrues(mStatsObj.getNumTrues());
      boolStats.setNumNulls(mStatsObj.getNumNulls());
      colStatsData.setBooleanStats(boolStats);
    } else if (colType.equals("string") ||
        colType.startsWith("varchar") || colType.startsWith("char")) {
      StringColumnStatsData stringStats = new StringColumnStatsData();
      stringStats.setNumNulls(mStatsObj.getNumNulls());
      stringStats.setAvgColLen(mStatsObj.getAvgColLen());
      stringStats.setMaxColLen(mStatsObj.getMaxColLen());
      stringStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setStringStats(stringStats);
    } else if (colType.equals("binary")) {
      BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
      binaryStats.setNumNulls(mStatsObj.getNumNulls());
      binaryStats.setAvgColLen(mStatsObj.getAvgColLen());
      binaryStats.setMaxColLen(mStatsObj.getMaxColLen());
      colStatsData.setBinaryStats(binaryStats);
    } else if (colType.equals("bigint") || colType.equals("int") ||
        colType.equals("smallint") || colType.equals("tinyint") ||
        colType.equals("timestamp")) {
      LongColumnStatsData longStats = new LongColumnStatsData();
      longStats.setNumNulls(mStatsObj.getNumNulls());
      Long longHighValue = mStatsObj.getLongHighValue();
      if (longHighValue != null) {
        longStats.setHighValue(longHighValue);
      }
      Long longLowValue = mStatsObj.getLongLowValue();
      if (longLowValue != null) {
        longStats.setLowValue(longLowValue);
      }
      longStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setLongStats(longStats);
    } else if (colType.equals("double") || colType.equals("float")) {
      DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
      doubleStats.setNumNulls(mStatsObj.getNumNulls());
      Double doubleHighValue = mStatsObj.getDoubleHighValue();
      if (doubleHighValue != null) {
        doubleStats.setHighValue(doubleHighValue);
      }
      Double doubleLowValue = mStatsObj.getDoubleLowValue();
      if (doubleLowValue != null) {
        doubleStats.setLowValue(doubleLowValue);
      }
      doubleStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDoubleStats(doubleStats);
    } else if (colType.startsWith("decimal")) {
      DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
      decimalStats.setNumNulls(mStatsObj.getNumNulls());
      String decimalHighValue = mStatsObj.getDecimalHighValue();
      if (decimalHighValue != null) {
        decimalStats.setHighValue(createThriftDecimal(decimalHighValue));
      }
      String decimalLowValue = mStatsObj.getDecimalLowValue();
      if (decimalLowValue != null) {
        decimalStats.setLowValue(createThriftDecimal(decimalLowValue));
      }
      decimalStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDecimalStats(decimalStats);
    } else if (colType.equals("date")) {
      DateColumnStatsData dateStats = new DateColumnStatsData();
      dateStats.setNumNulls(mStatsObj.getNumNulls());
      Long highValue = mStatsObj.getLongHighValue();
      if (highValue != null) {
        dateStats.setHighValue(new Date(highValue));
      }
      Long lowValue = mStatsObj.getLongLowValue();
      if (lowValue != null) {
        dateStats.setLowValue(new Date(lowValue));
      }
      dateStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDateStats(dateStats);
    }
    statsObj.setStatsData(colStatsData);
    return statsObj;
  }

  public static ColumnStatisticsDesc getTableColumnStatisticsDesc(
      MTableColumnStatistics mStatsObj) {
    ColumnStatisticsDesc statsDesc = new ColumnStatisticsDesc();
    statsDesc.setIsTblLevel(true);
    statsDesc.setDbName(mStatsObj.getDbName());
    statsDesc.setTableName(mStatsObj.getTableName());
    statsDesc.setLastAnalyzed(mStatsObj.getLastAnalyzed());
    return statsDesc;
  }

  public static MPartitionColumnStatistics convertToMPartitionColumnStatistics(
      MPartition partition, ColumnStatisticsDesc statsDesc, ColumnStatisticsObj statsObj)
          throws MetaException, NoSuchObjectException {
    if (statsDesc == null || statsObj == null) {
      return null;
    }

    MPartitionColumnStatistics mColStats = new MPartitionColumnStatistics();
    mColStats.setPartition(partition);
    mColStats.setDbName(statsDesc.getDbName());
    mColStats.setTableName(statsDesc.getTableName());
    mColStats.setPartitionName(statsDesc.getPartName());
    mColStats.setLastAnalyzed(statsDesc.getLastAnalyzed());
    mColStats.setColName(statsObj.getColName());
    mColStats.setColType(statsObj.getColType());

    if (statsObj.getStatsData().isSetBooleanStats()) {
      BooleanColumnStatsData boolStats = statsObj.getStatsData().getBooleanStats();
      mColStats.setBooleanStats(
          boolStats.isSetNumTrues() ? boolStats.getNumTrues() : null,
          boolStats.isSetNumFalses() ? boolStats.getNumFalses() : null,
          boolStats.isSetNumNulls() ? boolStats.getNumNulls() : null);
    } else if (statsObj.getStatsData().isSetLongStats()) {
      LongColumnStatsData longStats = statsObj.getStatsData().getLongStats();
      mColStats.setLongStats(
          longStats.isSetNumNulls() ? longStats.getNumNulls() : null,
          longStats.isSetNumDVs() ? longStats.getNumDVs() : null,
          longStats.isSetLowValue() ? longStats.getLowValue() : null,
          longStats.isSetHighValue() ? longStats.getHighValue() : null);
    } else if (statsObj.getStatsData().isSetDoubleStats()) {
      DoubleColumnStatsData doubleStats = statsObj.getStatsData().getDoubleStats();
      mColStats.setDoubleStats(
          doubleStats.isSetNumNulls() ? doubleStats.getNumNulls() : null,
          doubleStats.isSetNumDVs() ? doubleStats.getNumDVs() : null,
          doubleStats.isSetLowValue() ? doubleStats.getLowValue() : null,
          doubleStats.isSetHighValue() ? doubleStats.getHighValue() : null);
    } else if (statsObj.getStatsData().isSetDecimalStats()) {
      DecimalColumnStatsData decimalStats = statsObj.getStatsData().getDecimalStats();
      String low = decimalStats.isSetLowValue() ? createJdoDecimalString(decimalStats.getLowValue()) : null;
      String high = decimalStats.isSetHighValue() ? createJdoDecimalString(decimalStats.getHighValue()) : null;
      mColStats.setDecimalStats(
          decimalStats.isSetNumNulls() ? decimalStats.getNumNulls() : null,
          decimalStats.isSetNumDVs() ? decimalStats.getNumDVs() : null,
              low, high);
    } else if (statsObj.getStatsData().isSetStringStats()) {
      StringColumnStatsData stringStats = statsObj.getStatsData().getStringStats();
      mColStats.setStringStats(
          stringStats.isSetNumNulls() ? stringStats.getNumNulls() : null,
          stringStats.isSetNumDVs() ? stringStats.getNumDVs() : null,
          stringStats.isSetMaxColLen() ? stringStats.getMaxColLen() : null,
          stringStats.isSetAvgColLen() ? stringStats.getAvgColLen() : null);
    } else if (statsObj.getStatsData().isSetBinaryStats()) {
      BinaryColumnStatsData binaryStats = statsObj.getStatsData().getBinaryStats();
      mColStats.setBinaryStats(
          binaryStats.isSetNumNulls() ? binaryStats.getNumNulls() : null,
          binaryStats.isSetMaxColLen() ? binaryStats.getMaxColLen() : null,
          binaryStats.isSetAvgColLen() ? binaryStats.getAvgColLen() : null);
    } else if (statsObj.getStatsData().isSetDateStats()) {
      DateColumnStatsData dateStats = statsObj.getStatsData().getDateStats();
      mColStats.setDateStats(
          dateStats.isSetNumNulls() ? dateStats.getNumNulls() : null,
          dateStats.isSetNumDVs() ? dateStats.getNumDVs() : null,
          dateStats.isSetLowValue() ? dateStats.getLowValue().getDaysSinceEpoch() : null,
          dateStats.isSetHighValue() ? dateStats.getHighValue().getDaysSinceEpoch() : null);
    }
    return mColStats;
  }

  public static ColumnStatisticsObj getPartitionColumnStatisticsObj(
      MPartitionColumnStatistics mStatsObj) {
    ColumnStatisticsObj statsObj = new ColumnStatisticsObj();
    statsObj.setColType(mStatsObj.getColType());
    statsObj.setColName(mStatsObj.getColName());
    String colType = mStatsObj.getColType().toLowerCase();
    ColumnStatisticsData colStatsData = new ColumnStatisticsData();

    if (colType.equals("boolean")) {
      BooleanColumnStatsData boolStats = new BooleanColumnStatsData();
      boolStats.setNumFalses(mStatsObj.getNumFalses());
      boolStats.setNumTrues(mStatsObj.getNumTrues());
      boolStats.setNumNulls(mStatsObj.getNumNulls());
      colStatsData.setBooleanStats(boolStats);
    } else if (colType.equals("string") ||
        colType.startsWith("varchar") || colType.startsWith("char")) {
      StringColumnStatsData stringStats = new StringColumnStatsData();
      stringStats.setNumNulls(mStatsObj.getNumNulls());
      stringStats.setAvgColLen(mStatsObj.getAvgColLen());
      stringStats.setMaxColLen(mStatsObj.getMaxColLen());
      stringStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setStringStats(stringStats);
    } else if (colType.equals("binary")) {
      BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
      binaryStats.setNumNulls(mStatsObj.getNumNulls());
      binaryStats.setAvgColLen(mStatsObj.getAvgColLen());
      binaryStats.setMaxColLen(mStatsObj.getMaxColLen());
      colStatsData.setBinaryStats(binaryStats);
    } else if (colType.equals("tinyint") || colType.equals("smallint") ||
        colType.equals("int") || colType.equals("bigint") ||
        colType.equals("timestamp")) {
      LongColumnStatsData longStats = new LongColumnStatsData();
      longStats.setNumNulls(mStatsObj.getNumNulls());
      if (mStatsObj.getLongHighValue() != null) {
        longStats.setHighValue(mStatsObj.getLongHighValue());
      }
      if (mStatsObj.getLongLowValue() != null) {
        longStats.setLowValue(mStatsObj.getLongLowValue());
      }
      longStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setLongStats(longStats);
    } else if (colType.equals("double") || colType.equals("float")) {
      DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
      doubleStats.setNumNulls(mStatsObj.getNumNulls());
      if (mStatsObj.getDoubleHighValue() != null) {
        doubleStats.setHighValue(mStatsObj.getDoubleHighValue());
      }
      if (mStatsObj.getDoubleLowValue() != null) {
        doubleStats.setLowValue(mStatsObj.getDoubleLowValue());
      }
      doubleStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDoubleStats(doubleStats);
    } else if (colType.startsWith("decimal")) {
      DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
      decimalStats.setNumNulls(mStatsObj.getNumNulls());
      if (mStatsObj.getDecimalHighValue() != null) {
        decimalStats.setHighValue(createThriftDecimal(mStatsObj.getDecimalHighValue()));
      }
      if (mStatsObj.getDecimalLowValue() != null) {
        decimalStats.setLowValue(createThriftDecimal(mStatsObj.getDecimalLowValue()));
      }
      decimalStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDecimalStats(decimalStats);
    } else if (colType.equals("date")) {
      DateColumnStatsData dateStats = new DateColumnStatsData();
      dateStats.setNumNulls(mStatsObj.getNumNulls());
      dateStats.setHighValue(new Date(mStatsObj.getLongHighValue()));
      dateStats.setLowValue(new Date(mStatsObj.getLongLowValue()));
      dateStats.setNumDVs(mStatsObj.getNumDVs());
      colStatsData.setDateStats(dateStats);
    }
    statsObj.setStatsData(colStatsData);
    return statsObj;
  }

  public static ColumnStatisticsDesc getPartitionColumnStatisticsDesc(
    MPartitionColumnStatistics mStatsObj) {
    ColumnStatisticsDesc statsDesc = new ColumnStatisticsDesc();
    statsDesc.setIsTblLevel(false);
    statsDesc.setDbName(mStatsObj.getDbName());
    statsDesc.setTableName(mStatsObj.getTableName());
    statsDesc.setPartName(mStatsObj.getPartitionName());
    statsDesc.setLastAnalyzed(mStatsObj.getLastAnalyzed());
    return statsDesc;
  }

  // SQL
  public static void fillColumnStatisticsData(String colType, ColumnStatisticsData data,
      Object llow, Object lhigh, Object dlow, Object dhigh, Object declow, Object dechigh,
      Object nulls, Object dist, Object avglen, Object maxlen, Object trues, Object falses) throws MetaException {
    colType = colType.toLowerCase();
    if (colType.equals("boolean")) {
      BooleanColumnStatsData boolStats = new BooleanColumnStatsData();
      boolStats.setNumFalses(MetaStoreDirectSql.extractSqlLong(falses));
      boolStats.setNumTrues(MetaStoreDirectSql.extractSqlLong(trues));
      boolStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      data.setBooleanStats(boolStats);
    } else if (colType.equals("string") ||
        colType.startsWith("varchar") || colType.startsWith("char")) {
      StringColumnStatsData stringStats = new StringColumnStatsData();
      stringStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      stringStats.setAvgColLen(MetaStoreDirectSql.extractSqlDouble(avglen));
      stringStats.setMaxColLen(MetaStoreDirectSql.extractSqlLong(maxlen));
      stringStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setStringStats(stringStats);
    } else if (colType.equals("binary")) {
      BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
      binaryStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      binaryStats.setAvgColLen(MetaStoreDirectSql.extractSqlDouble(avglen));
      binaryStats.setMaxColLen(MetaStoreDirectSql.extractSqlLong(maxlen));
      data.setBinaryStats(binaryStats);
    } else if (colType.equals("bigint") || colType.equals("int") ||
        colType.equals("smallint") || colType.equals("tinyint") ||
        colType.equals("timestamp")) {
      LongColumnStatsData longStats = new LongColumnStatsData();
      longStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (lhigh != null) {
        longStats.setHighValue(MetaStoreDirectSql.extractSqlLong(lhigh));
      }
      if (llow != null) {
        longStats.setLowValue(MetaStoreDirectSql.extractSqlLong(llow));
      }
      longStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setLongStats(longStats);
    } else if (colType.equals("double") || colType.equals("float")) {
      DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
      doubleStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (dhigh != null) {
        doubleStats.setHighValue(MetaStoreDirectSql.extractSqlDouble(dhigh));
      }
      if (dlow != null) {
        doubleStats.setLowValue(MetaStoreDirectSql.extractSqlDouble(dlow));
      }
      doubleStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setDoubleStats(doubleStats);
    } else if (colType.startsWith("decimal")) {
      DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
      decimalStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (dechigh != null) {
        decimalStats.setHighValue(createThriftDecimal((String)dechigh));
      }
      if (declow != null) {
        decimalStats.setLowValue(createThriftDecimal((String)declow));
      }
      decimalStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setDecimalStats(decimalStats);
    } else if (colType.equals("date")) {
      DateColumnStatsData dateStats = new DateColumnStatsData();
      dateStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (lhigh != null) {
        dateStats.setHighValue(new Date(MetaStoreDirectSql.extractSqlLong(lhigh)));
      }
      if (llow != null) {
        dateStats.setLowValue(new Date(MetaStoreDirectSql.extractSqlLong(llow)));
      }
      dateStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setDateStats(dateStats);
    }
  }

  public static void fillColumnStatisticsData(String colType, ColumnStatisticsData data,
      Object llow, Object lhigh, Object dlow, Object dhigh, Object declow, Object dechigh,
      Object nulls, Object dist, Object avglen, Object maxlen, Object trues, Object falses,
      Object avgLong, Object avgDouble, Object avgDecimal, Object sumDist,
      boolean useDensityFunctionForNDVEstimation, double ndvTuner) throws MetaException {
    colType = colType.toLowerCase();
    if (colType.equals("boolean")) {
      BooleanColumnStatsData boolStats = new BooleanColumnStatsData();
      boolStats.setNumFalses(MetaStoreDirectSql.extractSqlLong(falses));
      boolStats.setNumTrues(MetaStoreDirectSql.extractSqlLong(trues));
      boolStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      data.setBooleanStats(boolStats);
    } else if (colType.equals("string") || colType.startsWith("varchar")
        || colType.startsWith("char")) {
      StringColumnStatsData stringStats = new StringColumnStatsData();
      stringStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      stringStats.setAvgColLen(MetaStoreDirectSql.extractSqlDouble(avglen));
      stringStats.setMaxColLen(MetaStoreDirectSql.extractSqlLong(maxlen));
      stringStats.setNumDVs(MetaStoreDirectSql.extractSqlLong(dist));
      data.setStringStats(stringStats);
    } else if (colType.equals("binary")) {
      BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
      binaryStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      binaryStats.setAvgColLen(MetaStoreDirectSql.extractSqlDouble(avglen));
      binaryStats.setMaxColLen(MetaStoreDirectSql.extractSqlLong(maxlen));
      data.setBinaryStats(binaryStats);
    } else if (colType.equals("bigint") || colType.equals("int") || colType.equals("smallint")
        || colType.equals("tinyint") || colType.equals("timestamp")) {
      LongColumnStatsData longStats = new LongColumnStatsData();
      longStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (lhigh != null) {
        longStats.setHighValue(MetaStoreDirectSql.extractSqlLong(lhigh));
      }
      if (llow != null) {
        longStats.setLowValue(MetaStoreDirectSql.extractSqlLong(llow));
      }
      long lowerBound = MetaStoreDirectSql.extractSqlLong(dist);
      long higherBound = MetaStoreDirectSql.extractSqlLong(sumDist);
      long rangeBound = Long.MAX_VALUE;
      if (lhigh != null && llow != null) {
        rangeBound = MetaStoreDirectSql.extractSqlLong(lhigh)
            - MetaStoreDirectSql.extractSqlLong(llow) + 1;
      }
      long estimation;
      if (useDensityFunctionForNDVEstimation && lhigh != null && llow != null && avgLong != null
          && MetaStoreDirectSql.extractSqlDouble(avgLong) != 0.0) {
        // We have estimation, lowerbound and higherbound. We use estimation if
        // it is between lowerbound and higherbound.
        estimation = MetaStoreDirectSql
            .extractSqlLong((MetaStoreDirectSql.extractSqlLong(lhigh) - MetaStoreDirectSql
                .extractSqlLong(llow)) / MetaStoreDirectSql.extractSqlDouble(avgLong));
        if (estimation < lowerBound) {
          estimation = lowerBound;
        } else if (estimation > higherBound) {
          estimation = higherBound;
        }
      } else {
        estimation = (long) (lowerBound + (higherBound - lowerBound) * ndvTuner);
      }
      estimation = Math.min(estimation, rangeBound);
      longStats.setNumDVs(estimation);
      data.setLongStats(longStats);
    } else if (colType.equals("date")) {
      DateColumnStatsData dateStats = new DateColumnStatsData();
      dateStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (lhigh != null) {
        dateStats.setHighValue(new Date(MetaStoreDirectSql.extractSqlLong(lhigh)));
      }
      if (llow != null) {
        dateStats.setLowValue(new Date(MetaStoreDirectSql.extractSqlLong(llow)));
      }
      long lowerBound = MetaStoreDirectSql.extractSqlLong(dist);
      long higherBound = MetaStoreDirectSql.extractSqlLong(sumDist);
      long rangeBound = Long.MAX_VALUE;
      if (lhigh != null && llow != null) {
        rangeBound = MetaStoreDirectSql.extractSqlLong(lhigh)
            - MetaStoreDirectSql.extractSqlLong(llow) + 1;
      }
      long estimation;
      if (useDensityFunctionForNDVEstimation && lhigh != null && llow != null && avgLong != null
          && MetaStoreDirectSql.extractSqlDouble(avgLong) != 0.0) {
        // We have estimation, lowerbound and higherbound. We use estimation if
        // it is between lowerbound and higherbound.
        estimation = MetaStoreDirectSql
            .extractSqlLong((MetaStoreDirectSql.extractSqlLong(lhigh) - MetaStoreDirectSql
                .extractSqlLong(llow)) / MetaStoreDirectSql.extractSqlDouble(avgLong));
        if (estimation < lowerBound) {
          estimation = lowerBound;
        } else if (estimation > higherBound) {
          estimation = higherBound;
        }
      } else {
        estimation = (long) (lowerBound + (higherBound - lowerBound) * ndvTuner);
      }
      estimation = Math.min(estimation, rangeBound);
      dateStats.setNumDVs(estimation);
      data.setDateStats(dateStats);
    } else if (colType.equals("double") || colType.equals("float")) {
      DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
      doubleStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      if (dhigh != null) {
        doubleStats.setHighValue(MetaStoreDirectSql.extractSqlDouble(dhigh));
      }
      if (dlow != null) {
        doubleStats.setLowValue(MetaStoreDirectSql.extractSqlDouble(dlow));
      }
      long lowerBound = MetaStoreDirectSql.extractSqlLong(dist);
      long higherBound = MetaStoreDirectSql.extractSqlLong(sumDist);
      if (useDensityFunctionForNDVEstimation && dhigh != null && dlow != null && avgDouble != null
          && MetaStoreDirectSql.extractSqlDouble(avgDouble) != 0.0) {
        long estimation = MetaStoreDirectSql
            .extractSqlLong((MetaStoreDirectSql.extractSqlLong(dhigh) - MetaStoreDirectSql
                .extractSqlLong(dlow)) / MetaStoreDirectSql.extractSqlDouble(avgDouble));
        if (estimation < lowerBound) {
          doubleStats.setNumDVs(lowerBound);
        } else if (estimation > higherBound) {
          doubleStats.setNumDVs(higherBound);
        } else {
          doubleStats.setNumDVs(estimation);
        }
      } else {
        doubleStats.setNumDVs((long) (lowerBound + (higherBound - lowerBound) * ndvTuner));
      }
      data.setDoubleStats(doubleStats);
    } else if (colType.startsWith("decimal")) {
      DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
      decimalStats.setNumNulls(MetaStoreDirectSql.extractSqlLong(nulls));
      Decimal low = null;
      Decimal high = null;
      BigDecimal blow = null;
      BigDecimal bhigh = null;
      if (dechigh instanceof BigDecimal) {
        bhigh = (BigDecimal) dechigh;
        high = new Decimal(ByteBuffer.wrap(bhigh.unscaledValue().toByteArray()),
            (short) bhigh.scale());
      } else if (dechigh instanceof String) {
        bhigh = new BigDecimal((String) dechigh);
        high = createThriftDecimal((String) dechigh);
      }
      decimalStats.setHighValue(high);
      if (declow instanceof BigDecimal) {
        blow = (BigDecimal) declow;
        low = new Decimal(ByteBuffer.wrap(blow.unscaledValue().toByteArray()), (short) blow.scale());
      } else if (dechigh instanceof String) {
        blow = new BigDecimal((String) declow);
        low = createThriftDecimal((String) declow);
      }
      decimalStats.setLowValue(low);
      long lowerBound = MetaStoreDirectSql.extractSqlLong(dist);
      long higherBound = MetaStoreDirectSql.extractSqlLong(sumDist);
      if (useDensityFunctionForNDVEstimation && dechigh != null && declow != null && avgDecimal != null
          && MetaStoreDirectSql.extractSqlDouble(avgDecimal) != 0.0) {
        long estimation = MetaStoreDirectSql.extractSqlLong(MetaStoreDirectSql.extractSqlLong(bhigh
            .subtract(blow).floatValue() / MetaStoreDirectSql.extractSqlDouble(avgDecimal)));
        if (estimation < lowerBound) {
          decimalStats.setNumDVs(lowerBound);
        } else if (estimation > higherBound) {
          decimalStats.setNumDVs(higherBound);
        } else {
          decimalStats.setNumDVs(estimation);
        }
      } else {
        decimalStats.setNumDVs((long) (lowerBound + (higherBound - lowerBound) * ndvTuner));
      }
      data.setDecimalStats(decimalStats);
    }
  }

  public static Decimal createThriftDecimal(String s) {
    BigDecimal d = new BigDecimal(s);
    return new Decimal(ByteBuffer.wrap(d.unscaledValue().toByteArray()), (short)d.scale());
  }

  private static String createJdoDecimalString(Decimal d) {
    return new BigDecimal(new BigInteger(d.getUnscaled()), d.getScale()).toString();
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 885 (1887)

#### Original name
Agaricus lepton Berk.

### Remarks
null


text:
package com.publictransitanalytics.scoregenerator.location;

import com.publictransitanalytics.scoregenerator.geography.GeoLatitude;
import com.publictransitanalytics.scoregenerator.testhelpers.CountingVisitor;
import org.junit.Assert;
import org.junit.Test;
import com.publictransitanalytics.scoregenerator.geography.GeoPoint;
import com.publictransitanalytics.scoregenerator.geography.AngleUnit;
import com.publictransitanalytics.scoregenerator.geography.GeoLongitude;

/**
 *
 * @author Public Transit Analytics
 */
public class LandmarkTest {

    private static final GeoPoint POINT = new GeoPoint(
            new GeoLongitude("-122.32370", AngleUnit.DEGREES),
            new GeoLatitude("47.654656", AngleUnit.DEGREES));

    @Test
    public void testVisit() throws Exception {
        final Landmark landmark = new Landmark(POINT);
        final CountingVisitor visitor = new CountingVisitor();
        landmark.accept(visitor);
        Assert.assertEquals(1, visitor.getLandmarkCount());
    }

    @Test
    public void testIdentifierIsRadianLocation() {
        final Landmark landmark = new Landmark(POINT);
        Assert.assertEquals("0.831731, -2.134951", landmark.getIdentifier());
    }

    @Test
    public void testNameIsDegreeLocation() {
        final Landmark landmark = new Landmark(POINT);
        Assert.assertEquals("47.654656, -122.323700", landmark.getCommonName());
    }

}


text:
'use strict';

// Bug with Jest because we're going to the node_modules that is a sibling
// of what jest thinks our root (the dir with the package.json) should be.

module.exports = require.requireActual('q');


text:
package com.cloudray.scalapress.widgets.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{PathVariable, RequestParam, RequestBody, RequestMethod, ModelAttribute, RequestMapping}
import org.springframework.beans.factory.annotation.Autowired
import com.cloudray.scalapress.widgets.Widget
import scala.Array
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.cloudray.scalapress.framework.{ScalapressContext, ComponentClassScanner}

/** @author Stephen Samuel */
@Controller
@Autowired
@RequestMapping(Array("backoffice/widget"))
class WidgetListController(context: ScalapressContext) {

  @RequestMapping
  def list = "admin/widget/list.vm"

  @RequestMapping(value = Array("create"), method = Array(RequestMethod.POST))
  def create(@RequestParam("class") klass: String) = {
    val widget = Class.forName(klass).newInstance().asInstanceOf[Widget]
    widget.init(context)
    "redirect:/backoffice/widget"
  }

  @RequestMapping(value = Array("{id}/delete"))
  def delete(@PathVariable("id") id: Long) = {
    context.widgetDao.removeById(id)
    "redirect:/backoffice/widget"
  }

  @RequestMapping(value = Array("order"), method = Array(RequestMethod.POST))
  def reorderWidgets(@RequestBody order: String): String = {

    val widgets = context.widgetDao.findAll
    val ids = order.split("-")
    if (ids.size == widgets.size)
      widgets.foreach(w => {
        val pos = ids.indexOf(w.id.toString)
        w.position = pos
        context.widgetDao.save(w)
      })
    "ok"
  }

  @ModelAttribute("widgets")
  def widgets = {
    val ordering = Ordering[(String, Int)].on[Widget](x => (Option(x.location).map(_.toLowerCase).getOrElse(""), x
      .position))
    context.widgetDao.findAll.sorted(ordering).toArray
  }

  @ModelAttribute("classes")
  def classes = {
    val map = new mutable.LinkedHashMap[String, String]
    for ( c <- ComponentClassScanner.widgets.sortBy(_.getSimpleName) ) {
      map += c.getName -> c.getSimpleName
    }
    map.asJava
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/**
 * @var $this yii\web\View
 * @var $model lo\plugins\models\search\CategorySearch
 * @var $form yii\widgets\ActiveForm
 */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>
    <?= $form->field($model, 'name') ?>

        <?= Html::submitButton(Yii::t('plugin', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('plugin', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
package org.sakaiproject.nakamura.cluster;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.sakaiproject.nakamura.api.cluster.ClusterServer;
import org.sakaiproject.nakamura.api.cluster.ClusterTrackingService;
import org.sakaiproject.nakamura.api.cluster.ClusterUser;
import org.sakaiproject.nakamura.api.cluster.cache.ClusterServerImpl;
import org.sakaiproject.nakamura.api.cluster.cache.ClusterUserImpl;
import org.sakaiproject.nakamura.api.memory.Cache;
import org.sakaiproject.nakamura.api.memory.CacheManagerService;
import org.sakaiproject.nakamura.api.memory.CacheScope;
import org.sakaiproject.nakamura.api.servlet.HttpOnlyCookie;
import org.sakaiproject.nakamura.util.StringUtils;
import org.sakaiproject.nakamura.util.osgi.EventUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The ClusterTrackingService, maintains an entry for the active server and tracks active
 * users with a cluster replicated shared cache.
 */
@Component(description = "Cluster tracking, tracks app servers and users within the cluster", label = "Cluster Tracking", immediate = true, metatype=true)
@Service({ ClusterTrackingService.class, Runnable.class })
@Properties(value = {
    @Property(name = Scheduler.PROPERTY_SCHEDULER_CONCURRENT, boolValue = false),
    @Property(name = Scheduler.PROPERTY_SCHEDULER_PERIOD, longValue = 300L) })
public class ClusterTrackingServiceImpl implements ClusterTrackingService, Runnable {

  /**
   * The logger for the service.
   */
  private static final Logger LOGGER = LoggerFactory
      .getLogger(ClusterTrackingServiceImpl.class);
  /**
   * The name of the cache used to track users.
   */
  private static final String TRACKING_CACHE = "user-tracking-cache";

  /**
   * The name of the cache used to track users.
   */
  private static final String SERVER_CACHE = "server-tracking-cache";

  /**
   * The Name of the Cookie used to track users.
   */
  private static final String SAKAI_TRACKING = "SAKAI-TRACKING";

  @Property(name="secure-host-url", value = "http://localhost:8081",description = "The URL where other nodes in the cluster can contact this App server, will be different for each app server. Normal urls appended to the end of the url.")
  protected static final String PROP_SECURE_HOST_URL = "secure-host-url";

  /**
   * The Cache Manager service, injected.
   */
  @Reference
  private CacheManagerService cacheManagerService;

  @Reference
  private EventAdmin eventAdmin;

  /**
   * A String representing the time when the service started.
   */
  private String componentStartTime;

  /**
   * The Id of the server, takned from JMX normally processID@server-hostname.
   */
  private String serverId;
  /**
   * True when the service is active.
   */
  private boolean isActive = false;

  /**
   * becomes true when the server is registered
   */
  private boolean isReady = false;
  private int serverNumber;
  private String thisSecureUrl;
  private UniqueIdGenerator uniqueIdGenerator;

  /**
   * Constructor for testing purposes only.
   *
   * @param cacheManagerService2
   */
  protected ClusterTrackingServiceImpl(CacheManagerService cacheManagerService) {
    this.cacheManagerService = cacheManagerService;
  }

  public ClusterTrackingServiceImpl() {
  }

  /**
   * Activate the service, getting the id of the jvm instance and register the instance.
   *
   * @param ctx
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  protected void activate(ComponentContext ctx) throws Exception {

    Dictionary<String, Object> properties = ctx.getProperties();
    thisSecureUrl = PropertiesUtil.toString(properties.get(PROP_SECURE_HOST_URL), "");

    componentStartTime = String.valueOf(System.currentTimeMillis());
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("java.lang:type=Runtime");
    serverId = ((String) mbeanServer.getAttribute(name, "Name")).replace("@", "-");
    isActive = true;
    pingInstance();
    uniqueIdGenerator = new UniqueIdGenerator(serverNumber);
    isReady = true;
  }

  /**
   * Remove the registration for the instance.
   *
   * @param ctx
   * @throws Exception
   */
  protected void deactivate(ComponentContext ctx) throws Exception {
    try {
      removeInstance(serverId);
    } catch ( IllegalStateException e ) {
      LOGGER.info("Cluster Tacking Cache has already been disposed, the server registration will timeout on other nodes :{}",e.getMessage());
      LOGGER.debug(e.getMessage(),e);
    }
  }

  /**
   * Track a user, called from a filter, this will update the central cache for the cookie
   * and set the cookie if not present.
   *
   * @param request
   *          the http request oject.
   * @param response
   *          the http response object which will, if there is no cookie present, and the
   *          response is not committed, have the cookie set.
   */
  public void trackClusterUser(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    String remoteUser = request.getRemoteUser();
    boolean tracking = false;
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie != null) {
          String cookieName = cookie.getName();
          if (cookieName.equals(SAKAI_TRACKING)) {
            String trackingCookie = cookie.getValue();
            if (isServerAlive(trackingCookie)) {
              try {
                pingTracking(trackingCookie, remoteUser);
                tracking = true;
              } catch (PingRemoteTrackingFailedException e) {
                LOGGER.warn(e.getMessage());
              }
            }
          }
        }
      }
    }
    if (!tracking && !response.isCommitted()) {
      // the tracking cookie is the a sha1 hash of the thread, the server startup id and
      // time
      String seed = Thread.currentThread().getName() + ":" + componentStartTime + ":"
          + System.currentTimeMillis();
      String trackingCookie = Thread.currentThread().getName() + ":"
          + System.currentTimeMillis();
      try {
        trackingCookie = serverId + "-" + StringUtils.sha1Hash(seed);
      } catch (Exception e) {
        LOGGER.error("Failed to hash new cookie ", e);
      }

      Cookie cookie = new HttpOnlyCookie(SAKAI_TRACKING, trackingCookie);
      cookie.setMaxAge(-1);
      cookie.setComment("Cluster User Tracking");
      cookie.setPath("/");
      cookie.setVersion(0);
      response.addCookie(cookie);
      // rfc 2109 section 4.5. stop http 1.1 caches caching the response
      response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
      // and stop http 1.0 caches caching the response
      response.addDateHeader("Expires", 0);
      // we *do not* track cookies the first time, to avoid DOS on the cookie store.
      // pingTracking(trackingCookie, remoteUser);
    }

  }

  public String[] getRequestTrackingCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    Set<String> tracking = new HashSet<String>();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie != null) {
          String cookieName = cookie.getName();
          if (cookieName.equals(SAKAI_TRACKING)) {
            String trackingCookie = cookie.getValue();
            if (isServerAlive(trackingCookie)) {
              tracking.add(trackingCookie);
            }
          }
        }
      }
    }
    return tracking.toArray(new String[tracking.size()]);
  }

  /**
   * @param trackingCookie
   * @return
   */
  private boolean isServerAlive(String trackingCookie) {
    return getServer(trackingCookie) != null;
  }

  /**
   * @param trackingCookie
   * @return
   */
  private boolean isRemote(String trackingCookie) {
    ClusterServer server = getServer(trackingCookie);
    if (server != null) {
      return !serverId.equals(server.getServerId());
    }
    return true;
  }

  /**
   * @param trackingCookie
   * @return
   */
  public ClusterServer getServer(String trackingCookie) {
    int i = trackingCookie.lastIndexOf('-');
    if (i > 0) {
      String serverId = trackingCookie.substring(0, i);
      return getServerCache().get(serverId);
    }
    return null;
  }

  /**
   * Get the user based on a tracking id.
   *
   * @param trackingCookie
   * @return
   */
  public ClusterUser getUser(String trackingCookie) {
    if (trackingCookie == null) {
      return null;
    }
    Cache<ClusterUser> cache = getTrackingCache();
    ClusterUser cuser = cache.get(trackingCookie);
    if (cuser == null) {
      return null;
    } else if (((ClusterUserImpl) cuser).expired()) {
      cache.remove(trackingCookie);
      return null;
    }
    return cuser;
  }

  /**
   * update the tracking for a user, if expired or the user name has changed.
   *
   * @param trackingCookie
   *          the cookie tracking.
   * @param remoteUser
   *          the user id.
   * @throws PingRemoteTrackingFailedException
   */
  private void pingTracking(String trackingCookie, String remoteUser)
      throws PingRemoteTrackingFailedException {
    pingTracking(trackingCookie, remoteUser, true);
  }

  /**
   * @param trackingCookie
   * @param remoteUser
   * @throws PingRemoteTrackingFailedException
   */
  protected void pingTracking(String trackingCookie, String remoteUser, boolean andRemote)
      throws PingRemoteTrackingFailedException {
    Cache<ClusterUser> cache = getTrackingCache();
    ClusterUser cuser = cache.get(trackingCookie);
    if (cuser == null || ((ClusterUserImpl) cuser).expired(remoteUser)) {
      if (andRemote && isRemote(trackingCookie)) {
        pingRemoteTracking(trackingCookie, remoteUser);
      }
      cache.put(trackingCookie, new ClusterUserImpl(remoteUser, serverId));
    }
  }

  /**
   * @param trackingCookie
   * @param remoteUser
   * @throws PingRemoteTrackingFailedException
   */
  private void pingRemoteTracking(String trackingCookie, String remoteUser)
      throws PingRemoteTrackingFailedException {
    ClusterServer clusterServer = getServer(trackingCookie);
    if (clusterServer == null) {
      throw new PingRemoteTrackingFailedException("Server at " + trackingCookie
          + " not alive ");
    }
    // send over OSGi and then JMS over the OSGi2JMS Bridge
    Dictionary<String, Object> messageDict = new Hashtable<String, Object>();
    messageDict.put(EVENT_FROM_SERVER, serverId);
    messageDict.put(EVENT_TO_SERVER, clusterServer.getServerId());
    messageDict.put(EVENT_TRACKING_COOKIE, trackingCookie);
    messageDict.put(EVENT_USER, remoteUser);
    String remotePingTopic = EVENT_PING_CLUSTER_USER + "/"
        + EventUtils.safeTopicElement(clusterServer.getServerId());
    Event pingUserEvent = new Event(remotePingTopic, messageDict);
    eventAdmin.postEvent(pingUserEvent);

  }

  /**
   * Update the server registration.
   */
  private void pingInstance() {
    if (isActive) {
      if (!isReady) {
        do {
          updateServerNumber();
          getServerCache().put(serverId,
              new ClusterServerImpl(serverId, serverNumber, thisSecureUrl));
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {

          }
        } while (!checkServerNumber());

      } else {
        try {
          Object cs = getServerCache().put(serverId,
              new ClusterServerImpl(serverId, serverNumber, thisSecureUrl));

          if (cs == null) {
            LOGGER.warn("This servers registration dissapeared, replaced as {} ",
                serverId);
          }
        } catch (NullPointerException e) {
          // prevent excessive logging in edge case where cache == null;
          LOGGER.debug(e.getLocalizedMessage(), e);
        }
      }
    }
  }

  /**
   * @return true if the only server number registered is our server number
   */
  private boolean checkServerNumber() {
    List<ClusterServer> servers = getServerCache().list();
    for (ClusterServer server : servers) {
      if (server.getServerNumber() == serverNumber
          && !serverId.equals(server.getServerId())) {
        return false;
      }
    }
    return true;
  }

  /**
   * Find the next unique server number.
   */
  private void updateServerNumber() {
    List<ClusterServer> servers = getServerCache().list();
    boolean[] spare = new boolean[servers.size()];
    for (int i = 0; i < spare.length; i++) {
      spare[i] = true;
    }
    for (ClusterServer server : servers) {
      int i = server.getServerNumber();
      if (i < spare.length) {
        spare[i] = false;
      }
    }
    serverNumber = spare.length;
    for (int i = 0; i < spare.length; i++) {
      if (spare[i]) {
        serverNumber = i;
        break;
      }
    }
  }

  /**
   * @param serverId
   *          remove the instance from the cluster wide cache.
   */
  private void removeInstance(String serverId) {
    getServerCache().remove(serverId);
  }

  /**
   * @return the cache used to store server registrations.
   */
  private Cache<ClusterServer> getServerCache() {
    return cacheManagerService.getCache(SERVER_CACHE, CacheScope.CLUSTERREPLICATED);
  }

  /**
   * @return the Cache used to track users
   */
  private Cache<ClusterUser> getTrackingCache() {
    // this is a local cache. if we add things here we ping the home server
    return cacheManagerService.getCache(TRACKING_CACHE, CacheScope.INSTANCE);
  }

  /**
   * {@inheritDoc}
   *
   * Invoked as a task by the Sling Scheduler, once every 5 minutes to update the last
   * time the server was registered in the cluster cache.
   *
   * @see java.lang.Runnable#run()
   */
  public void run() {
    pingInstance();
  }

  /**
   * {@inheritDoc}
   *
   * @see org.sakaiproject.nakamura.api.cluster.ClusterTrackingService#getAllServers()
   */
  public List<ClusterServer> getAllServers() {
    return getServerCache().list();
  }

  /**
   * {@inheritDoc}
   *
   * @see org.sakaiproject.nakamura.api.cluster.ClusterTrackingService#getCurrentServerId()
   */
  public String getCurrentServerId() {
    return serverId;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.sakaiproject.nakamura.api.cluster.ClusterTrackingService#getClusterUniqueId()
   */
  public String getClusterUniqueId() {
    return uniqueIdGenerator.nextId();
  }

}


text:
package org.opencb.opencga.catalog.models;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by jacobo on 11/09/14.
 */
public class Variable {

    private String name;
    private String category;

    /**
     * Type accepted values: text, numeric.
     */
    private VariableType type;
    private Object defaultValue;
    private boolean required;
    private boolean multiValue;

    /**
     * Example for numeric range: -3:5.
     * Example for categorical values: T,F
     */
    private List<String> allowedValues;
    private long rank;
    private String dependsOn;
    private String description;
    /**
     * Variables for validate internal fields. Only valid if type is OBJECT.
     **/
    private Set<Variable> variableSet;
    private Map<String, Object> attributes;

    public Variable() {
    }

    public Variable(String name, String category, VariableType type, Object defaultValue, boolean required, boolean multiValue,
                    List<String> allowedValues, long rank, String dependsOn, String description, Set<Variable> variableSet,
                    Map<String, Object> attributes) {
        this.name = name;
        this.category = category;
        this.type = type;
        this.defaultValue = defaultValue;
        this.required = required;
        this.multiValue = multiValue;
        this.allowedValues = allowedValues;
        this.rank = rank;
        this.dependsOn = dependsOn;
        this.description = description;
        this.variableSet = variableSet;
        this.attributes = attributes;
    }

    public enum VariableType {
        BOOLEAN,
        CATEGORICAL,
        NUMERIC,
        TEXT,
        OBJECT
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Variable{");
        sb.append("name='").append(name).append('\'');
        sb.append(", category='").append(category).append('\'');
        sb.append(", type=").append(type);
        sb.append(", defaultValue=").append(defaultValue);
        sb.append(", required=").append(required);
        sb.append(", multiValue=").append(multiValue);
        sb.append(", allowedValues=").append(allowedValues);
        sb.append(", rank=").append(rank);
        sb.append(", dependsOn='").append(dependsOn).append('\'');
        sb.append(", description='").append(description).append('\'');
        sb.append(", variableSet=").append(variableSet);
        sb.append(", attributes=").append(attributes);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Variable)) {
            return false;
        }

        Variable variable = (Variable) o;

        if (!name.equals(variable.name)) {
            return false;
        }

        return true;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public VariableType getType() {
        return type;
    }

    public void setType(VariableType type) {
        this.type = type;
    }

    public Object getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(Object defaultValue) {
        this.defaultValue = defaultValue;
    }

    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    public boolean isMultiValue() {
        return multiValue;
    }

    public void setMultiValue(boolean multiValue) {
        this.multiValue = multiValue;
    }

    public List<String> getAllowedValues() {
        return allowedValues;
    }

    public void setAllowedValues(List<String> allowedValues) {
        this.allowedValues = allowedValues;
    }

    public long getRank() {
        return rank;
    }

    public void setRank(long rank) {
        this.rank = rank;
    }

    public String getDependsOn() {
        return dependsOn;
    }

    public void setDependsOn(String dependsOn) {
        this.dependsOn = dependsOn;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<Variable> getVariableSet() {
        return variableSet;
    }

    public void setVariableSet(Set<Variable> variableSet) {
        this.variableSet = variableSet;
    }

    public Map<String, Object> getAttributes() {
        return attributes;
    }

    public void setAttributes(Map<String, Object> attributes) {
        this.attributes = attributes;
    }
}


text:
package bsoncodec

import (
	"fmt"
	"reflect"
	"strconv"

	"go.mongodb.org/mongo-driver/bson/bsonoptions"
	"go.mongodb.org/mongo-driver/bson/bsonrw"
	"go.mongodb.org/mongo-driver/bson/bsontype"
)

var defaultMapCodec = NewMapCodec()

// MapCodec is the Codec used for map values.
type MapCodec struct {
	DecodeZerosMap         bool
	EncodeNilAsEmpty       bool
	EncodeKeysWithStringer bool
}

var _ ValueCodec = &MapCodec{}

// KeyMarshaler is the interface implemented by an object that can marshal itself into a string key.
// This applies to types used as map keys and is similar to encoding.TextMarshaler.
type KeyMarshaler interface {
	MarshalKey() (key string, err error)
}

// KeyUnmarshaler is the interface implemented by an object that can unmarshal a string representation
// of itself. This applies to types used as map keys and is similar to encoding.TextUnmarshaler.
//
// UnmarshalKey must be able to decode the form generated by MarshalKey.
// UnmarshalKey must copy the text if it wishes to retain the text
// after returning.
type KeyUnmarshaler interface {
	UnmarshalKey(key string) error
}

// NewMapCodec returns a MapCodec with options opts.
func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec {
	mapOpt := bsonoptions.MergeMapCodecOptions(opts...)

	codec := MapCodec{}
	if mapOpt.DecodeZerosMap != nil {
		codec.DecodeZerosMap = *mapOpt.DecodeZerosMap
	}
	if mapOpt.EncodeNilAsEmpty != nil {
		codec.EncodeNilAsEmpty = *mapOpt.EncodeNilAsEmpty
	}
	if mapOpt.EncodeKeysWithStringer != nil {
		codec.EncodeKeysWithStringer = *mapOpt.EncodeKeysWithStringer
	}
	return &codec
}

// EncodeValue is the ValueEncoder for map[*]* types.
func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
	if !val.IsValid() || val.Kind() != reflect.Map {
		return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
	}

	if val.IsNil() && !mc.EncodeNilAsEmpty {
		// If we have a nil map but we can't WriteNull, that means we're probably trying to encode
		// to a TopLevel document. We can't currently tell if this is what actually happened, but if
		// there's a deeper underlying problem, the error will also be returned from WriteDocument,
		// so just continue. The operations on a map reflection value are valid, so we can call
		// MapKeys within mapEncodeValue without a problem.
		err := vw.WriteNull()
		if err == nil {
			return nil
		}
	}

	dw, err := vw.WriteDocument()
	if err != nil {
		return err
	}

	return mc.mapEncodeValue(ec, dw, val, nil)
}

// mapEncodeValue handles encoding of the values of a map. The collisionFn returns
// true if the provided key exists, this is mainly used for inline maps in the
// struct codec.
func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error {

	elemType := val.Type().Elem()
	encoder, err := ec.LookupEncoder(elemType)
	if err != nil && elemType.Kind() != reflect.Interface {
		return err
	}

	keys := val.MapKeys()
	for _, key := range keys {
		keyStr, err := mc.encodeKey(key)
		if err != nil {
			return err
		}

		if collisionFn != nil && collisionFn(keyStr) {
			return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key)
		}

		currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.MapIndex(key))
		if lookupErr != nil && lookupErr != errInvalidValue {
			return lookupErr
		}

		vw, err := dw.WriteDocumentElement(keyStr)
		if err != nil {
			return err
		}

		if lookupErr == errInvalidValue {
			err = vw.WriteNull()
			if err != nil {
				return err
			}
			continue
		}

		err = currEncoder.EncodeValue(ec, vw, currVal)
		if err != nil {
			return err
		}
	}

	return dw.WriteDocumentEnd()
}

// DecodeValue is the ValueDecoder for map[string/decimal]* types.
func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
	if val.Kind() != reflect.Map || (!val.CanSet() && val.IsNil()) {
		return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
	}

	switch vrType := vr.Type(); vrType {
	case bsontype.Type(0), bsontype.EmbeddedDocument:
	case bsontype.Null:
		val.Set(reflect.Zero(val.Type()))
		return vr.ReadNull()
	case bsontype.Undefined:
		val.Set(reflect.Zero(val.Type()))
		return vr.ReadUndefined()
	default:
		return fmt.Errorf("cannot decode %v into a %s", vrType, val.Type())
	}

	dr, err := vr.ReadDocument()
	if err != nil {
		return err
	}

	if val.IsNil() {
		val.Set(reflect.MakeMap(val.Type()))
	}

	if val.Len() > 0 && mc.DecodeZerosMap {
		clearMap(val)
	}

	eType := val.Type().Elem()
	decoder, err := dc.LookupDecoder(eType)
	if err != nil {
		return err
	}
	eTypeDecoder, _ := decoder.(typeDecoder)

	if eType == tEmpty {
		dc.Ancestor = val.Type()
	}

	keyType := val.Type().Key()

	for {
		key, vr, err := dr.ReadElement()
		if err == bsonrw.ErrEOD {
			break
		}
		if err != nil {
			return err
		}

		k, err := mc.decodeKey(key, keyType)
		if err != nil {
			return err
		}

		elem, err := decodeTypeOrValueWithInfo(decoder, eTypeDecoder, dc, vr, eType, true)
		if err != nil {
			return newDecodeError(key, err)
		}

		val.SetMapIndex(k, elem)
	}
	return nil
}

func clearMap(m reflect.Value) {
	var none reflect.Value
	for _, k := range m.MapKeys() {
		m.SetMapIndex(k, none)
	}
}

func (mc *MapCodec) encodeKey(val reflect.Value) (string, error) {
	if mc.EncodeKeysWithStringer {
		return fmt.Sprint(val), nil
	}

	// keys of any string type are used directly
	if val.Kind() == reflect.String {
		return val.String(), nil
	}
	// KeyMarshalers are marshaled
	if km, ok := val.Interface().(KeyMarshaler); ok {
		if val.Kind() == reflect.Ptr && val.IsNil() {
			return "", nil
		}
		buf, err := km.MarshalKey()
		if err == nil {
			return buf, nil
		}
		return "", err
	}

	switch val.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.FormatInt(val.Int(), 10), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return strconv.FormatUint(val.Uint(), 10), nil
	}
	return "", fmt.Errorf("unsupported key type: %v", val.Type())
}

var keyUnmarshalerType = reflect.TypeOf((*KeyUnmarshaler)(nil)).Elem()

func (mc *MapCodec) decodeKey(key string, keyType reflect.Type) (reflect.Value, error) {
	keyVal := reflect.ValueOf(key)
	var err error
	switch {
	// First, if EncodeKeysWithStringer is not enabled, try to decode withKeyUnmarshaler
	case !mc.EncodeKeysWithStringer && reflect.PtrTo(keyType).Implements(keyUnmarshalerType):
		keyVal = reflect.New(keyType)
		v := keyVal.Interface().(KeyUnmarshaler)
		err = v.UnmarshalKey(key)
		keyVal = keyVal.Elem()
	// Otherwise, go to type specific behavior
	default:
		switch keyType.Kind() {
		case reflect.String:
			keyVal = reflect.ValueOf(key).Convert(keyType)
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n, parseErr := strconv.ParseInt(key, 10, 64)
			if parseErr != nil || reflect.Zero(keyType).OverflowInt(n) {
				err = fmt.Errorf("failed to unmarshal number key %v", key)
			}
			keyVal = reflect.ValueOf(n).Convert(keyType)
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			n, parseErr := strconv.ParseUint(key, 10, 64)
			if parseErr != nil || reflect.Zero(keyType).OverflowUint(n) {
				err = fmt.Errorf("failed to unmarshal number key %v", key)
				break
			}
			keyVal = reflect.ValueOf(n).Convert(keyType)
		case reflect.Float32, reflect.Float64:
			if mc.EncodeKeysWithStringer {
				parsed, err := strconv.ParseFloat(key, 64)
				if err != nil {
					return keyVal, fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %v", keyType.Kind(), err)
				}
				keyVal = reflect.ValueOf(parsed)
				break
			}
			fallthrough
		default:
			return keyVal, fmt.Errorf("unsupported key type: %v", keyType)
		}
	}
	return keyVal, err
}


text:
if not pcall(require, 'hop') then
  return
end

local hop = require('hop')

hop.setup()

-- vim.keymap.set('n', ' ', hop.hint_words)


text:
<!DOCTYPE html>

<title>Canvas test: 2d.gradient.radial.transform.3</title>

<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css">

2d.gradient.radial.transform.3

Radial gradient transforms do not experience broken caching effects

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
package org.spoutcraft.mod.gui.builtin;

import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import org.spoutcraft.api.util.RandomUtil;
import org.spoutcraft.api.util.RenderUtil;
import org.spoutcraft.api.util.TimeUtil;

import org.lwjgl.opengl.GL11;

public class SpoutcraftBackground extends Gui {
	private static ResourceLocation location = selectBackground();

	private static ResourceLocation selectBackground() {
		switch (TimeUtil.getTime()) {
			case "day":
				return new ResourceLocation("spoutcraft", "textures/gui/title/background/day/background_" + RandomUtil.inclusive(1, 29) + ".jpg");
			case "evening":
				return new ResourceLocation("spoutcraft", "textures/gui/title/background/day/background_" + RandomUtil.inclusive(1, 29) + ".jpg");
			case "night":
				return new ResourceLocation("spoutcraft", "textures/gui/title/background/day/background_" + RandomUtil.inclusive(1, 29) + ".jpg");
			default:
				return new ResourceLocation("spoutcraft", "textures/gui/title/background/day/background_" + RandomUtil.inclusive(1, 29) + ".jpg");
		}
	}

	public void drawBackground(int x, int y, int width, int height, boolean overlay) {
		RenderUtil.MINECRAFT.getTextureManager().bindTexture(location);
		GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		RenderUtil.create2DRectangleModal(x, y, width, height, 0);
		RenderUtil.TESSELLATOR.draw();

		if (overlay) {
			drawGradientRect(0, 0, width, height, Integer.MAX_VALUE, 0);
		}
	}
}