text:
"""
rcs4cvs2svn prepares an RCS project for processing with cvs2svn.

rcs4cvs2svn is useful for developers who still have ancient source code
floating around in RCS repositories and want to move it to a modern SCM system.

While rcs4cvs2svn does not provide any possibility to directly migrate to any
other SCM system, it creates a copy of your RCS repository that can be
processed by `cvs2svn <http://cvs2svn.tigris.org/>`_.

That way, you'll end up with a Subversion repository, which already may be
sufficient. Alternatively, Subversion offers a sound base for further migration
to another SCM such as Git or Mercurial, as most SCM vendors provide tools to
migrate from SVN but not from RCS.

(You can of course use rcs4cvs2svn as replacement for various rcs2cvs scripts
floating around. Unlike many of these scripts, rcs4cvs2svn can process
filenames with space characters and handles any errors it encounters.)

Usage
=====

Usage is simple::

  $ python rcs4cvs2svn.py /path/to/rcs/project /path/to/cvs/repository

There are a couple of options, for more information run::

  $ python rcs4cvs2svn.py --help

Tutorial
========

This section describes how to migrate an RCS repository to
CVS and then to Subversion.

First, create a simple RCS repository for a project called "hello" which
contains a single file, "hello.txt" with 2 revisions::

  $ mkdir -p hello/RCS
  $ cd hello
  $ echo "hello world!" >hello.txt
  $ echo "Added greetings.\\n." | ci -u hello.txt
  $ co -l hello.txt
  $ echo "hello space!" >>hello.txt
  $ echo "Added more greetings.\\n." | ci -u hello.txt

Now migrate the the RCS repository to CVS::

  $ python rcs4cvs2svn.py hello/ /tmp/hello_cvs/

The output should be::

  INFO:rcs4cvs2svn:create new CVS repository at "/tmp/hello_cvs/"
  INFO:rcs4cvs2svn:migrated 1 files from "hello/" to "/tmp/hello_cvs/"

Because CVS still is a very dated way to manage a software project, let's move
on to the next step of evolution: Subversion. You will need ``cvs2svn``,
available from <http://cvs2svn.tigris.org/>.

While there are several ways to convert CVS to SVN, the easiest for our task is
to simple create a SVN dumpfile containing the CVS as trunk::

  $ cvs2svn --trunk-only --dumpfile hello.dump /tmp/hello_cvs/

Now you can create a SVN repository and load the trunk into it::

  $ svnadmin create /tmp/hello_svn/
  $ svnadmin load /tmp/hello_svn/ <hello.dump

Moving on to even more advanced SCM systems is left as an exercise to the
reader.

License
=======

Copyright (c) 2006-2011, Thomas Aglassinger. All rights reserved. Distributed
under the `BSD License <http://www.opensource.org/licenses/bsd-license.php>`_.

Source code
===========

The source code is available from <https://github.com/roskakori/rcs4cvs2svn>.

Version information
===================

**Version 1.2, 2011-10-26**

* Fixed logging which could cause issues with file names containing non ASCII
  characters or percent signs (%).
* Improved handling of CVS target folder, which can now be a relative folder
  even though ``csv init`` expects an absolute folder.
* Improved API: Added ``rcs4cvs2svn.main()``, which can be called from Python
  similar to the command line.
* Changed test shell scripts to proper unit test.
* Cleaned up PEP8 issues.

**Version 1.1, 2010-07-06**

* Added automatic creation of CVS repository in case the target path does
  not already contain a ``CVSROOT`` folder. In order for this to work, the
  ``cvs`` command line client has  to be installed.
* Fixed protection bits in CVS which were copied from RCS and did make the
  files write protected (which was not an issue for converting to SVN but
  forced the user to remove the CVS for repeated conversion).
* Cleaned up API. Simply ``import rcs4cvs2svn`` and call
  ``initCvsRepository()`` and ``convertRcsToCvs()`` as needed.

**Version 1.0, 2010-07-04**

* Initial public release.

**Version 0.9, 2006-05-01**

* Initial internal version used to convert some of my own projects.
"""
# Copyright (c) 2006-2011, Thomas Aglassinger
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of Thomas Aglassinger nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

# **Developer cheat sheet**
#
# Create the installer archive::
#
# $ python setup.py sdist --formats=zip
#
# Upload release to PyPI::
#
# $ python test_rcs4cvs2svn.py
# $ pep8 --repeat *.py
# $ python setup.py sdist --formats=zip upload
#
# Tag a release in the repository::
#
# $ git tag -a -m "Tagged version 1.x." 1.x
# $ git push --tags

import errno
import logging
import optparse
import os.path
import shutil
import subprocess
import sys

log = logging.getLogger("rcs4cvs2svn")

__version__ = "1.2"

def _listFiles(folderToListPath):
    assert folderToListPath is not None

    result = []
    absoluteBaseDir = os.path.abspath(folderToListPath)
    for root, _, files in os.walk(folderToListPath):
        for name in files:
            absoluteFilePath = os.path.abspath(os.path.join(root, name))
            if absoluteFilePath.find(".svn") == -1:
                relativeFilePath = absoluteFilePath[len(absoluteBaseDir) + 1:]
                result.append(relativeFilePath)
    return result

def _makedirs(folderToCreatePath):
    """
    Like ``os.makedirs()``, but does not raise OSError if directory already
    exists.
    """
    assert folderToCreatePath is not None

    try:
        os.makedirs(folderToCreatePath)
    except OSError, error:
        if error.errno != errno.EEXIST:
            raise

def initCvsRepository(cvsTargetFolderPath):
    """
    Check that ``cvsTargetFolderPath`` is a path to a CVS repository and if
    not, call the ``csv`` command line client to create one.
    """
    assert cvsTargetFolderPath is not None

    absoluteCvsTargetFolderPath = os.path.abspath(cvsTargetFolderPath)
    cvsRootPath = os.path.join(absoluteCvsTargetFolderPath, "CVSROOT")
    if not os.path.exists(cvsRootPath):
        log.info(u"create new CVS repository at \"%s\"",
            absoluteCvsTargetFolderPath)
        subprocess.check_call([
            "cvs", "-d", absoluteCvsTargetFolderPath, "init"
        ])

def convertRcsToCvs(rcsSourceFolderPath, cvsTargetFolderPath):
    """
    Convert source code in RCS repository  ``rcsSourceFolderPath`` to
    existing CVS repository at ``cvsTargetFolderPath``.
    """
    assert rcsSourceFolderPath is not  None
    assert cvsTargetFolderPath is not None

    rcsFiles = _listFiles(rcsSourceFolderPath)
    copiedFileCount = 0
    for filePath in rcsFiles:
        if filePath.endswith(",v"):
            rcsFilePath = os.path.join(rcsSourceFolderPath, filePath)
            possibleRcsDir = os.path.split(filePath)[0]
            possibleRcsDirName = os.path.split(possibleRcsDir)[1]
            if possibleRcsDirName == "RCS":
                rcsParentDir = os.path.split(possibleRcsDir)[0]
                rcsFileName = os.path.split(rcsFilePath)[1]
                flattenedFilePath = os.path.join(
                    cvsTargetFolderPath,
                    os.path.join(rcsParentDir, rcsFileName)
                )
                log.debug(u"copy \"%s\" -> \"%s\"",
                    filePath, flattenedFilePath)
                _makedirs(os.path.split(flattenedFilePath)[0])
                # Copy file without permission bits.
                shutil.copyfile(rcsFilePath, flattenedFilePath)
                copiedFileCount += 1
    log.info(
        u"migrated %d files from \"%s\" to \"%s\"",
        copiedFileCount, rcsSourceFolderPath, cvsTargetFolderPath
    )

def _parsedOptions(arguments):
    assert arguments is not None

    # Parse command line options.
    Usage = """usage: %prog [options] RCS_FOLDER CVS_FOLDER

    Prepare an RCS project for processing with cvs2svn."""
    parser = optparse.OptionParser(
        usage=Usage,
        version="%prog " + __version__
    )
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
                      help="log all actions performed in console")
    (options, others) = parser.parse_args(arguments)
    if len(others) == 0:
        parser.error("RCS_FOLDER and CVS_FOLDER must be specified")
    elif len(others) == 1:
        parser.error("CVS_FOLDER must be specified")
    elif len(others) > 2:
        parser.error("unknown options must be removed: %s" % others[2:])
    if options.verbose:
        log.setLevel(logging.DEBUG)

    rcsSourceFolderPath = others[0]
    cvsTargetFolderPath = others[1]

    return rcsSourceFolderPath, cvsTargetFolderPath

def main(argv=None):
    if argv is None:
        argv = sys.argv

    exitCode = 1
    try:
        rcsSourceFolderPath, cvsTargetFolderPath = _parsedOptions(argv[1:])
        initCvsRepository(cvsTargetFolderPath)
        convertRcsToCvs(rcsSourceFolderPath, cvsTargetFolderPath)
        exitCode = 0
    except (EnvironmentError, subprocess.CalledProcessError), error:
        log.error(error)
    except KeyboardInterrupt:
        log.warning(u"interrupted by user")
    except Exception, error:
        log.exception(error)
    return exitCode

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    sys.exit(main())


text:
package geoip

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DescribeGeoipInstanceDataUrl invokes the geoip.DescribeGeoipInstanceDataUrl API synchronously
func (client *Client) DescribeGeoipInstanceDataUrl(request *DescribeGeoipInstanceDataUrlRequest) (response *DescribeGeoipInstanceDataUrlResponse, err error) {
	response = CreateDescribeGeoipInstanceDataUrlResponse()
	err = client.DoAction(request, response)
	return
}

// DescribeGeoipInstanceDataUrlWithChan invokes the geoip.DescribeGeoipInstanceDataUrl API asynchronously
func (client *Client) DescribeGeoipInstanceDataUrlWithChan(request *DescribeGeoipInstanceDataUrlRequest) (<-chan *DescribeGeoipInstanceDataUrlResponse, <-chan error) {
	responseChan := make(chan *DescribeGeoipInstanceDataUrlResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DescribeGeoipInstanceDataUrl(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DescribeGeoipInstanceDataUrlWithCallback invokes the geoip.DescribeGeoipInstanceDataUrl API asynchronously
func (client *Client) DescribeGeoipInstanceDataUrlWithCallback(request *DescribeGeoipInstanceDataUrlRequest, callback func(response *DescribeGeoipInstanceDataUrlResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DescribeGeoipInstanceDataUrlResponse
		var err error
		defer close(result)
		response, err = client.DescribeGeoipInstanceDataUrl(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DescribeGeoipInstanceDataUrlRequest is the request struct for api DescribeGeoipInstanceDataUrl
type DescribeGeoipInstanceDataUrlRequest struct {
	*requests.RpcRequest
	InstanceId   string `position:"Query" name:"InstanceId"`
	DataType     string `position:"Query" name:"DataType"`
	UserClientIp string `position:"Query" name:"UserClientIp"`
	Lang         string `position:"Query" name:"Lang"`
}

// DescribeGeoipInstanceDataUrlResponse is the response struct for api DescribeGeoipInstanceDataUrl
type DescribeGeoipInstanceDataUrlResponse struct {
	*responses.BaseResponse
	FixedDomainDownloadUrl string `json:"FixedDomainDownloadUrl" xml:"FixedDomainDownloadUrl"`
	RequestId              string `json:"RequestId" xml:"RequestId"`
	DownloadUrl            string `json:"DownloadUrl" xml:"DownloadUrl"`
}

// CreateDescribeGeoipInstanceDataUrlRequest creates a request to invoke DescribeGeoipInstanceDataUrl API
func CreateDescribeGeoipInstanceDataUrlRequest() (request *DescribeGeoipInstanceDataUrlRequest) {
	request = &DescribeGeoipInstanceDataUrlRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("geoip", "2020-01-01", "DescribeGeoipInstanceDataUrl", "geoip", "openAPI")
	request.Method = requests.POST
	return
}

// CreateDescribeGeoipInstanceDataUrlResponse creates a response to parse from DescribeGeoipInstanceDataUrl response
func CreateDescribeGeoipInstanceDataUrlResponse() (response *DescribeGeoipInstanceDataUrlResponse) {
	response = &DescribeGeoipInstanceDataUrlResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}

redpajama_set_name: RedPajamaGithub


text:
package cubicchunks;

import org.junit.Test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

import javax.annotation.Nonnull;

import cubicchunks.util.XYZAddressable;
import cubicchunks.util.XYZMap;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class TestXYZMap {
	@Test
	public void testSimpleGetEqual() {
		XYZAddressable value = new Addressable(0, 0, 0, "1");
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		map.put(value);
		assertEquals(value, map.get(0, 0, 0));
	}

	@Test
	public void testGetEqualRandomPositions() {
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		//set seed so that tests are predictable
		Random rand = new Random(42);
		int maxPuts = 500;
		Addressable[] values = new Addressable[maxPuts];
		testPutRandom(map, rand, maxPuts, values);
	}

	@Test
	public void testGetEqualRandomPositionsReplace() {
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		//set seed so that tests are predictable
		Random rand = new Random(42);
		int maxPuts = 500;
		Addressable[] values = new Addressable[maxPuts];
		testPutRandom(map, rand, maxPuts, values);
		rand = new Random(42);
		//test that replacing works
		testPutRandom(map, rand, maxPuts, values);
		assertEquals(maxPuts, map.getSize());
	}

	private void testPutRandom(XYZMap<XYZAddressable> map, Random rand, int maxPuts, Addressable[] values) {
		for (int i = 0; i < maxPuts; i++) {
			values[i] = new Addressable(rand.nextInt(), rand.nextInt(), rand.nextInt(), String.valueOf(i));
			map.put(values[i]);
			//test all previous values
			for (int j = 0; j <= i; j++) {
				Addressable exp = values[j];
				assertEquals(
					"added=" + values[i] + ", wrongValue=" + exp, exp, map.get(exp.getX(), exp.getY(), exp.getZ()));
			}
		}
	}

	@Test
	public void testGetUnique() {
		XYZAddressable value = new Addressable(0, 0, 0, "1");
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		map.put(value);
		for (int x = -20; x < 20; x++) {
			for (int y = -20; y < 20; y++) {
				for (int z = -20; z < 20; z++) {
					if (x != 0 || y != 0 || z != 0) {
						assertNull(map.get(x, y, z));
					}
				}
			}
		}
	}

	@Test
	public void testContains() {
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		TestXYZMap.Addressable[] values = new TestXYZMap.Addressable[500];

		Random rand = new Random(42);
		for (int i = 0; i < values.length; ++i) {
			values[i] = new TestXYZMap.Addressable(rand.nextInt(), rand.nextInt(), rand.nextInt(), String.valueOf(i));
			map.put(values[i]);

			for (int j = 0; j <= i; ++j) {
				assertTrue(map.contains(values[i].getX(), values[i].getY(), values[i].getZ()));
			}
		}
	}

	@Test
	public void testContainsNot() {
		XYZAddressable value = new TestXYZMap.Addressable(0, 0, 0, "1");
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		map.put(value);
		for (int x = -20; x < 20; x++) {
			for (int y = -20; y < 20; y++) {
				for (int z = -20; z < 20; z++) {
					if (x != 0 || y != 0 || z != 0) {
						assertTrue(!map.contains(x, y, z));
					}
				}
			}
		}
	}

	@Test
	public void testIterator() {
		XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10);
		Set<XYZAddressable> allElements = new HashSet<>();
		Random rand = new Random(42);
		int maxPut = 500;
		for (int i = 0; i < maxPut; i++) {
			Addressable newElement = new Addressable(rand.nextInt(), rand.nextInt(), rand.nextInt(), String.valueOf(i));
			map.put(newElement);
			allElements.add(newElement);
		}
		Iterator<XYZAddressable> it = map.iterator();
		while (it.hasNext()) {
			XYZAddressable element = it.next();
			assertThat(allElements, hasItem(element));
			allElements.remove(element);
		}
		assertThat(allElements, empty());
	}

	/**
	 * Simple implementation of Addressable for testing, equal only if id of them is equal
	 */
	private static class Addressable implements XYZAddressable {
		private final int x;
		private final int y;
		private final int z;
		private Object id;

		public Addressable(int x, int y, int z, @Nonnull Object id) {
			this.x = x;
			this.y = y;
			this.z = z;
			this.id = id;
		}

		@Override public int getX() {
			return x;
		}

		@Override public int getY() {
			return y;
		}

		@Override public int getZ() {
			return z;
		}

		@Override public boolean equals(Object o) {
			if (this == o) return true;
			if (o == null || getClass() != o.getClass()) return false;

			Addressable that = (Addressable) o;

			return this.id.equals(that.id);

		}

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


text:
package com.pinterest.secor.common;

import com.pinterest.secor.io.FileWriter;
import com.pinterest.secor.util.FileUtil;
import com.pinterest.secor.util.ReflectionUtil;
import com.pinterest.secor.util.StatsUtil;

import org.apache.hadoop.io.compress.CompressionCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * FileRegistry keeps track of local log files currently being appended to and the associated
 * writers.
 *
 * @author Pawel Garbacki (pawel@pinterest.com)
 */
public class FileRegistry {
    private static final Logger LOG = LoggerFactory.getLogger(FileRegistry.class);

    private final SecorConfig mConfig;
    private HashMap<TopicPartition, HashSet<LogFilePath>> mFiles;
    private HashMap<LogFilePath, FileWriter> mWriters;
    private HashMap<LogFilePath, Long> mCreationTimes;

    public FileRegistry(SecorConfig mConfig) {
        this.mConfig = mConfig;
        mFiles = new HashMap<TopicPartition, HashSet<LogFilePath>>();
        mWriters = new HashMap<LogFilePath, FileWriter>();
        mCreationTimes = new HashMap<LogFilePath, Long>();
    }

    /**
     * Get all topic partitions.
     * @return Collection of all registered topic partitions.
     */
    public Collection<TopicPartition> getTopicPartitions() {
        Set<TopicPartition> topicPartitions = mFiles.keySet();
        if (topicPartitions == null) {
            return new HashSet<TopicPartition>();
        }
        // Return a copy of the collection to prevent the caller from modifying internals.
        return new HashSet<TopicPartition>(topicPartitions);
    }

    /**
     * Get paths in a given topic partition.
     * @param topicPartition The topic partition to retrieve paths for.
     * @return Collection of file paths in the given topic partition.
     */
    public Collection<LogFilePath> getPaths(TopicPartition topicPartition) {
        HashSet<LogFilePath> logFilePaths = mFiles.get(topicPartition);
        if (logFilePaths == null) {
            return new HashSet<LogFilePath>();
        }
        return new HashSet<LogFilePath>(logFilePaths);
    }

    /**
     * Retrieve a writer for a given path or create a new one if it does not exist.
     * @param path The path to retrieve writer for.
     * @param codec Optional compression codec.
     * @return Writer for a given path.
     * @throws Exception
     */
    public FileWriter getOrCreateWriter(LogFilePath path, CompressionCodec codec)
            throws Exception {
        FileWriter writer = mWriters.get(path);
        if (writer == null) {
            // Just in case.
            FileUtil.delete(path.getLogFilePath());
            FileUtil.delete(path.getLogFileCrcPath());
            TopicPartition topicPartition = new TopicPartition(path.getTopic(),
                    path.getKafkaPartition());
            HashSet<LogFilePath> files = mFiles.get(topicPartition);
            if (files == null) {
                files = new HashSet<LogFilePath>();
                mFiles.put(topicPartition, files);
            }
            if (!files.contains(path)) {
                files.add(path);
            }
            writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), path, codec);
            mWriters.put(path, writer);
            mCreationTimes.put(path, System.currentTimeMillis() / 1000L);
            LOG.debug("created writer for path " + path.getLogFilePath());
        }
        return writer;
    }

    /**
     * Delete a given path, the underlying file, and the corresponding writer.
     * @param path The path to delete.
     * @throws IOException
     */
    public void deletePath(LogFilePath path) throws IOException {
        TopicPartition topicPartition = new TopicPartition(path.getTopic(),
                                                           path.getKafkaPartition());
        HashSet<LogFilePath> paths = mFiles.get(topicPartition);
        paths.remove(path);
        if (paths.isEmpty()) {
            mFiles.remove(topicPartition);
            StatsUtil.clearLabel("secor.size." + topicPartition.getTopic() + "." +
                                 topicPartition.getPartition());
            StatsUtil.clearLabel("secor.modification_age_sec." + topicPartition.getTopic() + "." +
                                 topicPartition.getPartition());
        }
        deleteWriter(path);
        FileUtil.delete(path.getLogFilePath());
        FileUtil.delete(path.getLogFileCrcPath());
    }

    /**
     * Delete all paths, files, and writers in a given topic partition.
     * @param topicPartition The topic partition to remove.
     * @throws IOException
     */
    public void deleteTopicPartition(TopicPartition topicPartition) throws IOException {
        HashSet<LogFilePath> paths = mFiles.get(topicPartition);
        if (paths == null) {
            return;
        }
        HashSet<LogFilePath> clonedPaths = (HashSet<LogFilePath>) paths.clone();
        for (LogFilePath path : clonedPaths) {
            deletePath(path);
        }
    }

    /**
     * Delete writer for a given topic partition.  Underlying file is not removed.
     * @param path The path to remove the writer for.
     */
    public void deleteWriter(LogFilePath path) throws IOException {
        FileWriter writer = mWriters.get(path);
        if (writer == null) {
            LOG.warn("No writer found for path " + path.getLogFilePath());
        } else {
            LOG.info("Deleting writer for path " + path.getLogFilePath());
            writer.close();
            mWriters.remove(path);
            mCreationTimes.remove(path);
        }
    }

    /**
     * Delete all writers in a given topic partition.  Underlying files are not removed.
     * @param topicPartition The topic partition to remove the writers for.
     */
    public void deleteWriters(TopicPartition topicPartition) throws IOException {
        HashSet<LogFilePath> paths = mFiles.get(topicPartition);
        if (paths == null) {
            LOG.warn("No paths found for topic " + topicPartition.getTopic() + " partition " +
                     topicPartition.getPartition());
        } else {
            for (LogFilePath path : paths) {
                deleteWriter(path);
            }
        }
    }

    /**
     * Get aggregated size of all files in a given topic partition.
     * @param topicPartition The topic partition to get the size for.
     * @return Aggregated size of files in the topic partition or 0 if the topic partition does
     *     not contain any files.
     * @throws IOException
     */
    public long getSize(TopicPartition topicPartition) throws IOException {
        Collection<LogFilePath> paths = getPaths(topicPartition);
        long result = 0;
        for (LogFilePath path : paths) {
            FileWriter writer = mWriters.get(path);
            if (writer != null) {
                result += writer.getLength();
            }
        }
        StatsUtil.setLabel("secor.size." + topicPartition.getTopic() + "." +
                           topicPartition.getPartition(), Long.toString(result));
        return result;
    }

    /**
     * Get the creation age of the most recently created file in a given topic partition.
     * @param topicPartition The topic partition to get the age of.
     * @return Age of the most recently created file in the topic partition or -1 if the partition
     *     does not contain any files.
     * @throws IOException
     */
    public long getModificationAgeSec(TopicPartition topicPartition) throws IOException {
        long now = System.currentTimeMillis() / 1000L;
        long result = Long.MAX_VALUE;
        Collection<LogFilePath> paths = getPaths(topicPartition);
        for (LogFilePath path : paths) {
            Long creationTime = mCreationTimes.get(path);
            if (creationTime == null) {
                LOG.warn("no creation time found for path " + path);
                creationTime = now;
            }
            long age = now - creationTime;
            if (age < result) {
                result = age;
            }
        }
        if (result == Long.MAX_VALUE) {
            result = -1;
        }
        StatsUtil.setLabel("secor.modification_age_sec." + topicPartition.getTopic() + "." +
            topicPartition.getPartition(), Long.toString(result));
        return result;
    }
}


text:
from google.cloud import discoveryengine_v1beta

async def sample_recommend():
    # Create a client
    client = discoveryengine_v1beta.RecommendationServiceAsyncClient()

    # Initialize request argument(s)
    user_event = discoveryengine_v1beta.UserEvent()
    user_event.event_type = "event_type_value"
    user_event.user_pseudo_id = "user_pseudo_id_value"

    request = discoveryengine_v1beta.RecommendRequest(
        serving_config="serving_config_value",
        user_event=user_event,
    )

    # Make the request
    response = await client.recommend(request=request)

    # Handle the response
    print(response)

# [END discoveryengine_v1beta_generated_RecommendationService_Recommend_async]


text:
NS_ASSUME_NONNULL_BEGIN

@interface DoraemonTimeProfilerPlugin : NSObject<DoraemonPluginProtocol>

@end

NS_ASSUME_NONNULL_END


text:
package org.opentripplanner.standalone;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.onebusaway.gtfs.model.Route;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Sets;

/**
 * The equivalent of a ride in an API response. Information degenerates to Strings and ints here.
 * TODO rename to TransitSegment
 */
public class Segment {

    private static final Logger LOG = LoggerFactory.getLogger(Segment.class);

    public static class SegmentPattern implements Comparable<SegmentPattern> {
        public String patternId;
        public int fromIndex;
        public int toIndex;
        public int nTrips;

        public SegmentPattern(PatternRide patternRide) {
            this.patternId = patternRide.pattern.code;
            this.fromIndex = patternRide.fromIndex;
            this.toIndex = patternRide.toIndex;
            this.nTrips = patternRide.stats.num; // this stats has time window applied
        }

        @Override
        public int compareTo(SegmentPattern other) {
            return other.nTrips - this.nTrips;
        }
    }

    // Use AgencyAndId instead of String to get both since we are now multi-feed
    public String from;
    public String to;
    public int walkTime;
    public int walkDistance;
    public Stats waitStats;
    public TraverseMode mode;
    public String fromName;
    public String toName;
    public Stats rideStats;
    public List<RouteShort> routes;
    public List<SegmentPattern> segmentPatterns = Lists.newArrayList();
    public String startTime;
    public String endTime;

    public Segment(Ride ride) {
        Route route = ride.patternRides.get(0).pattern.route;
        this.from = ride.from.id;
        this.to = ride.to.id;
        this.fromName = ride.from.name;
        this.toName = ride.to.name;
        this.rideStats = ride.rideStats;
        Set<Route> routes = Sets.newHashSet();
        // LOG.info(" Ride fom {} to {}", ride.from.id, ride.to.id);
        for (PatternRide patternRide : ride.patternRides) {
            this.segmentPatterns.add(new SegmentPattern(patternRide));
            routes.add(patternRide.pattern.route);
            // LOG.info("   pattern {} {} from {} to {}", patternRide.pattern.mode,
            // patternRide.pattern.getCode(), patternRide.getFromStop(), patternRide.getToStop());
        }
        Collections.sort(this.segmentPatterns);
        // Note that despite the fact that multiple patterns from different routes will appear in
        // the same ride,
        // in practice all the patterns within a ride will be from the same operator and mode
        // because they all pass
        // through the same stops.
        this.mode = ride.patternRides.get(0).pattern.mode;
        for (PatternRide pr : ride.patternRides) {
            if (pr.pattern.mode != this.mode) {
                LOG.warn("Segment contains patterns using more than one mode.");
            }
        }
        this.walkTime = ride.accessTime;
        this.walkDistance = ride.accessDist;
        this.waitStats = ride.waitStats;
        this.routes = RouteShort.list(routes);
    }

}


text:
import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  // selectedHero: Hero;

  heroes: Hero[];

  getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);
  }

  // onSelect(hero: Hero) {
  //   this.selectedHero = hero;
  // }

  constructor(private heroService: HeroService) {
    this.getHeroes();
   }

  ngOnInit() {
  }

}


text:
package com.github.TKnudsen.DMandML.model.supervised.regression.mixedFeatures;

import com.github.TKnudsen.ComplexDataObject.data.features.mixedData.MixedDataFeatureVector;
import com.github.TKnudsen.DMandML.model.supervised.regression.BasicZeroR;

/**
 *

 * Title: ZeroR
 *

 *
 *

 * Description:
 *

 *
 * @author Christian Ritter
 * @version 1.02
 */
public class ZeroR extends BasicZeroR<MixedDataFeatureVector> {

}


text:
layout: post
title: Körsbär
date: 2015-08-02
---

Mamma och Pappa håller på att renovera stugan. Jag får inte vara där, för nu har tydligen pappa förstört nästan hela innertaket. De säger att det är med flit, men jag vet inte jag.

Så under tiden fick jag hälsa på släkten. Vi började med Morfar i Halmstad. Han hade ett körsbärsträd som jag länsade. Körsbär är jättegott.

![körsbär](/images/2015-07-22.jpg)

Sedan åkte jag till Farmor i Falkenberg. Jag bodde där två nätter och lekte med deras glasbord. Jan-Ove tycker att det är skönt att jag kommer på besök, för då får han en liten paus från Farmor.

![glasbord](/images/2015-07-22-glasbord.jpg)

Sedan fick jag hälsa på de flesta i Gislaved, och så avslutade vi med våffelkalas hos Evald och Barbro. Våfflor kan jag äta nästan hur många som helst, men jag blev lite arg på Ann-Helen som tog telefonen för mig när jag satt i godan ro och tittade på filmer. Hon är ju inte riktigt klok den människan. Men å andra sidan är ju jag väldigt klok, så vi matchar varandra bra.


text:
<readable><title>279728508_6bd7281f3c</title><content>
A boy jumps into water fully clothed .
A boy jumps into water while another watches .
A boys jumps in the water while another boy looks on .
A kid jumps over a small waterful while another boy looks on .
Two boys playing in a lake .
</content></readable>


text:
package income

import (
	"context"
	"fmt"
	"sort"
	"time"

	model "go-common/app/admin/main/growup/model/income"
	"go-common/app/admin/main/growup/service"

	"go-common/library/log"
	"go-common/library/xstr"
)

// UpIncomeList up income list
func (s *Service) UpIncomeList(c context.Context, mids []int64, typ, groupType int, fromTime, toTime, minIncome, maxIncome int64, from, limit int) (upIncome []*model.UpIncome, total int, err error) {
	table := setUpTableByGroup(groupType)
	_, incomeType := getUpInfoByType(typ)
	fromDate := getDateByGroup(groupType, time.Unix(fromTime, 0))
	toDate := getDateByGroup(groupType, time.Unix(toTime, 0))
	typeField := getUpFieldByType(typ)
	query := formatUpQuery(mids, fromDate, toDate, incomeType)
	if maxIncome != 0 || minIncome != 0 {
		query = fmt.Sprintf("%s AND %s >= %d AND %s <= %d", query, incomeType, minIncome, incomeType, maxIncome)
	}
	total, err = s.dao.UpIncomeCount(c, table, query)
	if err != nil {
		log.Error("s.dao.UpIncomeCount error(%v)", err)
		return
	}

	upIncome, err = s.dao.GetUpIncomeBySort(c, table, typeField, incomeType, query, from, limit)
	if err != nil {
		log.Error("s.dao.GetUpIncomeBySort error(%v)", err)
		return
	}
	if len(upIncome) == 0 {
		return
	}
	for _, up := range upIncome {
		mids = append(mids, up.MID)
	}

	nicknames, err := s.dao.ListUpInfo(c, mids)
	if err != nil {
		log.Error("s.dao.ListUpInfo error(%v)", err)
		return
	}

	var breachType []int64
	switch typ {
	case _video:
		breachType = []int64{0}
	case _column:
		breachType = []int64{2}
	case _bgm:
		breachType = []int64{3}
	case _up:
		breachType = []int64{0, 1, 2, 3}
	}
	breachs, err := s.dao.GetAvBreachByMIDs(c, mids, breachType)
	if err != nil {
		log.Error("s.dao.GetAvBreachByMIDs error(%v)", err)
		return
	}
	upIncomeList(upIncome, nicknames, breachs, typ, groupType)
	return
}

func upIncomeList(upIncome []*model.UpIncome, nicknames map[int64]string, breachs []*model.AvBreach, typ, groupType int) {
	midDateBreach := make(map[int64]map[string]int64) // map[mid][date] = money
	for _, b := range breachs {
		dateFormat := formatDateByGroup(b.CDate.Time(), groupType)
		if _, ok := midDateBreach[b.MID]; !ok {
			midDateBreach[b.MID] = make(map[string]int64)
		}
		midDateBreach[b.MID][dateFormat] += b.Money
	}

	for _, up := range upIncome {
		up.Nickname = nicknames[up.MID]
		up.DateFormat = formatDateByGroup(up.Date.Time(), groupType)
		up.ExtraIncome = up.Income - up.BaseIncome
		if _, ok := midDateBreach[up.MID]; ok {
			up.Breach = midDateBreach[up.MID][up.DateFormat]
		}
		switch typ {
		case _video:
			up.Count = up.AvCount
		case _column:
			up.Count = up.ColumnCount
		case _bgm:
			up.Count = up.BgmCount
		case _up:
			up.Count = up.AvCount + up.ColumnCount + up.BgmCount
		}
	}
}

// UpIncomeListExport up income list
func (s *Service) UpIncomeListExport(c context.Context, mids []int64, typ, groupType int, fromTime, toTime, minIncome, maxIncome int64, from, limit int) (res []byte, err error) {
	ups, _, err := s.UpIncomeList(c, mids, typ, groupType, fromTime, toTime, minIncome, maxIncome, from, limit)
	if err != nil {
		log.Error("s.UpIncomeList error(%v)", err)
		return
	}
	records := formatUpIncome(ups)
	res, err = service.FormatCSV(records)
	if err != nil {
		log.Error("FormatCSV error(%v)")
	}
	return
}

// UpIncomeStatis up income statis
func (s *Service) UpIncomeStatis(c context.Context, mids []int64, typ, groupType int, fromTime, toTime int64) (data interface{}, err error) {
	from := getDateByGroup(groupType, time.Unix(fromTime, 0))
	to := getDateByGroup(groupType, time.Unix(toTime, 0))
	if groupType == _groupDay && len(mids) == 0 {
		return s.upStatisDaily(c, typ, from, to)
	}
	return s.upIncomeStatisDate(c, mids, typ, groupType, from, to)
}

func (s *Service) upStatisDaily(c context.Context, typ int, from, to time.Time) (data interface{}, err error) {
	table, _ := getUpInfoByType(typ)
	statis, err := s.dao.GetUpDailyStatis(c, table, from.Format(_layout), to.Format(_layout))
	if err != nil {
		log.Error("s.dao.GetIncomeDailyStatis error(%v)", err)
		return
	}
	dateMap := make(map[string]*model.UpStatisRsp)
	for _, sta := range statis {
		date := sta.Date.Time().Format(_layout)
		if val, ok := dateMap[date]; ok {
			val.Ups += sta.Ups
		} else {
			dateMap[date] = &model.UpStatisRsp{
				Income: sta.Income,
				Ups:    sta.Ups,
			}
		}
	}
	data = calUpStatis(dateMap, 1, from, to)
	return
}

func (s *Service) upIncomeStatisDate(c context.Context, mids []int64, typ, groupType int, from, to time.Time) (data interface{}, err error) {
	table := setUpTableByGroup(groupType)
	_, incomeType := getUpInfoByType(typ)
	query := formatUpQuery(mids, from, to, incomeType)
	upIncome, err := s.GetUpIncome(c, table, incomeType, query)
	if err != nil {
		log.Error("s.GetUpIncome error(%v)", err)
		return
	}

	sort.Slice(upIncome, func(i, j int) bool {
		return upIncome[i].Date < upIncome[j].Date
	})

	dateMap := make(map[string]*model.UpStatisRsp)
	for _, up := range upIncome {
		date := formatDateByGroup(up.Date.Time(), groupType)
		if val, ok := dateMap[date]; ok {
			val.Income += up.Income
			val.Ups++
		} else {
			dateMap[date] = &model.UpStatisRsp{
				Income: up.Income,
				Ups:    1,
			}
		}
	}
	data = calUpStatis(dateMap, groupType, from, to)
	return
}

func calUpStatis(dateMap map[string]*model.UpStatisRsp, groupType int, from, to time.Time) interface{} {
	incomes, ups, xAxis := []string{}, []int{}, []string{}
	to = to.AddDate(0, 0, 1)
	for from.Before(to) {
		dateStr := formatDateByGroup(from, groupType)
		xAxis = append(xAxis, dateStr)
		if val, ok := dateMap[dateStr]; ok {
			incomes = append(incomes, fmt.Sprintf("%.2f", float64(val.Income)/float64(100)))
			ups = append(ups, val.Ups)
		} else {
			incomes = append(incomes, "0")
			ups = append(ups, 0)
		}

		from = addDayByGroup(groupType, from)
	}

	return map[string]interface{}{
		"counts":  ups,
		"incomes": incomes,
		"xaxis":   xAxis,
	}
}

// GetUpIncome get
func (s *Service) GetUpIncome(c context.Context, table, incomeType, query string) (upIncomes []*model.UpIncome, err error) {
	var id int64
	limit := 2000
	for {
		upIncome, err := s.dao.GetUpIncome(c, table, incomeType, query, id, limit)
		if err != nil {
			return upIncomes, err
		}
		upIncomes = append(upIncomes, upIncome...)
		if len(upIncome) < limit {
			break
		}
		id = upIncome[len(upIncome)-1].ID
	}
	return
}

func formatUpQuery(mids []int64, fromTime, toTime time.Time, incomeType string) string {
	query := "date >= '" + fromTime.Format("2006-01-02") + "'"
	query += " AND "
	query += "date <= '" + toTime.Format("2006-01-02") + "'"
	if len(mids) != 0 {
		query += " AND "
		query += "mid in (" + xstr.JoinInts(mids) + ")"
	}
	query += fmt.Sprintf(" AND %s > 0", incomeType)
	return query
}


text:
<?xml version="1.0" ?>
<settings xmlns="http://stanovnik.net/ParallelTimetables"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://stanovnik.net/ParallelTimetables settings.xsd">
    <population_size>2000</population_size>
    <survivor_ratio>0.01</survivor_ratio>
    <rounds>1000</rounds>
    <mutation_probability>0.15</mutation_probability>
    <stats_round_divisor>1</stats_round_divisor>
</settings>


text:
'use strict';

require('./bootstrap-modal');
require('./file-selected');
require('./os-datatype');
require('./popover');
require('./progress-bar');


text:
START_ATF_NAMESPACE
    namespace std
    {
        struct ios_baseVtbl
        {
            void *(WINAPIV *__vecDelDtor)(struct ios_base *_this, unsigned int);
        };
    }; // end namespace std
END_ATF_NAMESPACE


text:
// Type definitions for react-scramble 0.4
// Project: https://github.com/cettoana/react-scramble#readme
// Definitions by: fes300 <https://github.com/fes300>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

import * as React from 'react';

export interface Step {
    /**
     * Action of the step, + as scramble, - as descramble and leave blank to do nothing.
     */
    action: '+' | '-';
    /**
     * Times of action in the step.
     */
    roll?: number;
    /**
     * Change the original text.
     */
    text?: string;
    /**
     * Scramble/descrmble type of the step.
     */
    type?: 'all' | 'random' | 'forward';
}

export interface AnimationControls {
    start: () => void;
    pause: () => void;
}

export interface Props {
    /**
     * Set true to auto start animation after render.
     */
    autoStart?: boolean;
    /**
     * Scramble the text after render.
     */
    preScramble?: boolean;
    /**
     * Speed of scramble per second.
     */
    speed?: 'slow' | 'medium' | 'fast';
    /**
     * Original text.
     */
    text: string;
    /**
     * Scramble steps, a list of Object in Step format.
     */
    steps: Step[];
    /**
     * Using no-break space or not.
     */
    noBreakSpace?: boolean;
    /**
     * Event trigger type when mouse enter.
     */
    mouseEnterTrigger?: 'start' | 'pause' | 'reset' | 'restart';
    /**
     * Event trigger type when mouse leave.
     */
    mouseLeaveTrigger?: 'start' | 'pause' | 'reset' | 'restart';
    /**
     * Method binding callback function.
     */
    bindMethod?: (c: AnimationControls) => void;
}

/**
 * @example
 * ```
 * import React from 'react'
 * import Scramble from 'react-scramble'
 *
 * class App extends React.Component {
 *   render() {
 *    return (
 *      <Scramble
 *        autoStart
 *        text="Scramble me!"
 *        steps={[
 *          {
 *            roll: 10,
 *            action: '+',
 *            type: 'all',
 *          },
 *          {
 *            action: '-',
 *            type: 'forward',
 *          },
 *        ]}
 *      />
 *    )
 *  }
 * }
 * ```
 */
declare const Scramble: React.FC<Props>;

export default Scramble;


text:
var React = require('react');
var TweetList = require('./components/TweetList');
var wordTransformUtil = require('./utils/wordTransformUtil');
var generalUtil = require('./utils/generalUtil');

var printResult = (method, original, transformed) => {
  console.warn(`${method}: {original: "${original}", transformed: "${transformed}"}`);
};

var demoTransformers = () => {
    wordTransformUtil.random((word) => {
      wordTransformUtil.wikiSynonym(word, (transformed) => {
        printResult('wikiSynonym', word, transformed);
      });
    });

    wordTransformUtil.random((word) => {
      wordTransformUtil.synonym(word, (transformed) => {
        printResult('synonym', word, transformed);
      });
    });

    wordTransformUtil.random((word) => {
      wordTransformUtil.antonym(word, (transformed) => {
        printResult('antonym', word, transformed);
      });
    });
};

var App = React.createClass({
  componentDidMount() {
    // Uncomment for a little derpy demo of the word transformations...
    // demoTransformers();
  },

  render() {
    return <TweetList />;
  }
});

React.render(<App />, document.getElementById('app'));


text:
<?php
use yii\helpers\Html;

/* @var $this \yii\web\View */
/* @var $content string */

if (Yii::$app->controller->action->id === 'login') {
    /**
     * Do not use this code in your template. Remove it.
     * Instead, use the code  $this->layout = '//main-login'; in your controller.
     */
    echo $this->render(
        'main-login',
        ['content' => $content]
    );
} else {

    $userModel = Yii::$app->user->identity;
    switch ($userModel->post) {
        case 'developer':
            $post = 'Разрабочик';
            break;
        case 'manager':
            $post = 'Менеджер';
            break;
        case 'director':
            $post = 'Директор';
            break;
        case 'founder':
            $post = 'Учредитель';
            break;
        default;
            $post = 'Ошибка !!!';
    }
    $userData = [
        'id' => $userModel->id,
        'user_name' => $userModel->first_name . ' ' . $userModel->last_name,
        'image' => $userModel->photo,
        'post' => $post,
        'registration_date' => Yii::$app->formatter->asTime($userModel->created_at, "YYYY-MM-DD"),
    ];

    if (class_exists('backend\assets\AppAsset')) {
        backend\assets\AppAsset::register($this);
    } else {
        app\assets\AppAsset::register($this);
    }

    dmstr\web\AdminLteAsset::register($this);

    $directoryAsset = Yii::$app->assetManager->getPublishedUrl('@vendor/almasaeed2010/adminlte/dist');
    ?>
    <?php $this->beginPage() ?>
    <!DOCTYPE html>
    <html lang="<?= Yii::$app->language ?>">
    <head>
        <meta charset="<?= Yii::$app->charset ?>"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?= Html::csrfMetaTags() ?>
        <title><?= Html::encode($this->title) ?></title>
        <?php $this->head() ?>
    </head>
    <body class="hold-transition skin-blue sidebar-mini">
    <?php $this->beginBody() ?>
    <div class="wrapper">

        <?= $this->render(
            'header.php',
            ['directoryAsset' => $directoryAsset, 'userData' => $userData]
        ) ?>

        <?= $this->render(
            'left.php',
            ['directoryAsset' => $directoryAsset, 'userData' => $userData]
        )
        ?>

        <?= $this->render(
            'content.php',
            ['content' => $content, 'directoryAsset' => $directoryAsset]
        ) ?>

    </div>

    <?php $this->endBody() ?>

    <?php
    $this->registerCssFile('/web/css/bootstrap-slider.css');
    $this->registerJsFile('/web/js/bootstrap-slider.js');
    ?>

    </body>
    </html>
    <?php $this->endPage() ?>
<?php } ?>


text:
namespace shapes{
    class Box {
        public:
            double getVolume();
            void setLength(double l);
            void setBredth(double b);
            void setHeight(double h);
            Box operator+(const Box& b);
        private:
            double length;
            double breadth;
            double height;
    };
}
#endif


text:
'use strict';

var Promise  = require('../ext/promise');
var chalk    = require('chalk');
var Task     = require('../models/task');
var fs       = require('fs');
var path     = require('path');

function npmInstall(npm) {
  return Promise.denodeify(npm.commands.install)(['ember-cli']);
}

module.exports = Task.extend({
  init: function() {
    this.npm = this.npm || require('npm');
  },

  run: function(options, updateInfo) {
    var env = options.environment || 'development';

    process.env.EMBER_ENV = process.env.EMBER_ENV || env;

    this.ui.writeLine('');
    this.ui.writeLine(chalk.yellow('A new version of ember-cli is available (' +
                                   updateInfo.newestVersion + ').'));

    var updatePrompt = {
      type: 'confirm',
      name: 'answer',
      message: 'Are you sure you want to update ember-cli?',
      choices: [
        { key: 'y', name: 'Yes, update', value: 'yes' },
        { key: 'n', name: 'No, cancel', value: 'no' }
      ]
    };

    return this.ui.prompt(updatePrompt).then(function(response) {
      if (response.answer === true) {
        return this.runNpmUpdate(updateInfo.newestVersion);
      }
    }.bind(this));
  },

  runNpmUpdate: function(newestVersion) {
    this.ui.startProgress(chalk.green('Updating ember-cli'), chalk.green('.'));

    // first, run `npm install -g ember-cli`
    var npm = this.npm;
    var loadNPM = Promise.denodeify(npm.load);

    var stopProgress = (function() {
      this.ui.stopProgress();
    }.bind(this));

    var reportFailure = (function(reason) {
      this.ui.writeLine('There was an error – possibly a permissions issue. You ' +
                        'may need to manually run ' +
                        chalk.green('npm install -g ember-cli') + '.');
      throw reason;
    }.bind(this));

    var updateDependencies = (function() {
      var pkg = this.project.pkg;
      var packagePath = path.join(this.project.root, 'package.json');

      if (!pkg) {
        this.ui.write('There was an error locating your package.json file.');
        return false;
      }

      pkg.devDependencies['ember-cli'] = newestVersion;
      fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2));
      this.ui.writeLine('');
      this.ui.writeLine(chalk.green('✓ ember-cli was successfully updated!'));

      return this.showEmberInitPrompt();
    }.bind(this));

    return loadNPM({
      loglevel: 'silent',
      global: true
    })
      .then(npmInstall)
      .then(updateDependencies)
      .catch(reportFailure)
      .finally(stopProgress);
  },

  showEmberInitPrompt: function() {
    this.ui.writeLine('To complete the update, you need to run ' +
                      chalk.green('ember init') + ' in your project directory.');

    var initPrompt = {
      type: 'confirm',
      name: 'answer',
      message: 'Would you like to run ' + chalk.green('ember init') + ' now?',
      choices: [
        { key: 'y', name: 'Yes', value: 'yes' },
        { key: 'n', name: 'No', value: 'no' }
      ]
    };

    return this.ui.prompt(initPrompt).then(function(response) {
      if (response.answer === true) {
        var InitCommand = this.commands.Init;

        var initCommand = new InitCommand({
          ui: this.ui,
          analytics: this.analytics,
          tasks: this.tasks,
          project: this.project
        });

        return initCommand.run({}, []);
      }
    }.bind(this));
  }
});


text:
from connection import Connection, create_connection

class CommonDatabase():

	def __init__(self):
		self.client = None

	def set_cassandra_client(self, nodeIP, keyspaceName):
		self.client = create_connection(nodeIP, keyspaceName)

	def close_connection(self):
		self.client.close()


text:
  A simple 2D platformer which you may freely look at and use as a resource or whatever. It is programmed in c# and was made in Unity.

### I don't understand what line ___ does.
  I am currenly working on going back and commenting the code (possibly). I regret not doing it the first time.

 ### I found a bug.
  Post it in the issues. Please note, I probably won't address it anymore.

### I have a suggestion.
  Also post these in the Issues. Please note, I probably won't address it anymore either.

### It's been ___ months since you updated this game. Is it done?
  Yes. I realize it's dirty, but for a first, proper game, I am proud of it.

### So where Is  this project headed?
  It's done. Follow my blog.


text:
package io.advantageous.qbit.meta.swagger;

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

public class Department {
    Set<Employee> employeeList;
    Map<String, String> tags;
    Employee[] employeeArray;
}


text:
import styled from 'styled-components'

const BtnInage = styled.div`
width: 38px;
height: 32px;
opacity: ${props =>
  props.isActive
    ? props.theme.activeIconOpacity
    : props.theme.inactiveIconOpacity};
border-radius: 4px;
margin-left: 6px;
cursor: default;
-webkit-user-select: none;
`

export default BtnInage


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05.Distance_of_the_Stars
{
    class DistanceOfTheStars
    {
        static void Main(string[] args)
        {
            decimal ly = 9.45E12m;
            decimal nearestStar = (4.22m * ly);
            decimal centerOfGalaxy = 26000m * ly;
            decimal diameterGalaxy = 100000m * ly;
            decimal universe = 46500000000m * ly;

            Console.WriteLine(nearestStar.ToString("e2"));
            Console.WriteLine(centerOfGalaxy.ToString("e2"));
            Console.WriteLine(diameterGalaxy.ToString("e2"));
            Console.WriteLine(universe.ToString("e2"));
        }
    }
}


text:
export * from './app-info.component';
export * from './app-info.module';


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>pub editor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../pub/css/normalize.css">
<link rel="stylesheet" href="../pub/css/editor.css">
<link rel="stylesheet" href="../pub/humane-js/flatty.css">

 ✓

 ✍

    <textarea class="editor row"></textarea>


text:
using namespace cv;
using namespace std;

string serialize(Mat input, string filename);

Mat deserialize(stringstream& input, string &filename);

#endif


text:
describe('$mdDateLocale', function() {
  var dateLocale, dateUtil;

  // Fake $locale with made-up days and months.
  var $localeFake = {
    DATETIME_FORMATS: {
      DAY: ['Sundog', 'Mondog', 'Tuesdog', 'Wednesdog', 'Thursdog', 'Fridog', 'Saturdog'],
      MONTH: ['JanZ', 'FebZ', 'MarZ', 'AprZ', 'MayZ', 'JunZ', 'JulZ', 'AugZ', 'SeptZ',
          'OctZ', 'NovZ', 'DecZ'],
      SHORTMONTH: ['JZ', 'FZ', 'MZ', 'AZ', 'MZ', 'JZ', 'JZ', 'AZ', 'SZ', 'OZ', 'NZ', 'DZ']
    }
  };

  beforeEach(module('material.components.datepicker'));

  describe('with default values', function() {
    beforeEach(module(function($provide) {
      $provide.value('$locale', $localeFake);
    }));

    beforeEach(inject(function($mdDateLocale, $$mdDateUtil) {
      dateLocale = $mdDateLocale;
      dateUtil = $$mdDateUtil;
    }));

    it('should expose default days, months, and dates', function() {
      var expected = [undefined, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];

      expect(dateLocale.months).toEqual($localeFake.DATETIME_FORMATS.MONTH);
      expect(dateLocale.shortMonths).toEqual($localeFake.DATETIME_FORMATS.SHORTMONTH);
      expect(dateLocale.days).toEqual($localeFake.DATETIME_FORMATS.DAY);
      expect(dateLocale.shortDays).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']);
      expect(dateLocale.dates.length).toEqual(expected.length);
    });

    it('should have a default date formatter', function() {
      var date = new Date(2014, 2, 25);
      var dateStr = dateLocale.formatDate(date);
      expect(dateStr).toEqual(jasmine.any(String));
      expect(dateStr).toBeTruthy();
    });

    it('should have a default date parser', function() {
      var dateStr = '2014-03-25';
      expect(dateLocale.parseDate(dateStr)).toEqual(jasmine.any(Date));
    });

    it('should have default date completion detection', function() {
      // Valid dates.
      expect(dateLocale.isDateComplete('04/05/15')).toBe(true);
      expect(dateLocale.isDateComplete('04/05/2015')).toBe(true);
      expect(dateLocale.isDateComplete('4/5/2015')).toBe(true);
      expect(dateLocale.isDateComplete('2015 04 05')).toBe(true);
      expect(dateLocale.isDateComplete('2015-04-05')).toBe(true);
      expect(dateLocale.isDateComplete('2015,04,05')).toBe(true);
      expect(dateLocale.isDateComplete('2015.04.05')).toBe(true);
      expect(dateLocale.isDateComplete('April 5, 2015')).toBe(true);
      expect(dateLocale.isDateComplete('April 5 2015')).toBe(true);
      expect(dateLocale.isDateComplete('Apr 5, 2015')).toBe(true);
      expect(dateLocale.isDateComplete('Apr 5 2015')).toBe(true);
      expect(dateLocale.isDateComplete('2015 Apr 5')).toBe(true);

      // Invalid dates.
      expect(dateLocale.isDateComplete('5')).toBe(false);
      expect(dateLocale.isDateComplete('4/5')).toBe(false);
      expect(dateLocale.isDateComplete('04/05')).toBe(false);
      expect(dateLocale.isDateComplete('Apr 5')).toBe(false);
      expect(dateLocale.isDateComplete('April 5')).toBe(false);
      expect(dateLocale.isDateComplete('April 5 200000')).toBe(false);
    });
  });

  describe('with custom values', function() {
    var fakeMonths = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];
    var fakeshortMonths = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'j', 'l'];
    var fakeDays = ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7'];
    var fakeShortDays = ['1', '2', '3', '4', '5', '6', '7'];
    var fakeDates = [undefined, 'X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'X9', 'X10', 'X11',
        'X12', 'X13', 'X14', 'X15', 'X16', 'X17', 'X18', 'X19', 'X20', 'X21', 'X22', 'X23', 'X24',
        'X25', 'X26', 'X27', 'X28', 'X29', 'X30', 'X31'];

    beforeEach(module(function($mdDateLocaleProvider) {
      $mdDateLocaleProvider.months = fakeMonths;
      $mdDateLocaleProvider.shortMonths = fakeshortMonths;
      $mdDateLocaleProvider.days = fakeDays;
      $mdDateLocaleProvider.shortDays = fakeShortDays;
      $mdDateLocaleProvider.dates = fakeDates;
      $mdDateLocaleProvider.formatDate = function() {
        return 'Your birthday!';
      };
      $mdDateLocaleProvider.parseDate = function() {
        return new Date(1969, 6, 16);
      };
      $mdDateLocaleProvider.isDateComplete = function(dateString) {
        return dateString === 'The One True Date';
      };
    }));

    beforeEach(inject(function($mdDateLocale, $$mdDateUtil) {
      dateLocale = $mdDateLocale;
      dateUtil = $$mdDateUtil;
    }));

    it('should expose custom settings', function() {
      expect(dateLocale.months).toEqual(fakeMonths);
      expect(dateLocale.shortMonths).toEqual(fakeshortMonths);
      expect(dateLocale.days).toEqual(fakeDays);
      expect(dateLocale.shortDays).toEqual(fakeShortDays);
      expect(dateLocale.dates).toEqual(fakeDates);
      expect(dateLocale.formatDate(new Date())).toEqual('Your birthday!');
      expect(dateLocale.parseDate('2020-01-20')).toEqual(new Date(1969, 6, 16));
      expect(dateLocale.parseDate('2020-01-20')).toEqual(new Date(1969, 6, 16));
      expect(dateLocale.isDateComplete('The One True Date')).toBe(true);
      expect(dateLocale.isDateComplete('Anything Else')).toBe(false);
    });
  });
});


text:
package com.griddynamics.workshop.rx.todo;

import rx.Observable;
import rx.Subscriber;

import static com.griddynamics.workshop.rx.Utils.print;

/**
 * @author Max Myslyvtsev
 * @since 11/23/15
 */
public class _04_ErrorHandling {

    public static void main(String[] args) {

        Observable<String> unhandled = null; // TODO: create an observable that emits "item1" and then error with message "Oops"

        Observable<String> defaulted = null; // TODO: change unhandled observable to emit default item on error: "default"

        Observable<String> backup = null; // TODO: create backup observable that emits "backup1", "backup2"
        Observable<String> resumed = null; // TODO: change unhandled observable to emit items from backup observable on error

        Observable<String> mapped = null; // TODO: change unhandled observable to append " Mapped" suffix to exception message on error

        print("unhandled", unhandled);
        print("defaulted", defaulted);
        print("backup", backup);
        print("resumed", resumed);
        print("mapped", mapped);
    }
}


text:
package org.zalando.nakadi.service.converter;

import com.google.common.annotations.VisibleForTesting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zalando.nakadi.cache.EventTypeCache;
import org.zalando.nakadi.domain.NakadiCursor;
import org.zalando.nakadi.exceptions.runtime.InternalNakadiException;
import org.zalando.nakadi.exceptions.runtime.InvalidCursorException;
import org.zalando.nakadi.exceptions.runtime.NoSuchEventTypeException;
import org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException;
import org.zalando.nakadi.service.CursorConverter;
import org.zalando.nakadi.service.timeline.TimelineService;
import org.zalando.nakadi.view.Cursor;
import org.zalando.nakadi.view.SubscriptionCursor;
import org.zalando.nakadi.view.SubscriptionCursorWithoutToken;

import java.util.Collection;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@Service
public class CursorConverterImpl implements CursorConverter {

    private final Map<Version, VersionedConverter> converters = new EnumMap<>(Version.class);

    @Autowired
    public CursorConverterImpl(final EventTypeCache eventTypeCache, final TimelineService timelineService) {
        registerConverter(new VersionOneConverter(eventTypeCache));
        registerConverter(new VersionZeroConverter(timelineService));
    }

    private void registerConverter(final VersionedConverter converter) {
        this.converters.put(converter.getVersion(), converter);
    }

    @Override
    public NakadiCursor convert(final SubscriptionCursorWithoutToken cursor)
            throws InternalNakadiException, NoSuchEventTypeException, ServiceTemporarilyUnavailableException,
            InvalidCursorException {
        return convert(cursor.getEventType(), cursor);
    }

    @Override
    public List<NakadiCursor> convert(final Collection<SubscriptionCursorWithoutToken> cursors)
            throws InternalNakadiException, NoSuchEventTypeException, ServiceTemporarilyUnavailableException,
            InvalidCursorException {
        final LinkedHashMap<SubscriptionCursorWithoutToken, AtomicReference<NakadiCursor>> orderingMap =
                new LinkedHashMap<>();
        cursors.forEach(item -> orderingMap.put(item, new AtomicReference<>(null)));

        final Map<Version, List<SubscriptionCursorWithoutToken>> mappedByVersions = cursors.stream()
                .collect(Collectors.groupingBy(c -> guessVersion(c.getOffset())));
        for (final Map.Entry<Version, List<SubscriptionCursorWithoutToken>> entry : mappedByVersions.entrySet()) {
            final List<NakadiCursor> result = converters.get(entry.getKey()).convertBatched(entry.getValue());
            IntStream.range(0, entry.getValue().size())
                    .forEach(idx -> orderingMap.get(entry.getValue().get(idx)).set(result.get(idx)));
        }
        return orderingMap.values().stream().map(AtomicReference::get).collect(Collectors.toList());
    }

    @Override
    public NakadiCursor convert(final String eventTypeStr, final Cursor cursor)
            throws InternalNakadiException, NoSuchEventTypeException, InvalidCursorException,
            ServiceTemporarilyUnavailableException {
        return converters.get(guessVersion(cursor.getOffset())).convert(eventTypeStr, cursor);
    }

    /**
     * Method tries to get version of cursor. If version can not be restored, than {@link Version#ZERO}
     * will be returned
     *
     * @param offset Offset to guess version from
     * @return Version of offset.
     */
    @VisibleForTesting
    static Version guessVersion(final String offset) {
        if (offset.length() < (CursorConverter.VERSION_LENGTH)) {
            return CursorConverter.Version.ZERO;
        }
        final String versionStr = offset.substring(0, CursorConverter.VERSION_LENGTH);
        final Optional<Version> version =
                Stream.of(CursorConverter.Version.values())
                        .filter(v -> v.code.equals(versionStr))
                        .findAny();
        return version.orElse(CursorConverter.Version.ZERO);
    }

    public Cursor convert(final NakadiCursor nakadiCursor) {
        return new Cursor(
                nakadiCursor.getPartition(),
                converters.get(CursorConverter.Version.ONE).formatOffset(nakadiCursor));
    }

    public SubscriptionCursor convert(final NakadiCursor position, final String token) {
        final Cursor oldCursor = convert(position);
        return new SubscriptionCursor(
                oldCursor.getPartition(), oldCursor.getOffset(), position.getEventType(), token);
    }

    @Override
    public SubscriptionCursorWithoutToken convertToNoToken(final NakadiCursor position) {
        final Cursor oldCursor = convert(position);
        return new SubscriptionCursorWithoutToken(
                position.getEventType(), oldCursor.getPartition(), oldCursor.getOffset());
    }
}


text:
var logger = require('log4js').getLogger()
var muser = require('../db/mod_user')
var responder = require('../util/responder')

module.exports = function(req, res) {

  var un = req.param('userId')
  var phone = req.param('phone')

  muser.set(un, {'phone': phone}, onPhoneSet(res))

}

var onPhoneSet = function(res) {
  return function(err, result) {

    if (err) {
      logger.error('Error setting phone number in mongo')
      responder.sendInternal(res)
      return
    }

    responder.sendOk(res, {'message': 'Phone number set'})

  }
}


text:
@interface User : NSObject <NSCoding>

@property (nonatomic) NSString *idNumber;
@property (nonatomic) NSString *userName;
@property (nonatomic) NSString *fullName;
@property (nonatomic) NSURL *profilePictureURL;
@property (nonatomic) UIImage *profilePicture;

- (instancetype)initWithDictionary:(NSDictionary *)userDictionary;

@end


text:
<?php

namespace common\modules\document\models;

/**
 * This is the model class for table "{{%document_tag}}".
 *
 * @property integer $document_id
 * @property integer $tag_id
 */
class DocumentTag extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%document_tag}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['document_id', 'tag_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'document_id' => '内容',
            'tag_id' => '标签',
        ];
    }
}


text:
//ready method

$(function() {
    /*
    Variables
    */
    var formContact = $('#formContact');

    /*
    ste default values
    */
    $.extend($.validator.messages, {
        required: 'Este campo es obligatorio',
        email: 'Ingresa un correo valido',
        url:'Ingresa una url valida',
        minlength: 'Ingresa al menos {0} caracteres'
    });

    /*
    Apply validation plugin
    */

    formContact.validate();

    // $('#formContact').validate();
});


text:
title: "VHF Maroon Radio"
author: Greg
layout: post
permalink: /2017/08/vhf-maroon-radio/
date: 2017-08-30 16:01:29 -0400
comments: True
licence: Creative Commons
categories:
  - Technology
tags:
  - technology
  - machine learning
  - sailing
---

My partner and I are leaving on a [year long sailing trip](https://www.youtube.com/SVCatsaway) this weekend. One of the last things on our shopping list is a spare handheld marine VHF radio. This spare radio will allow us to communicate with other boats if our main radio is incapacitated.

Canadian Tire's website returned a few entries with the query "VHF Marine Radio" so I headed off to my local store.

![Canadian Tire VHF Marine Radio Search](/wp-content/uploads/2017/08/Canadian Tire VHF Marine Radio Search.png){:height="75%" width="75%"}

When I arrived however I discovered that none of Canadian Tire's radios were *VHF Marine*, they were all *Walkie Talkies*. This is problematic as Walkie Talkies can not communicate with VHF Marine Radios. Canadian Tire... more like Canadian Liar... amirite?

This may seem like an inconsequential mistake until you consider when these radios are likely to be used. In an emergency on the water; Walkie Talkies are as useless as a knitted life raft. Ideally humans will check their equipment before they use them, however these radios normally come as a pair. It would be easy to be lulled into a false sense of security after a successful self radio check.

***Never attribute to malice that which is adequately explained by stupidity - Hanlon's razor***

It was unlikely that Canadian Tire was trying to trick people into floating powerless boats over waterfalls.

![Fat Cat Rowing A Boat](/wp-content/uploads/2017/08/Fat Cat Rowing A Boat.gif){:height="75%" width="75%"}

It far more likely that users of their website inadvertently trained Canadian Tire's search algorithms into believing that "VHF Marine Radio" was a synonym for "Walkie Talkie". A simple mistake for a gullible algorithm. Nowadays machine learning is relatively easy, machine learning useful things is more difficult. We're likely to see more mistakes like this as algorithms penetrate our lives. I just hope the machines are smarter before they attempt their inevitable coup d'etat.


text:
typedef void (^DMResponseDataCallback)(NSData* data);

@interface DMResponse : DMResource

@property (nonatomic, strong)NSHTTPURLResponse* response;

- (id)initWith:(NSHTTPURLResponse*)response;

- (DMResponse*)data:(DMResponseDataCallback)data;

- (DMResponse*)end:(DMCallback)callable;

- (DMResponse*)error:(DMErrorCallback)callback;

- (NSInteger)statusCode;

- (long long)expectedContentLength;

@end


text:
package org.gluu.oxauth.model.config;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.gluu.oxauth.model.configuration.Configuration;

/**
 * @author Yuriy Zabrovarnyy
 * @author Javier Rojas Blum
 * @version 0.9 February 12, 2015
 */
@XmlRootElement(name = "static")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonIgnoreProperties(ignoreUnknown = true)
public class StaticConfiguration implements Configuration {

    @XmlElement(name = "base-dn")
    private BaseDnConfiguration baseDn;

    public BaseDnConfiguration getBaseDn() {
        return baseDn;
    }

    public void setBaseDn(BaseDnConfiguration p_baseDn) {
        baseDn = p_baseDn;
    }
}


text:
package org.mycontroller.standalone.db.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import org.mycontroller.standalone.AppProperties.RESOURCE_TYPE;
import org.mycontroller.standalone.api.jaxrs.model.Query;
import org.mycontroller.standalone.api.jaxrs.model.QueryResponse;
import org.mycontroller.standalone.db.tables.UidTag;
import org.mycontroller.standalone.exceptions.McDatabaseException;

import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Jeeva Kandasamy (jkandasa)
 * @since 0.0.1
 */
@Slf4j
public class UidTagDaoImpl extends BaseAbstractDaoImpl<UidTag, Integer> implements UidTagDao {

    public UidTagDaoImpl(ConnectionSource connectionSource) throws SQLException {
        super(connectionSource, UidTag.class);
    }

    @Override
    public UidTag get(UidTag uidTag) {
        return super.getById(uidTag.getId());
    }

    @Override
    public List<UidTag> getAllByUid(List<String> uids) {
        return super.getAll(UidTag.KEY_UID, uids);
    }

    @Override
    public void delete(RESOURCE_TYPE resourceType, Integer resourceId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(UidTag.KEY_RESOURCE_TYPE, resourceType);
        map.put(UidTag.KEY_RESOURCE_ID, resourceId);
        super.delete(map);
    }

    @Override
    public QueryResponse getAll(Query query) {
        try {
            query.setIdColumn(UidTag.KEY_ID);
            return this.getQueryResponse(query);
        } catch (SQLException ex) {
            _logger.error("unable to run query:[{}]", query, ex);
            throw new McDatabaseException(ex);
        }
    }

    @Override
    public UidTag get(RESOURCE_TYPE resourceType, Integer resourceId) {
        QueryBuilder<UidTag, Integer> queryBuilder = getDao().queryBuilder();
        try {
            queryBuilder.where().eq(UidTag.KEY_RESOURCE_TYPE, resourceType).and()
                    .eq(UidTag.KEY_RESOURCE_ID, resourceId);
            List<UidTag> uidTags = queryBuilder.query();
            if (uidTags != null && !uidTags.isEmpty()) {
                return uidTags.get(0);
            }
        } catch (SQLException ex) {
            _logger.error("Error, ", ex);
            throw new McDatabaseException(ex);
        }
        return null;
    }

    @Override
    public UidTag getByUid(String uid) {
        List<UidTag> uidTags = super.getAll(UidTag.KEY_UID, uid);
        if (uidTags != null && !uidTags.isEmpty()) {
            return uidTags.get(0);
        }
        return null;
    }

    @Override
    public void deleteByUid(String uid) {
        super.delete(UidTag.KEY_UID, uid);
    }

    @Override
    public List<UidTag> getAll(List<Integer> ids) {
        return super.getAll(UidTag.KEY_ID, ids);
    }

}


text:
using Xamarin.Forms;

namespace Hanselman.Effects
{
    public class TabbedPageNoShiftEffect : RoutingEffect
    {
        public TabbedPageNoShiftEffect() : base($"Hanselman.{nameof(TabbedPageNoShiftEffect)}")
        {
        }
    }
}


text:
using System;
using UIKit;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Foundation;
using CoreGraphics;

namespace XamarinTable
{
	public class MainViewController : UIViewController
	{
		public List<UIImage> Images;

		public MainViewController ()
			:base(null, null)
		{
		}

		public async override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			Images = new List<UIImage> ();
			var table = new UITableView (new CGRect (0, 70, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height - 70));
			table.Source = new MyTableSource (this);
			Add (table);

			var btn = new UIButton (new CGRect (0, 20, 80, 50));
			btn.SetTitle ("Reload", UIControlState.Normal);
			btn.TouchUpInside += async (sender, e) => await DownloadImages(table);
			Add (btn);

			await DownloadImages (table);

		}

		private async Task DownloadImages(UITableView table)
		{
			var client = new HttpClient ();
			Images.Clear ();

			for (int i = 0; i < 100; i++) {
				var bytes = await client.GetByteArrayAsync ("http://lorempixel.com/50/50/");
				Images.Add(UIImage.LoadFromData(NSData.FromArray(bytes)));
				table.ReloadData ();
			}
		}
	}

	public class MyTableSource : UITableViewSource
	{
		private readonly MainViewController _vc;

		public MyTableSource(MainViewController vc)
		{
			_vc = vc;
		}

		public override nint RowsInSection (UITableView tableview, nint section)
		{
			return _vc.Images.Count;
		}

		public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
		{
			var cell = new UITableViewCell (UITableViewCellStyle.Default, "cell");
			cell.ImageView.Image = _vc.Images[(int)indexPath.Item];
			return cell;
		}

	}
}


text:
function wrap_selection(e,o,c,f)
{
	// Code for IE
	if (document.selection)
	{
		e.focus();
		var t = document.selection.createRange();
		t.text = o + ( f ? f(t.text) : t.text) + c;
		return;
	}

	// Code for Webkit/Firefox
	var len = e.value.length;
	var start = e.selectionStart;
	var end = e.selectionEnd;

	var scrollTop = e.scrollTop;
	var scrollLeft = e.scrollLeft;

	var t = e.value.substring(start, end);
	e.value =  e.value.substring(0,start) + o + ( f ? f(t) : t) + c + e.value.substring(end,len);

	e.scrollTop = scrollTop;
	e.scrollLeft = scrollLeft;
}

// Textarea element, menu element, menu items
function create_menu_item(p,m,f)
{
	// Create a new menu item
	var b = document.createElement('button');
	b.id = p.id + f.id;
	b.className = f.id;
	b.title = f.label;

	// Add it to the menu bar
	m.appendChild(b);

	// Register the callback
	kb.on(b,'click',function(e){ wrap_selection(p,f.open,f.close,f.callback); });
}

// Element, menu items, tabs
function createTextEditor(el,f,t,p)
{
	// Activate preview field (if found)
	if(p=$(el.id+'preview'))
	{
		// Local preview function
		var update_preview = function()
		{
			// @todo: This needs work to show ALL HTML elements inside <code> blocks!
			p.innerHTML = el.value.replace(/<(\/?)script/g, '<$1script').replace(/\n\n+/g,"\n\n\n").replace(/([^>])\n/g,'$1\n<br>');
		}

		// Each time they type something update it
		kb.on(el,'keyup',function(e){ update_preview(); });

		// Update preview as soon as loaded
		update_preview();
	}

	if(t)
	{
		// Also allow tabbing
		kb.on(el,'keydown',function(e)
		{
			if (e && e.keyCode == 9)// && (e.altKey || e.metaKey || e.ctrlKey)) if you want a combo...
			{
				kb.stop(e);
				wrap_selection(el, "\t", '', function(t) { return t.replace(/\n/g,"\n\t") });
			}
		});
	}

	// Create a new menu DOM element
	var m = document.createElement('div');

	// Create menu class
	m.className = "texteditormenu";

	// Add the menu to the top of the textarea
	el.parentNode.insertBefore(m,el);

	// Create the buttons
	for (var i=0;i<f.length;i++){ create_menu_item(el,m,f[i]); }
}


text:
package io.lineage;

/**
 * Boolean gene
 *
 */
public class BooleanGene extends Gene<Boolean>
{

    public BooleanGene(final boolean value)
    {
        this.allele = value;
    }

    @Override
    public void mutate()
    {
        // TODO Auto-generated method stub

    }

    @Override
    protected Gene<Boolean> clone() throws CloneNotSupportedException
    {
        return new BooleanGene(allele);
    }
}


text:
These are VM based tests for core u-root functionality such as:

* retrieving and kexec'ing a Linux kernel,
* DHCP client tests,
* uinit (user init), and
* running unit tests requiring root privileges.

All tests are in the integration/ directory. Within that, there are a
few subdirectories:

* generic-tests/ : most tests can be put under this.
* gotests/ : this is for Go unit tests that can be run inside the VM.
* testcmd/ : this contains custom uinits for tests.
* testdata/ : this contains any extra files for tests.

To learn more about how these tests work under the hood, see the next section,
otherwise jump ahead to the sections on how to write and run these tests.

## VM Testing Infrastructure

Our VM testing infrastructure starts a QEMU virtual machine that boots with
our given kernel and initramfs, and runs the uinit or commands that we want to
test.

Testing mainly relies on 2 packages: [pkg/vmtest](/pkg/vmtest) and
[pkg/qemu](/pkg/qemu).

pkg/vmtest takes in integration test options, and given those and the
environment variables, uses pkg/qemu to start a QEMU VM with the correct command
line and configuration.

Files that need to be shared with the VM are written to a temp dir which is
exposed as a Plan 9 (9p) filesystem in the VM. This includes the kernel and
initramfs being used for the VM.

The test architecture, kernel and QEMU binary are set using environment
variables.

The initramfs can come from the following sources:
* User overridden: when the `UROOT_INITRAMFS` environment variable is used to
  override the initramfs. The user is responsible for ensuring the initramfs
  contains the correct binaries.
* Custom u-root opts: define u-root opts in the test itself (eg. custom uinit).
  The testing setup will generate an initramfs with those options.
* Default: provide the set of commands to be tested. The commands are written to
  an elvish script in the shared dir. The testing setup will generate a generic
  initramfs that mounts the shared 9p filesystem as '/testdata', and then finds
  and runs the elvish script.

To check for the correct behavior, we use the go expect package to find
expected output in QEMU's serial output within a given timeout.

## Running Tests

These tests only run on Linux on amd64 and arm.

1. **Set Environment Variables**

-   `UROOT_QEMU` points to a QEMU binary and args, e.g.

```sh
export UROOT_QEMU="$HOME/bin/qemu-system-x86_64 -enable-kvm"
```

-   `UROOT_KERNEL` points to a Linux kernel binary, e.g.

```sh
export UROOT_KERNEL="$HOME/linux/arch/x86/boot/bzImage"
```
-   (optional) `UROOT_INITRAMFS` is a custom initramfs to use for all tests.
    This will override all other initramfs options defined by the tests.

-   (optional) `UROOT_TESTARCH` (defaults to host architecture) is the
    architecture to test. Only `arm` and `amd64` are supported.

-   (optional) `UROOT_QEMU_TIMEOUT_X` (defaults to 1.0) can be used to multiply
    the timeouts for each test in case QEMU on your machine is slower. For
    example, if you cannot turn on `-enable-kvm`, use `UROOT_QEMU_TIMEOUT_X=2`
    as our test automation does.

Our automated CI uses Dockerfiles to build a kernel and QEMU and set these
environment variables. You can see the Dockerfile and the config file used to
build the kernel for each supported architecture [here](/.circleci/images).

If you don't want to deal with version differences in QEMU and the kernel, you
can use the docker image get both. Inside /.circleci/images/test-image-amd64 (or
whatever arch you have), run

```
cd test-image-$GOARCH
docker build . -t uroottest/test-image-$GOARCH:$VERSION
docker run uroottest/test-image-$GOARCH:$VERSION
docker container list -a
```

Then look for the container id for your newly built container, and

```
docker cp $CONTAINER_ID:bzImage <target>
docker cp $CONTAINER_ID:qemu-system-x86_64 <target>
docker cp $CONTAINER_ID:pc-bios <target>
```

The pc bios needs to be passed into qemu with the -L flag for this built version
of qemu.

2. **Run Tests**

Recall that there are 2 subdirectories with tests, generic-tests/ and gotests/.
To run tests in both directories, run:

```sh
go test [-v] ./...
```

The verbose flag is useful to see the QEMU command line being used and the full
serial output. It is also useful to see which tests are being skipped and why
(particularly for ARM, where many tests are currently skipped).

Unless you want to wait a long time for all tests to complete, run just the
specific test you want from inside the correct directory e.g.

```sh
cd generic-tests/
go test [-v] -test.run=TestDhclient
```

*To avoid having to do this every time, check the instructions for the RUNLOCAL
script.*

## Kernel Code Coverage

For kernel code coverage, build your kernel with the CONFIGs here:
https://www.kernel.org/doc/html/v4.14/dev-tools/gcov.html

With these configs enabled, a folder containing gcda files (raw coverage data)
will appear in the VM /sys/kernel/debug/gcov/. The u-root test infra will
automatically tar this directory and save to:

```
u-root/integration/coverage/{{testname}}/{{instance}}/kernel_coverage.tar
```

## Writing a New Test

To write a new test, first decide which of the options from the previous
section best fit your case (custom initramfs, custom uinit, test commands).

`vmtest.QEMUTest` is the function that starts the QEMU VM and returns the VM
struct. There, provide the test options for your use case.

The VM struct returned by `vmtest.QEMUTest` represents a running QEMU virtual
machine. Use its family of Expect methods to check for the correct result.


text:
define([
    '../../bishop'
], function (
    bishop
) {
    "use strict";

    // To play around in console
    window.bishop = bishop;

    bishop.init();
    bishop.focus(document.querySelector('.focused'));
});


text:
package nam.model.application;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.aries.util.NameUtil;

import nam.model.Application;
import nam.model.Project;
import nam.model.util.ApplicationUtil;
import nam.ui.design.AbstractDomainElementWizard;
import nam.ui.design.SelectionContext;

@SessionScoped
@Named("applicationWizard")
@SuppressWarnings("serial")
public class ApplicationWizard extends AbstractDomainElementWizard<Application> implements Serializable {

	@Inject
	private ApplicationDataManager applicationDataManager;

	@Inject
	private ApplicationPageManager applicationPageManager;

	@Inject
	private ApplicationEventManager applicationEventManager;

	@Inject
	private SelectionContext selectionContext;

	@Override
	public String getName() {
		return "Application";
	}

	@Override
	public String getUrlContext() {
		return applicationPageManager.getApplicationWizardPage();
	}

	@Override
	public void initialize(Application application) {
		setOrigin(getSelectionContext().getUrl());
		assignPages(applicationPageManager.getSections());
		super.initialize(application);
		//configurationTreeManager.refresh(project);
		//configurationTreeManager.setRerenderList("applicationConfigPage");
		//configurationTreeManager.initialize(createConfigurationSelectListener());
	}

//	Handler<Object> createConfigurationSelectListener() {
//		return new Handler<Object>() {
//			public void handle(Object artifact) {
//				if (artifact instanceof Configuration) {
//					Configuration configuration = (Configuration) artifact;
//					Application application = getInstance();
//					application.setConfiguration(configuration);
//				}
//			}
//		};
//	}

//	@Override
//	public String getRefreshEvent() {
//		return "nam.applicationsChanged";
//	}

	@Override
	public boolean isBackEnabled() {
		return super.isBackEnabled();
	}

	@Override
	public boolean isNextEnabled() {
		return super.isNextEnabled();
	}

	@Override
	public boolean isFinishEnabled() {
		return super.isFinishEnabled();
	}

	@Override
	public String refresh() {
		String url = super.showPage();
		selectionContext.setUrl(url);
		applicationPageManager.updateState();
		return url;
	}

	@Override
	public String first() {
		String url = super.first();
		applicationPageManager.updateState();
		return url;
	}

	@Override
	public String back() {
		String url = super.back();
		applicationPageManager.updateState();
		return url;
	}

	@Override
	public String next() {
		String url = super.next();
		applicationPageManager.updateState();
		return url;
	}

	@Override
	//TODO Make this private - should only happen once per request - no EL should call this
	public boolean isValid() {
		return super.isValid();
	}

	@Override
	public String finish() {
		Application application = getInstance();
		applicationDataManager.saveApplication(application);
		applicationEventManager.fireSavedEvent(application);
		String url = selectionContext.popOrigin();
		return url;
	}

	@Override
	public String cancel() {
		Application application = getInstance();
		//TODO take this out soon
		if (application == null)
			application = new Application();
		applicationEventManager.fireCancelledEvent(application);
		String url = selectionContext.popOrigin();
		return url;
	}

	public String populateDefaultValues() {
		Application application = selectionContext.getSelection("application");
		String name = application.getName();
		if (StringUtils.isEmpty(name)) {
			display = getFromSession("display");
			display.setModule("applicationWizard");
			display.error("Application name must be specified");
			return null;
		}

		Project project = selectionContext.getSelection("project");

		String nameCapped = NameUtil.capName(name);
		String nameUncapped = NameUtil.uncapName(name);

		application.setName(nameUncapped);
		application.setLabel(nameCapped);
		application.setArtifactId(nameUncapped);
		application.setGroupId(project.getDomain());
		application.setNamespace(project.getNamespace()+"/"+nameUncapped);
		application.setContextRoot("/"+nameUncapped);
		application.setDescription("This is an Application named \""+nameUncapped+"\"");
		application.setVersion("0.0.1-SNAPSHOT");
		return getUrl();
	}

}


text:
package com.compomics.mascotdatfile.util.mascot.enumeration;

import org.apache.log4j.Logger;

/**
 * Enumaration for the distinct MascotDatfile types.
 */
public enum MascotDatfileType {
    /*
     * Types a MascotDatfile implementation that works completely in memory.
     * As a rough measure, a 10-fold of the file size will be required as virtual memory.
     * ex: A 100MB Mascot result file requires 1000 MB virtual memory.
     *
     * If memory is no issue, use this type as it is most fast.
     */
    MEMORY("In-memory parsing"),
    /**
     * Types a MascotDatfile implementation that is fully indexed.
     * As a rough measure, half of the file size will be required as virtual memory.
     * ex: A 100MB Mascot result file requires 50MB virtual memory.
     *
     * Even though the indexing is far slower, if memory is an issue, use this type of MascotDatfile.
     */
    INDEX("Index-based parsing");

    /**
     * A name for the Enum.
     */
    private String iName;

    /**
     * Constructor for the enum.
     * @param aName String name for the enum.
     */
    MascotDatfileType(String aName) {
        iName = aName;
    }

    /**
     * Returns a description for the enum.
     * @return String describing the enum.
     */
    public String toString() {
        return iName;
    }
}


text:
package com.aggrepoint.utils;

@FunctionalInterface
public interface OrderSetter<T> {
	void apply(T t, Integer v);
}


text:
<!DOCTYPE html>

<title></title>

Presentation Window Showed on Wireless Display

receiver display init


text:
import assert from "assert";
import { inherits as inherits$0 } from "util";
import Cipher from "./cipher";
import DES from "./des";
'use strict';
var inherits = { inherits: inherits$0 }.inherits;
function EDEState(type, key) {
    assert.equal(key.length, 24, 'Invalid key length');
    var k1 = key.slice(0, 8);
    var k2 = key.slice(8, 16);
    var k3 = key.slice(16, 24);
    if (type === 'encrypt') {
        this.ciphers = [
            DES.create({ type: 'encrypt', key: k1 }),
            DES.create({ type: 'decrypt', key: k2 }),
            DES.create({ type: 'encrypt', key: k3 })
        ];
    }
    else {
        this.ciphers = [
            DES.create({ type: 'decrypt', key: k3 }),
            DES.create({ type: 'encrypt', key: k2 }),
            DES.create({ type: 'decrypt', key: k1 })
        ];
    }
}
function EDE(options) {
    Cipher.call(this, options);
    var state = new EDEState(this.type, this.options.key);
    this._edeState = state;
}
inherits(EDE, Cipher);
EDE.create = function create(options) {
    return new EDE(options);
};
EDE.prototype._update = function _update(inp, inOff, out, outOff) {
    var state = this._edeState;
    state.ciphers[0]._update(inp, inOff, out, outOff);
    state.ciphers[1]._update(out, outOff, out, outOff);
    state.ciphers[2]._update(out, outOff, out, outOff);
};
EDE.prototype._pad = DES.prototype._pad;
EDE.prototype._unpad = DES.prototype._unpad;
export default EDE;


text:
package igeo;

/**
   Interface to be used as to switch methods to return entity or reference instance.

   @see ISwitchE
   @see ISwitchR

   @author Satoru Sugihara
*/
public interface ISwitchI{} // switch of entity/reference