text:
"""
Created on Apr 4, 2014

@author: Christoph Gollan

In this module you can find the :class:`MyStorage`. It inherits
from :class:`base.base.Storage`.

This class represents the base layer. It manages the project files,
the data loading and the data writing.

The data loading is called in the :class:`Task` which is a thread.
"""
# system imports
from os import remove
from os.path import splitext, basename, exists, split, join
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np

# swan-specific imports
from swan.base.storage import Storage
from swan.base.project import Project
from swan.neodata import NeoData
from swan.virtual_unit_map import VirtualUnitMap

class Task(QtCore.QThread):
    """
    A thread that loads the data.

    **Arguments**

        *data* (:class:`src.neodata.NeoData`):
            Is needed because it has the loading routine.
        *files* (list of string):
            The list containing the file paths.
        *channel* (integer):
            The channel that has to be loaded.

    """

    def __init__(self, data, files, channel):
        """
        **Properties**

            *data* (:class:`src.neodata.NeoData`):
                Is needed because it has the loading routine.
            *files* (list of string):
                The list containing the file paths.
            *channel* (integer):
                The channel that has to be loaded.

        """
        QtCore.QThread.__init__(self)
        self.data = data
        self.files = files
        self.channel = channel

    def run(self):
        """
        Runs the loading routine of
        the :class:`src.neodata.NeoData` object.

        """
        self.data.load(self.files, self.channel)

class MyStorage(Storage, QtCore.QObject):
    """
    The base class.

    It manages the project files and the data.

    **Arguments**

        *_program_dir* (string):
            The path to the main program. It has to end with the top-level directory swan.
        *cache_dir* (string):
            The default path of the cache directory.

    """

    progress = QtCore.pyqtSignal(int)
    """
    Progress signal that indicates how far the given task has progressed.

    """

    def __init__(self, program_dir, cache_dir):
        """
        **Properties**

            *_project* (:class:`base.project.Project`):
                The project object that manages project files.
            *_PNAME* (string):
                The default project name.
            *_program_dir* (string):
                The path to the main program. It has to end with the top-level directory swan.
            *_cache_dir* (string):
                The path to the cache directory.
            *_copy_i* (integer):
                An integer that is used to create the project name.
                If the default project name already exists, it will be changed by using
                this attribute.
            *_loading* (boolean):
                Whether or not something is loading at the moment.

        """
        super(MyStorage, self).__init__()
        super(QtCore.QObject, self).__init__()

        # properties{
        self._project = None
        self._PNAME = "swan"
        self._program_dir = program_dir
        self._cache_dir = cache_dir
        self._copy_i = 1
        self._loading = False
        # }

        self.store("channel", 1)
        self.store("lastchannel", 1)

    def set_cache_dir(self, cache_dir):
        """
        Lets you change the cache directory.

        **Arguments**

            *cache_dir* (string):
                The new cache location.

        """
        self._cache_dir = cache_dir
        try:
            self.get_data().cdir = cache_dir
        except:
            pass

    def load_project(self, prodir, proname, channel, files=None):
        """
        Creates or loads a new project.

        It creates the project files and loads data from the
        project file or the given file list.

        **Arguments**

            *prodir* (string):
                The path to the project directory.
            *proname* (string):
                The project name. Will be the name of the project file.
            *channel* (integer):
                The current channel. It is just used to set the channel.
                No loading will be done here.
            *files* (list of string or None):
                The list containing the file paths.
                Set it to None if you want to load from a file.
                Default: None.

            **Returns**: boolean
                If the project loading succeeded.

        """
        loadFiles = files is None

        # return if there is nothing to load
        if not loadFiles and len(files) == 0:
            return False

        # if something goes wrong, you can back to the old project
        tmp = self._project

        self.set_project(prodir)

        if not loadFiles:
            # checking if standard name is already existing
            # if so, the name will be changed

            while True:
                try:
                    self._project.add_file(self.get_pro_name(proname))
                    break
                except:
                    istr = str(self._copy_i)
                    l = len(istr)
                    if proname.endswith(")"):
                        proname = (splitext(proname)[0])[:-2 - l] + "(" + istr + ")"
                    else:
                        proname = (splitext(proname)[0]) + "(" + istr + ")"
                    self._copy_i += 1

            self._project.add_file(self.get_vum_name(proname))
        else:
            self._project.add_file(self.get_pro_name(proname), None, False)
            self._project.add_file(self.get_vum_name(proname), None, False)

        try:
            # reading the file
            if loadFiles:
                files = self.read_file()
            self.store("files", files)

            # free the old data object
            try:
                dataToDelete = self.get_data()
                dataToDelete.delete_IOs()
            except:
                pass

            # creating the important NeoData object
            neodata = NeoData(self._cache_dir)
            neodata.progress.connect(self.setProgress)
            self.store("data", neodata)

            self.set_channel(channel)

            # create or load the dict for the virtual unit mappings
            # create or load a second one for backup
            try:
                vum_all = self.load_map()
                vum_all2 = self.load_map()
            except IOError:
                vum_all = {}
                vum_all2 = {}
            self.store("vum_all", vum_all)
            self.store("vum_all2", vum_all2)

            self.save_file()

            return True
        except IOError:
            self._project = tmp
            return False

    def save_project(self):
        """
        Saves the project and the map.

        """
        if self.has_project():
            self.save_file()
            self.save_map()

    def save_project_as(self, filename):
        """
        Saves the project and the map but it changes the name of both of them.
        Existing project files with the same name will be removed.

        **Arguments**

            *filename* (string):
                The new filename.

        """
        (fdir, fname) = split(filename)
        if exists(filename):
            remove(filename)
        vumname = self.get_vum_name(fname)
        vumfull = join(fdir, vumname)
        if exists(vumfull):
            remove(vumfull)
        self.set_project(fdir)
        fname = self.get_pro_name(fname)
        self._project.add_file(fname)
        self._project.add_file(vumname)
        self.save_project()

    def set_project(self, prodir):
        """
        Creates and sets a new project.

        **Arguments**

            *prodir* (string):
                The path to the project directory.

        """
        p = Project(self._PNAME, prodir, False)
        self._project = p

    def set_channel(self, channel):
        """
        Sets the new channel and the last channel.

        **Arguments**

            channel (integer):
                The new channel.

        """
        last = self.get("channel")
        self.store("channel", channel)
        self.store("lastchannel", last)

    def get_project_path(self):
        """
        Wrapper for getting the absolute path to the project file.

            **Returns**: string
                The absolute path to the project file.

        """
        return self._project.get_file_path(self._project.get_file_list()[0])

    def get_map_path(self):
        """
        Wrapper for getting the absolute path to the map file.

            **Returns**: string
                The absolute path to the map file.

        """
        return self._project.get_file_path(self._project.get_file_list()[1])

    def has_project(self):
        """
            **Returns**: boolean
                If there is a project loaded.

        """
        return self._project is not None

    def get_pro_name(self, proname):
        """
        **Arguments**

            *proname* (string):
                The project file name.

            **Returns**: string
                A project file name with a .txt extension if it
                was not already there.

        """
        if proname.endswith(".txt"):
            return proname
        else:
            proname = proname + ".txt"
            return proname

    def get_vum_name(self, proname):
        """
        **Arguments**

            *proname* (string):
                The project file name.

            **Returns**: string
                A map file name with a .vum extension that belongs
                to the project file name.

        """
        proname = self.get_pro_name(proname)
        proname = splitext(proname)[0]
        vumname = proname + "_vum.vum"
        return vumname

    def get_channel(self):
        """
        Wraps the channel getter.

            **Returns**: integer
                The channel.

        """
        return self.get("channel")

    def get_last_channel(self):
        """
        Wraps the lastchannel getter.

            **Returns**: integer
                The last channel.

        """
        return self.get("lastchannel")

    def get_files(self, as_string=False, only_basenames=False):
        """
        Wraps the files getter.

        **Arguments**

            *as_string* (boolean):
                If you want a string containing the file paths instead.
                Default: False.

            **Returns**: list of string or string:
                The file list or a string with the file paths.

        """
        files = self.get("files")
        if only_basenames:
            files = [basename(file_path) for file_path in files]
        if as_string:
            return "\n".join(files)
        return files

    def get_map(self):
        """
        Wraps the map getter.

            **Returns**: :class:`src.virtualunitmap.VirtualUnitMap`
                The current virtual unit mapping.

        """
        return self.get("vum")

    def get_data(self):
        """
        Wraps the data getter.

            **Returns**: :class:`src.neodata.NeoData`
                The current data object.

        """
        return self.get("data")

    def get_mappings(self):
        """
        Getter for the virtual unit map container dictionary.

            **Returns**: dictionary
                All saved virtual unit maps.

        """
        return self.get("vum_all")

    def get_map_backup(self):
        """
        Getter for the map backup.

            **Returns**: :class:`src.virtualunitmap.VirtualUnitMap`
                The map backup loaded from the backup dictionary.

        """
        channel = self.get_channel()
        name = "vum" + str(channel)
        try:
            vum_all2 = self.get("vum_all2")
            vum = vum_all2[name]
            return vum
        except KeyError:
            return None

    def get_tooltips(self):
        """
        Creates tool tips for the overview.

        **Returns**: list of string:
                The tool tips.

        """
        tips = []
        virtual_unit_map = self.get_map()
        file_list = self.get_files()
        data = self.get_data()
        spike_nums = []
        c = 0
        for session_id in range(len(virtual_unit_map.mapping)):
            spike_nums.append([])
            for unit_id in range(len(virtual_unit_map.mapping[session_id])):
                if virtual_unit_map.mapping[session_id][unit_id] != 0:
                    runit = virtual_unit_map.get_realunit(session_id, unit_id, data)
                    spike_nums[c].append(data.get_data("n_spikes", runit))
                else:
                    spike_nums[c].append(0)
            c += 1

        c = 0
        for f, l, n in zip(file_list, virtual_unit_map.mapping, spike_nums):
            tips.append([])
            for u, v in zip(l, n):
                tooltip = "File: {}\nUnit: {}\nWaveforms: {}".format(basename(f), u, v)
                tips[c].append(tooltip)
            c += 1
        return tips

    def recalculate(self, mapping=0, parent=None):
        """
        Recalculates the mapping and sets it.

        """
        vum = self.get_map()
        data = self.get_data()

        vum.calculate_mapping(data, self, automatic_mapping=mapping, parent=parent)

        self.change_map()

    def revert(self):
        """
        Reverts the current mapping to the last saved one.

        """
        vumap = self.get_map()
        vumap.reset()
        vum = self.get_map_backup()
        data = self.get_data()
        if vum is not None:
            vumap.set_map(data.total_units_per_block, vum)
        else:
            vumap.set_initial_map(data)

    def swap(self, m, n1, n2):
        """
        Swaps the mapping of two entries in
        the :class:`src.virtualunitmap.VirtualUnitMap`.

        **Arguments**

            *m* (integer):
                The session index.
            *n1* (integer):
                The unit index 1.
            *n2* (integer):
                The unit index 2.

        """
        self.get_map().swap(m, n1, n2)
        self.change_map()

    def changeVisibility(self, i, j, visible):
        vmap = self.get_map()
        vmap.set_visible(i, j, visible)

    def load_channel(self, channel):
        """
        Loads a channel.

        **Arguments**

            *channel* (integer):
                The channel that should be loaded.

            **Returns**: tuple of integer
                The number of unit rows and the number of sessions.

        """
        self.set_channel(channel)
        data = self.get("data")
        files = self.get("files")

        # loading with a thread
        t = Task(data, files, channel)
        t.start()
        while t.isRunning():
            self._loading = t.isRunning()
            QtGui.QApplication.processEvents()
        self._loading = t.isRunning()

        vum_all = self.get("vum_all")
        name = "vum" + str(channel)

        vumap = VirtualUnitMap()

        # load a mapping or set the default one
        try:
            vum = vum_all[name]
            vumap.set_map(data.total_units_per_block, vum)
        except KeyError:
            vumap.set_initial_map(data)

        self.store("vum", vumap)

        return sum(data.total_units_per_block), len(vumap.mapping)

    def read_file(self):
        """
        Reads the project file and returns the lines without the
        newline character.

            **Returns**: list of string
                The input lines.

        """
        files = []
        try:
            with open(self.get_project_path(), "r") as fn:
                for f in fn:
                    if f.endswith("\n"):
                        files.append(f[:-1])
                    else:
                        files.append(f)
            return files
        except:
            raise IOError("Could not read project file")

    def save_file(self):
        """
        Writes the file paths of the loaded sessions to a file.

        """
        files = self.get("files")
        data = "\n".join(files)
        Storage.write(self.get_project_path(), data)

    def save_map(self):
        """
        Saves the dictionary containing all virtual unit mappings.

        """
        self.change_map()
        vum_all = self.get("vum_all")
        Storage.write(self.get_map_path(), vum_all, "pickle")
        self.store("vum_all2", self.load_map())

    def load_map(self):
        """
        Loads the dictionary containing all virtual unit mappings.

            **Returns**: dictionary
                The loaded map.

        """
        try:
            vum = Storage.read(self.get_map_path(), "pickle")
            return vum
        except:
            raise IOError("Could not read VUMap")

    def check_map(self, vum, files):
        """
        Checks if the map is correct.

        **Arguments**

            *vum* (:class:`src.virtualunitmap.VirtualUnitMap`):
                The mapping object that has to be checked.
            *files* (list of string):
                The file list containing the session names that
                should be in the map, too.

            **Returns**: boolean
                If the map is correct.

        """
        if not vum["files"] == files:
            return False
        return True

    def change_map(self):
        """
        Changes the current loaded map without saving it.

        """
        channel = self.get("channel")
        vum_all = self.get("vum_all")
        files = [basename(f) for f in self.get("files")]
        vum = self.get("vum")
        d = {"channel": channel}

        for i in range(vum.total_units):
            d[i] = []
        for filename, vus in zip(files, vum.mapping):
            for i in range(len(vus)):
                d[i].append((basename(filename), vus[i]))

        name = "vum" + str(channel)
        vum_all[name] = d
        vum_all["files"] = files

    def is_loading(self):
        """
        Getter for the loading information.

            **Returns**: boolean
                If there is something loading at the moment.

        """
        return self._loading

    def setProgress(self, i):
        """
        Emits a signal to the parent widget (the main program)
        containing the loading progress.

        **Arguments**

            *i* (integer):
                The loading progress.

        """
        self.progress.emit(i)


text:
package com.amazonaws.services.sagemaker.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.sagemaker.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * LabelCountersForWorkteamMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class LabelCountersForWorkteamMarshaller {

    private static final MarshallingInfo<Integer> HUMANLABELED_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("HumanLabeled").build();
    private static final MarshallingInfo<Integer> PENDINGHUMAN_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PendingHuman").build();
    private static final MarshallingInfo<Integer> TOTAL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Total").build();

    private static final LabelCountersForWorkteamMarshaller instance = new LabelCountersForWorkteamMarshaller();

    public static LabelCountersForWorkteamMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(LabelCountersForWorkteam labelCountersForWorkteam, ProtocolMarshaller protocolMarshaller) {

        if (labelCountersForWorkteam == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(labelCountersForWorkteam.getHumanLabeled(), HUMANLABELED_BINDING);
            protocolMarshaller.marshall(labelCountersForWorkteam.getPendingHuman(), PENDINGHUMAN_BINDING);
            protocolMarshaller.marshall(labelCountersForWorkteam.getTotal(), TOTAL_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace CpuProf {

/// \class CPUPROF_DEV_EXTENSION Holds all the driver state information and extends the device
class Device : ExplicitObject
{
private:
    // The driver device object.
    DEVICE_OBJECT* m_pDeviceObject;

    PrdDataBufferPool m_prdDataBuffersPool;

    // The array of clients, to allow for multiple Apps simultaneously profiling
    Client m_clients[MAX_CLIENT_COUNT];

    AtomicMask<MAX_CLIENT_COUNT> m_clientsMask;
    AtomicCounter<ULONG> m_clientsCount;

    // Obtained from \ref PcoreGetResourceCount
    ULONG m_resourceCounts[MAX_RESOURCE_TYPE];
    // The maximum number of resources of any one type
    ULONG m_maxResources;

    // Tracks whether the extended branch target feature of IBS_OP is available
    bool m_hasIbsBrnTrgt;
    // Tracks whether the extended extended count features of IBS_OP is available
    bool m_isIbsOpCntExt;

    // Pointer to the pause shared memory, an array of BOOLEAN, corresponding to index to aClients
    SHARED_CLIENT* m_pSharedObjSystemAddress;
    // Memory probed and locked page(s) containing the shared pause memory
    MDL* m_pSharedObjMdl;
    // Shared memory base address
    PVOID m_pSharedObjBaseAddress;
    // Shared memory section handle
    HANDLE m_sharedObjSectionHandle;

    StackTraceDispatcher m_stackTraceDispatcher;

public:
    Device(DEVICE_OBJECT* pDeviceObject);
    ~Device();

    Client* AcquireClient(PFILE_OBJECT pUserFileObject);
    bool ReleaseClient(ULONG clientId);
    ULONG ReleaseClients(PFILE_OBJECT pUserFileObject);

    StackTraceDispatcher& GetStackTraceDispatcher() { return m_stackTraceDispatcher; }

    PrdDataBufferPool& GetPrdDataBufferPool() { return m_prdDataBuffersPool; }

    ULONG GetRegisteredClientsMask() const { return m_clientsMask.GetValue(); }
    ULONG GetRegisteredClientsCount() const { return m_clientsCount; }
    ULONG GetResourceCount(PCORERESOURCETYPES type) const;
    ULONG GetMaxResourceCount() const { return m_maxResources; }

    bool HasIbsBrnTrgt() const { return m_hasIbsBrnTrgt; }
    bool IsIbsOpCntExt() const { return m_isIbsOpCntExt; }

    bool IsSamplingSuspended(ULONG clientId) const;

    const DEVICE_OBJECT* GetDeviceObject() const { return m_pDeviceObject; }
          DEVICE_OBJECT* GetDeviceObject()       { return m_pDeviceObject; }

    const Client* GetClient(ULONG clientId) const;
          Client* GetClient(ULONG clientId);

private:
    // Sets up the CodeAnalyst User-mode Kernel-mode Shared Object.
    NTSTATUS CreateUserKernelSharedMap();

    // Frees up the User-mode Kernel-mode Shared Object.
    NTSTATUS DeleteUserKernelSharedMap();

    static Device* s_pInstance;

    // number of CPUs on system
    static ULONG s_coresCount;

public:
    static Device* GetInstance() { return s_pInstance; }
    static ULONG GetCoresCount() { return s_coresCount; }

    static NTSTATUS Create(DEVICE_OBJECT* pDeviceObject, ULONG coresCount);
    static void Destroy();
};

inline ULONG GetCoresCount() { return Device::GetCoresCount(); }
inline Client* GetClient(ULONG clientId) { return Device::GetInstance()->GetClient(clientId); }

} // namespace CpuProf

#endif // _CPUPROF_DEVICE_HPP_


text:
function injectInitializer() {
  if (typeof Em !== 'undefined' && typeof Ember !== 'undefined') {

    (function($){
      var selector = 'li.budget-table-cell-budgeted div.currency-input, ' +
                     'div.ynab-grid-cell-outflow div.currency-input, ' +
                     'div.ynab-grid-cell-inflow div.currency-input';

      $(document).on('keypress', selector, function(e) {
        e = e || window.event;
        var charCode = e.which || e.keyCode;
        var charTyped = String.fromCharCode(charCode);

        if (charTyped == '+' ||
            charTyped == '-' ||
            charTyped == '*' ||
            charTyped == '/')
        {
          var input = $(this).find('input');
          var length = input.val().length;

          // This moves the caret to the end of the input.
          input[0].focus();
          input[0].setSelectionRange(length, length);
        }

        // Make sure we allow the event to bubble up so we don't mess with anything
        // that YNAB is doing.
      })
    })(jQuery)
  } else {
    setTimeout(injectInitializer, 250);
  }
}

setTimeout(injectInitializer, 250);


text:
/* */
var baseAt = require('./_baseAt'),
    flatRest = require('./_flatRest');
var at = flatRest(baseAt);
module.exports = at;


text:
import { Meteor } from 'meteor/meteor';

import { TabBar } from '../../ui-utils/client';
import { settings } from '../../settings';

Meteor.startup(function() {
	return TabBar.addButton({
		groups: ['channel', 'group', 'direct'],
		id: 'discussions',
		i18nTitle: 'Discussions',
		icon: 'discussion',
		template: 'discussionsTabbar',
		order: 1,
		condition: () => settings.get('Discussion_enabled'),
	});
});


text:
package com.gravity.goose

import org.junit.Test
import org.junit.Assert._

class OpenGraphTest {

  @Test
  def openGraph() {
    implicit val config = TestUtils.NO_IMAGE_CONFIG
    // og tags for http://www.telegraph.co.uk/foodanddrink/foodanddrinknews/8808120/Worlds-hottest-chilli-contest-leaves-two-in-hospital.html
    /*
<meta property="og:title" content="World's hottest chilli contest leaves two in hospital - Telegraph" />
<meta property="og:url" content="http://www.telegraph.co.uk/foodanddrink/foodanddrinknews/8808120/Worlds-hottest-chilli-contest-leaves-two-in-hospital.html" />

<meta property="og:image" content="http://i.telegraph.co.uk/multimedia/archive/02018/Kismot-Killer_2018476a.jpg" />
<meta property="og:type" content="article" />
     */
    val url: String = "http://www.telegraph.co.uk/foodanddrink/foodanddrinknews/8808120/Worlds-hottest-chilli-contest-leaves-two-in-hospital.html"
    val article = TestUtils.getArticle(url)
    assertEquals("og:description was not as expected!", article.openGraphData.description,
      "A 'world's hottest chilli' competition at a curry restaurant left two people   in hospital.")
    assertEquals("og:title was not as expected!", article.openGraphData.title,
      "World's hottest chilli contest leaves two in hospital - Telegraph")
    assertEquals("og:url was not as expected!", article.openGraphData.url,
      "http://www.telegraph.co.uk/foodanddrink/foodanddrinknews/8808120/Worlds-hottest-chilli-contest-leaves-two-in-hospital.html")
    assertEquals("og:image was not as expected!", article.openGraphData.image,
      "http://i.telegraph.co.uk/multimedia/archive/02018/Kismot-Killer_2018476a.jpg")
    assertEquals("og:type was not as expected!", article.openGraphData.ogType,
      "article")
  }
}


text:
import PostNodeBuilder from 'mobiledoc-kit/models/post-node-builder';
import TestHelpers from '../../test-helpers';
import { VALID_ATTRIBUTES, INVALID_ATTRIBUTES } from '../../helpers/sections';

const { module, test } = TestHelpers;

let builder;
module('Unit: List Section', {
  beforeEach() {
    builder = new PostNodeBuilder();
  },
  afterEach() {
    builder = null;
  }
});

VALID_ATTRIBUTES.forEach(attribute => {
  // eslint-disable-next-line no-loop-func
  test(`a section can have attribute "${attribute.key}" with value "${attribute.value}`, assert => {
    const attributes = {};
    attributes[attribute.key] = attribute.value;

    const s1 = builder.createListSection('ol', [], attributes);
    assert.deepEqual(
      s1.attributes,
      attributes,
      'Attribute set at instantiation'
    );
  });
});

INVALID_ATTRIBUTES.forEach(attribute => {
  // eslint-disable-next-line no-loop-func
  test(`a section throws when invalid attribute "${attribute.key}" is passed to a marker`, assert => {
    const attributes = {};
    attributes[attribute.key] = attribute.value;

    assert.throws(() => {
      builder.createListSection('ul', [], attributes);
    });
  });

  test('cloning a list section creates the same type of list section', assert => {
    let item = builder.createListItem([builder.createMarker('abc')]);
    let list = builder.createListSection('ol', [item]);
    let cloned = list.clone();

    assert.equal(list.tagName, cloned.tagName);
    assert.equal(list.items.length, cloned.items.length);
    assert.equal(list.items.head.text, cloned.items.head.text);
  });
});


text:
Drag And Drop Assignments

    <jhi-alert></jhi-alert>

                <button class="btn btn-primary" ui-sref="drag-and-drop-assignment.new" >

                        Create new Drag And Drop Assignment

                </button>

                    ID
                    Item
                    Location
                    Submitted Answer

                    {{dragAndDropAssignment.id}}

                        {{dragAndDropAssignment.item.id}}

                        {{dragAndDropAssignment.location.id}}

                        {{dragAndDropAssignment.submittedAnswer.id}}

                            <button type="submit"
                                    ui-sref="drag-and-drop-assignment-detail({id:dragAndDropAssignment.id})"
                                    class="btn btn-info btn-sm">

                            </button>
                            <button type="submit"
                                    ui-sref="drag-and-drop-assignment.edit({id:dragAndDropAssignment.id})"
                                    class="btn btn-primary btn-sm">

                            </button>
                            <button type="submit"
                                    ui-sref="drag-and-drop-assignment.delete({id:dragAndDropAssignment.id})"
                                    class="btn btn-danger btn-sm">

                            </button>


text:
"""A framework for developing sources for new file types.

To create a source for a new file type a sub-class of :class:`FileBasedSource`
should be created. Sub-classes of :class:`FileBasedSource` must implement the
method :meth:`FileBasedSource.read_records()`. Please read the documentation of
that method for more details.

For an example implementation of :class:`FileBasedSource` see
:class:`~apache_beam.io._AvroSource`.
"""

from __future__ import absolute_import

from past.builtins import long
from past.builtins import unicode

from apache_beam.internal import pickler
from apache_beam.io import concat_source
from apache_beam.io import iobase
from apache_beam.io import range_trackers
from apache_beam.io.filesystem import CompressionTypes
from apache_beam.io.filesystems import FileSystems
from apache_beam.io.restriction_trackers import OffsetRange
from apache_beam.options.value_provider import StaticValueProvider
from apache_beam.options.value_provider import ValueProvider
from apache_beam.options.value_provider import check_accessible
from apache_beam.transforms.core import DoFn
from apache_beam.transforms.core import ParDo
from apache_beam.transforms.core import PTransform
from apache_beam.transforms.display import DisplayDataItem
from apache_beam.transforms.util import Reshuffle

MAX_NUM_THREADS_FOR_SIZE_ESTIMATION = 25

__all__ = ['FileBasedSource']

class FileBasedSource(iobase.BoundedSource):
  """A :class:`~apache_beam.io.iobase.BoundedSource` for reading a file glob of
  a given type."""

  MIN_NUMBER_OF_FILES_TO_STAT = 100
  MIN_FRACTION_OF_FILES_TO_STAT = 0.01

  def __init__(self,
               file_pattern,
               min_bundle_size=0,
               compression_type=CompressionTypes.AUTO,
               splittable=True,
               validate=True):
    """Initializes :class:`FileBasedSource`.

    Args:
      file_pattern (str): the file glob to read a string or a
        :class:`~apache_beam.options.value_provider.ValueProvider`
        (placeholder to inject a runtime value).
      min_bundle_size (str): minimum size of bundles that should be generated
        when performing initial splitting on this source.
      compression_type (str): Used to handle compressed output files.
        Typical value is :attr:`CompressionTypes.AUTO
        <apache_beam.io.filesystem.CompressionTypes.AUTO>`,
        in which case the final file path's extension will be used to detect
        the compression.
      splittable (bool): whether :class:`FileBasedSource` should try to
        logically split a single file into data ranges so that different parts
        of the same file can be read in parallel. If set to :data:`False`,
        :class:`FileBasedSource` will prevent both initial and dynamic splitting
        of sources for single files. File patterns that represent multiple files
        may still get split into sources for individual files. Even if set to
        :data:`True` by the user, :class:`FileBasedSource` may choose to not
        split the file, for example, for compressed files where currently it is
        not possible to efficiently read a data range without decompressing the
        whole file.
      validate (bool): Boolean flag to verify that the files exist during the
        pipeline creation time.

    Raises:
      ~exceptions.TypeError: when **compression_type** is not valid or if
        **file_pattern** is not a :class:`str` or a
        :class:`~apache_beam.options.value_provider.ValueProvider`.
      ~exceptions.ValueError: when compression and splittable files are
        specified.
      ~exceptions.IOError: when the file pattern specified yields an empty
        result.
    """

    if not isinstance(file_pattern, ((str, unicode), ValueProvider)):
      raise TypeError('%s: file_pattern must be of type string'
                      ' or ValueProvider; got %r instead'
                      % (self.__class__.__name__, file_pattern))

    if isinstance(file_pattern, (str, unicode)):
      file_pattern = StaticValueProvider(str, file_pattern)
    self._pattern = file_pattern

    self._concat_source = None
    self._min_bundle_size = min_bundle_size
    if not CompressionTypes.is_valid_compression_type(compression_type):
      raise TypeError('compression_type must be CompressionType object but '
                      'was %s' % type(compression_type))
    self._compression_type = compression_type
    self._splittable = splittable
    if validate and file_pattern.is_accessible():
      self._validate()

  def display_data(self):
    return {'file_pattern': DisplayDataItem(str(self._pattern),
                                            label="File Pattern"),
            'compression': DisplayDataItem(str(self._compression_type),
                                           label='Compression Type')}

  @check_accessible(['_pattern'])
  def _get_concat_source(self):
    if self._concat_source is None:
      pattern = self._pattern.get()

      single_file_sources = []
      match_result = FileSystems.match([pattern])[0]
      files_metadata = match_result.metadata_list

      # We create a reference for FileBasedSource that will be serialized along
      # with each _SingleFileSource. To prevent this FileBasedSource from having
      # a reference to ConcatSource (resulting in quadratic space complexity)
      # we clone it here.
      file_based_source_ref = pickler.loads(pickler.dumps(self))

      for file_metadata in files_metadata:
        file_name = file_metadata.path
        file_size = file_metadata.size_in_bytes
        if file_size == 0:
          continue  # Ignoring empty file.

        # We determine splittability of this specific file.
        splittable = (
            self.splittable and
            _determine_splittability_from_compression_type(
                file_name, self._compression_type))

        single_file_source = _SingleFileSource(
            file_based_source_ref, file_name,
            0,
            file_size,
            min_bundle_size=self._min_bundle_size,
            splittable=splittable)
        single_file_sources.append(single_file_source)
      self._concat_source = concat_source.ConcatSource(single_file_sources)
    return self._concat_source

  def open_file(self, file_name):
    return FileSystems.open(
        file_name, 'application/octet-stream',
        compression_type=self._compression_type)

  @check_accessible(['_pattern'])
  def _validate(self):
    """Validate if there are actual files in the specified glob pattern
    """
    pattern = self._pattern.get()

    # Limit the responses as we only want to check if something exists
    match_result = FileSystems.match([pattern], limits=[1])[0]
    if len(match_result.metadata_list) <= 0:
      raise IOError(
          'No files found based on the file pattern %s' % pattern)

  def split(
      self, desired_bundle_size=None, start_position=None, stop_position=None):
    return self._get_concat_source().split(
        desired_bundle_size=desired_bundle_size,
        start_position=start_position,
        stop_position=stop_position)

  @check_accessible(['_pattern'])
  def estimate_size(self):
    pattern = self._pattern.get()
    match_result = FileSystems.match([pattern])[0]
    return sum([f.size_in_bytes for f in match_result.metadata_list])

  def read(self, range_tracker):
    return self._get_concat_source().read(range_tracker)

  def get_range_tracker(self, start_position, stop_position):
    return self._get_concat_source().get_range_tracker(start_position,
                                                       stop_position)

  def read_records(self, file_name, offset_range_tracker):
    """Returns a generator of records created by reading file 'file_name'.

    Args:
      file_name: a ``string`` that gives the name of the file to be read. Method
                 ``FileBasedSource.open_file()`` must be used to open the file
                 and create a seekable file object.
      offset_range_tracker: a object of type ``OffsetRangeTracker``. This
                            defines the byte range of the file that should be
                            read. See documentation in
                            ``iobase.BoundedSource.read()`` for more information
                            on reading records while complying to the range
                            defined by a given ``RangeTracker``.

    Returns:
      an iterator that gives the records read from the given file.
    """
    raise NotImplementedError

  @property
  def splittable(self):
    return self._splittable

def _determine_splittability_from_compression_type(
    file_path, compression_type):
  if compression_type == CompressionTypes.AUTO:
    compression_type = CompressionTypes.detect_compression_type(file_path)

  return compression_type == CompressionTypes.UNCOMPRESSED

class _SingleFileSource(iobase.BoundedSource):
  """Denotes a source for a specific file type."""

  def __init__(self, file_based_source, file_name, start_offset, stop_offset,
               min_bundle_size=0, splittable=True):
    if not isinstance(start_offset, (int, long)):
      raise TypeError(
          'start_offset must be a number. Received: %r' % start_offset)
    if stop_offset != range_trackers.OffsetRangeTracker.OFFSET_INFINITY:
      if not isinstance(stop_offset, (int, long)):
        raise TypeError(
            'stop_offset must be a number. Received: %r' % stop_offset)
      if start_offset >= stop_offset:
        raise ValueError(
            'start_offset must be smaller than stop_offset. Received %d and %d '
            'for start and stop offsets respectively' %
            (start_offset, stop_offset))

    self._file_name = file_name
    self._is_gcs_file = file_name.startswith('gs://') if file_name else False
    self._start_offset = start_offset
    self._stop_offset = stop_offset
    self._min_bundle_size = min_bundle_size
    self._file_based_source = file_based_source
    self._splittable = splittable

  def split(self, desired_bundle_size, start_offset=None, stop_offset=None):
    if start_offset is None:
      start_offset = self._start_offset
    if stop_offset is None:
      stop_offset = self._stop_offset

    if self._splittable:
      splits = OffsetRange(start_offset, stop_offset).split(
          desired_bundle_size, self._min_bundle_size)
      for split in splits:
        yield iobase.SourceBundle(
            split.stop - split.start,
            _SingleFileSource(
                # Copying this so that each sub-source gets a fresh instance.
                pickler.loads(pickler.dumps(self._file_based_source)),
                self._file_name,
                split.start,
                split.stop,
                min_bundle_size=self._min_bundle_size,
                splittable=self._splittable),
            split.start,
            split.stop)
    else:
      # Returning a single sub-source with end offset set to OFFSET_INFINITY (so
      # that all data of the source gets read) since this source is
      # unsplittable. Choosing size of the file as end offset will be wrong for
      # certain unsplittable source, e.g., compressed sources.
      yield iobase.SourceBundle(
          stop_offset - start_offset,
          _SingleFileSource(
              self._file_based_source,
              self._file_name,
              start_offset,
              range_trackers.OffsetRangeTracker.OFFSET_INFINITY,
              min_bundle_size=self._min_bundle_size,
              splittable=self._splittable
          ),
          start_offset,
          range_trackers.OffsetRangeTracker.OFFSET_INFINITY
      )

  def estimate_size(self):
    return self._stop_offset - self._start_offset

  def get_range_tracker(self, start_position, stop_position):
    if start_position is None:
      start_position = self._start_offset
    if stop_position is None:
      # If file is unsplittable we choose OFFSET_INFINITY as the default end
      # offset so that all data of the source gets read. Choosing size of the
      # file as end offset will be wrong for certain unsplittable source, for
      # e.g., compressed sources.
      stop_position = (
          self._stop_offset if self._splittable
          else range_trackers.OffsetRangeTracker.OFFSET_INFINITY)

    range_tracker = range_trackers.OffsetRangeTracker(
        start_position, stop_position)
    if not self._splittable:
      range_tracker = range_trackers.UnsplittableRangeTracker(range_tracker)

    return range_tracker

  def read(self, range_tracker):
    return self._file_based_source.read_records(self._file_name, range_tracker)

  def default_output_coder(self):
    return self._file_based_source.default_output_coder()

class _ExpandIntoRanges(DoFn):

  def __init__(
      self, splittable, compression_type, desired_bundle_size, min_bundle_size):
    self._desired_bundle_size = desired_bundle_size
    self._min_bundle_size = min_bundle_size
    self._splittable = splittable
    self._compression_type = compression_type

  def process(self, element, *args, **kwargs):
    match_results = FileSystems.match([element])
    for metadata in match_results[0].metadata_list:
      splittable = (
          self._splittable and
          _determine_splittability_from_compression_type(
              metadata.path, self._compression_type))

      if splittable:
        for split in OffsetRange(
            0, metadata.size_in_bytes).split(
                self._desired_bundle_size, self._min_bundle_size):
          yield (metadata, split)
      else:
        yield (metadata, OffsetRange(
            0, range_trackers.OffsetRangeTracker.OFFSET_INFINITY))

class _ReadRange(DoFn):

  def __init__(self, source_from_file):
    self._source_from_file = source_from_file

  def process(self, element, *args, **kwargs):
    metadata, range = element
    source = self._source_from_file(metadata.path)
    # Following split() operation has to be performed to create a proper
    # _SingleFileSource. Otherwise what we have is a ConcatSource that contains
    # a single _SingleFileSource. ConcatSource.read() expects a RangeTraker for
    # sub-source range and reads full sub-sources (not byte ranges).
    source = list(source.split(float('inf')))[0].source
    for record in source.read(range.new_tracker()):
      yield record

class ReadAllFiles(PTransform):
  """A Read transform that reads a PCollection of files.

  Pipeline authors should not use this directly. This is to be used by Read
  PTransform authors who wishes to implement file-based Read transforms that
  read a PCollection of files.
  """

  def __init__(
      self, splittable, compression_type, desired_bundle_size, min_bundle_size,
      source_from_file):
    """
    Args:
      splittable: If False, files won't be split into sub-ranges. If True,
                  files may or may not be split into data ranges.
      compression_type: A ``CompressionType`` object that specifies the
                  compression type of the files that will be processed. If
                  ``CompressionType.AUTO``, system will try to automatically
                  determine the compression type based on the extension of
                  files.
      desired_bundle_size: the desired size of data ranges that should be
                           generated when splitting a file into data ranges.
      min_bundle_size: minimum size of data ranges that should be generated when
                           splitting a file into data ranges.
      source_from_file: a function that produces a ``BoundedSource`` given a
                        file name. System will use this function to generate
                        ``BoundedSource`` objects for file paths. Note that file
                        paths passed to this will be for individual files, not
                        for file patterns even if the ``PCollection`` of files
                        processed by the transform consist of file patterns.
    """
    self._splittable = splittable
    self._compression_type = compression_type
    self._desired_bundle_size = desired_bundle_size
    self._min_bundle_size = min_bundle_size
    self._source_from_file = source_from_file

  def expand(self, pvalue):
    return (pvalue
            | 'ExpandIntoRanges' >> ParDo(_ExpandIntoRanges(
                self._splittable, self._compression_type,
                self._desired_bundle_size, self._min_bundle_size))
            | 'Reshard' >> Reshuffle()
            | 'ReadRange' >> ParDo(_ReadRange(self._source_from_file)))


text:
package instrument

import (
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/uber-go/tally"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"go.uber.org/zap/zaptest/observer"
)

func TestScopeAndLoggerTagged(t *testing.T) {
	core, recorded := observer.New(zapcore.InfoLevel)
	iOpts := NewOptions().
		SetMetricsScope(tally.NewTestScope("", map[string]string{})).
		SetLogger(zap.New(core))
	iOpts = WithOptions(iOpts, WithScopeAndLoggerTagged("k", "v"))

	// Make sure the metric has tag k:v.
	iOpts.MetricsScope().Counter("a").Inc(1)

	ss := iOpts.MetricsScope().(tally.TestScope).Snapshot()
	counters, ok := ss.Counters()["a+k=v"]
	require.True(t, ok)
	require.Equal(t, map[string]string{"k": "v"}, counters.Tags())

	// Make sure the log has tag k:v.
	iOpts.Logger().Info("b")

	require.Len(t, recorded.All(), 1)
	require.Len(t, recorded.FilterField(
		zap.String("k", "v"),
	).All(), 1)
}


text:
import createSagaMiddleware from 'redux-saga';
import { createStore, applyMiddleware, compose } from 'redux';
import { RoutingController } from './controllers';
import { AppStateModel } from './state';
import RootReducer from './reducers';
import { ItemMiddleware, ProviderMiddleware, DebugMiddleware } from './middlewares';
import rootSaga from './sagas';

const sagaMiddleware = createSagaMiddleware();
const composeEnhancers = compose;

export default createStore(RootReducer, new AppStateModel(), composeEnhancers(applyMiddleware(
  DebugMiddleware,
  ProviderMiddleware,
  ItemMiddleware,
  RoutingController.middleware(),
  sagaMiddleware,
)));

sagaMiddleware.run(rootSaga);


text:
package com.pinhuba.core.daoimpl;

import org.springframework.stereotype.Repository;

import com.pinhuba.core.pojo.*;
import com.pinhuba.core.dao.*;
/**
 * 表:OA_JOURNALS_TYPE 对应daoImpl
 */
@Repository
public class OaJournalsTypeDaoImpl extends BaseHapiDaoimpl<OaJournalsType, Long> implements IOaJournalsTypeDao {

   public OaJournalsTypeDaoImpl(){
      super(OaJournalsType.class);
   }
}


text:
%[X] = FPCder(y,t,p)
%
%===========
%Description:
%===========
%
%            This is the main program to perform Functional Principal Component
%            Analysis (FPCA) via PACE for estimation of curves and their derivatives.
%            The principal component scores can be estimated through conditional
%            expectation or via classical integration. For the latter, one can
%            choose a shrinkage method for estimated scores.
%
%======
%Input:
%======
%      y:          1*n cell array, y{i} is the vector of measurements for the ith subject,
%                  i=1,...,n.
%      t:          1*n cell array, t{i} is the vector of time points for the ith subject on which
%                  corresponding measurements y{i} are taken, i=1,...,n.
%      p:          a struct obtained from setOptions.m sets the rest of arguments for PCA.m
%                  ex:
%                  >> p = setDerOptions();
%=======
%Output:
%=======
%      X:         a cell array that contains all returned values from PCA.m
%                 where the last element contains the names of X
%
%   To see the names for X, type names(X)
%   To get individual value back, type getVal(varname, X)
%   To see an example, check with exampleDer.m
%   See also PCder, setDerOptions, showDerOptionNames, exampleDer, names
%
function [X] = FPCder(y,t,p)

  if nargin == 2
    p = setDerOptions();
  end
 %addpath('./PACE');
  if isempty(p.yname)
     p.yname = inputname(1);
  end
[no_opt,sigma,lambda,phi,eigen,xi_est,xi_var,mu,muDense,bw_mu,xcov,bw_xcov,xcovfit,AIC,BIC,...
 FVE,y_pred,y_predOrig,y_predDense,out1,out21,y,t, rcov, regular, rho_opt, sigmanew, mucopy, phicopy, eigencopy, out1copy, out21copy, xcovcopy, xcovfitcopy, xcorr, ops]...
=PCder(y,t,p.bwmu, p.bwmu_gcv, p.bwxcov, p.bwxcov_gcv, ...
p.ntest1,p.ngrid1,p.selection_k, p.FVE_threshold, p.maxk,...
p.control,p.regular,p.error, p.ngrid,p.method,p.shrink,p.newdata, p.kernel, ...
p.npoly, p.nder, p.method_int, p.numBins, p.yname, p.screePlot, p.designPlot, p.corrPlot, p.rho, p.verbose);

Xnames = {'no_opt','sigma','lambda','phi','eigen','xi_est','xi_var','mu','muDense','bw_mu','xcov','bw_xcov',...
	  'xcovfit','AIC','BIC','FVE','y_pred','y_predOrig','y_predDense','out1','out21', 'y','t','rcov', 'regular', 'rho_opt','sigmanew','mucopy',...
	  'phicopy','eigencopy','out1copy', 'out21copy', 'xcovcopy', 'xcovfitcopy','xcorr','ops','names'};
X = {no_opt,sigma,lambda,phi,eigen,xi_est,xi_var,mu,muDense,bw_mu,xcov,bw_xcov,...
     xcovfit,AIC,BIC,FVE,y_pred,y_predOrig,y_predDense,out1,out21, y,t,rcov, regular, rho_opt, sigmanew, mucopy,...
     phicopy, eigencopy, out1copy, out21copy, xcovcopy, xcovfitcopy, xcorr, ops, Xnames};

end


text:
/*global Burner */
/**
 * Creates a new RangeDisplay.
 *
 * A RangeDisplay is parented to a sensor and displays the sensor's
 * sensitivity range.
 *
 * @constructor
 * @extends Burner.Item
 * @param {Object} [opt_options=] A map of initial properties.
 */
function RangeDisplay(opt_options) {
  var options = opt_options || {};
  options.name = options.name || 'RangeDisplay';
  Burner.Item.call(this, options);
}
Utils.extend(RangeDisplay, Burner.Item);

/**
 * Initializes an instance.
 *
 * @param {Object} options A map of initial properties.
 * @param {Object} parentA The object that starts the connection.
 * @param {Object} parentB The object that ends the connection.
 * @param {number} [options.zIndex = 0] zIndex.
 * @param {string} [options.borderStyle = 'dotted'] Border style.
 * @param {Array} [options.borderColor = 150, 150, 150] Border color.
 */
RangeDisplay.prototype.init = function(options) {

  if (!options || !options.sensor) {
    throw new Error('RangeDisplay: a sensor is required.');
  }
  this.sensor = options.sensor;

  this.zIndex = options.zIndex || 10;

  this.borderStyle = typeof options.borderStyle === 'undefined' ? 'dashed' : options.borderStyle;
  this.borderDefaultColor = typeof options.borderDefaultColor === 'undefined' ? [150, 150, 150] : options.borderDefaultColor;

  /**
   * RangeDisplays have no height or color and rely on the associated DOM element's
   * CSS border to render their line.
   */
  this.borderWidth = 2;
  this.borderRadius = 100;
  this.width = this.sensor.sensitivity;
  this.height = this.sensor.sensitivity;
  this.minOpacity = 0.3;
  this.maxOpacity = 0.6;
  this.opacity = this.minOpacity;
  this.color = 'transparent';
  this.maxAngularVelocity = 1;
  this.minAngularVelocity = 0;
};

/**
 * Called every frame, step() updates the instance's properties.
 */
RangeDisplay.prototype.step = function() {
  this.location = this.sensor.location;

  var angularVelocity = Flora.Utils.map(this.sensor.parent.velocity.mag(),
      this.sensor.parent.minSpeed, this.sensor.parent.maxSpeed,
      this.maxAngularVelocity, this.minAngularVelocity);

  if (this.sensor.activated) {
    this.opacity = this.maxOpacity;
    this.borderColor = this.sensor.target.color;
  } else {
    this.opacity = this.minOpacity;
    this.borderColor = this.borderDefaultColor;
  }
};


text:
package tests.api.java.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;

public class SequenceInputStreamTest extends junit.framework.TestCase {

	SequenceInputStream si;

	String s1 = "Hello";

	String s2 = "World";

	/**
	 * @tests java.io.SequenceInputStream#SequenceInputStream(java.io.InputStream,
	 *        java.io.InputStream)
	 */
	public void test_ConstructorLjava_io_InputStreamLjava_io_InputStream() {
		// Test for method java.io.SequenceInputStream(java.io.InputStream,
		// java.io.InputStream)
		// Used in tests
	}

	/**
	 * @tests SequenceInputStream#SequenceInputStream(java.io.InputStream,
	 *        java.io.InputStream)
	 */
	public void test_Constructor_LInputStreamLInputStream_Null() {
		try {
			si = new SequenceInputStream(null , null);
			fail("should throw NullPointerException");
		} catch (NullPointerException e) {
			//expected
		}

		//will not throw NullPointerException if the first InputStream is not null
		InputStream is = new ByteArrayInputStream(s1.getBytes());
		si = new SequenceInputStream(is , null);
	}

	/**
	 * @tests java.io.SequenceInputStream#SequenceInputStream(java.util.Enumeration)
	 */
	public void test_ConstructorLjava_util_Enumeration() {
		// Test for method java.io.SequenceInputStream(java.util.Enumeration)
		class StreamEnumerator implements Enumeration {
			InputStream streams[] = new InputStream[2];

			int count = 0;

			public StreamEnumerator() {
				streams[0] = new ByteArrayInputStream(s1.getBytes());
				streams[1] = new ByteArrayInputStream(s2.getBytes());
			}

			public boolean hasMoreElements() {
				return count < streams.length;
			}

			public Object nextElement() {
				return streams[count++];
			}
		}

		try {
			si = new SequenceInputStream(new StreamEnumerator());
			byte buf[] = new byte[s1.length() + s2.length()];
			si.read(buf, 0, s1.length());
			si.read(buf, s1.length(), s2.length());
			assertTrue("Read incorrect bytes: " + new String(buf), new String(
					buf).equals(s1 + s2));
		} catch (IOException e) {
			fail("IOException during read test : " + e.getMessage());
		}

	}

	/**
	 * @tests java.io.SequenceInputStream#available()
	 */
	public void test_available() {
		// Test for method int java.io.SequenceInputStream.available()
		try {

			assertTrue("Returned incorrect number of bytes: " + si.available(),
					si.available() == s1.length());
		} catch (IOException e) {
			fail("IOException during available test : " + e.getMessage());
		}
	}

	/**
	 * @tests java.io.SequenceInputStream#close()
	 */
	public void test_close() throws IOException {
		si.close();
		//will not throw IOException to close a stream which is closed already
		si.close();
	}

	/**
	 * @tests java.io.SequenceInputStream#read()
	 */
	public void test_read() throws IOException {
		// Test for method int java.io.SequenceInputStream.read()
		try {
			si.read();
			assertTrue("Read incorrect char", (char) si.read() == s1.charAt(1));
		} catch (IOException e) {
			fail("IOException during read test: " + e.getMessage());
		}

		//returns -1 if the stream is closed , do not throw IOException
		si.close();
		int result = si.read();
		assertEquals(-1 , result);
	}

	/**
	 * @tests java.io.SequenceInputStream#read(byte[], int, int)
	 */
	public void test_read$BII() throws IOException {
		// Test for method int java.io.SequenceInputStream.read(byte [], int,
		// int)
		try {
			byte buf[] = new byte[s1.length() + s2.length()];
			si.read(buf, 0, s1.length());
			si.read(buf, s1.length(), s2.length());
			assertTrue("Read incorrect bytes: " + new String(buf), new String(
					buf).equals(s1 + s2));
		} catch (IOException e) {
			fail("IOException during read test : " + e.getMessage());
		}

		ByteArrayInputStream bis1 = new ByteArrayInputStream(
				new byte[] { 1, 2, 3, 4 });
		ByteArrayInputStream bis2 = new ByteArrayInputStream(
				new byte[] { 5, 6, 7, 8 });
		SequenceInputStream sis = new SequenceInputStream(bis1, bis2);

		try {
			sis.read(null, 0, -1);
			fail("Expected NullPointerException exception");
		} catch (NullPointerException e) {
			// expected
		}

        //returns -1 if the stream is closed , do not throw IOException
		byte[] array = new byte[] { 1 , 2 , 3 ,4 };
		sis.close();
		int result = sis.read(array , 0 , 5);
		assertEquals(-1 , result);

	}

	/**
	 * Sets up the fixture, for example, open a network connection. This method
	 * is called before a test is executed.
	 */
	protected void setUp() {
		si = new SequenceInputStream(new ByteArrayInputStream(s1.getBytes()),
				new ByteArrayInputStream(s2.getBytes()));
	}

	/**
	 * Tears down the fixture, for example, close a network connection. This
	 * method is called after a test is executed.
	 */
	protected void tearDown() {
	}
}


text:
<?php

namespace tests\unit\validators;

use app\validators\PasswordValidator;
use tests\unit\TestCase;

class PasswordValidatorTest extends TestCase
{
    /**
     * @return array test data
     */
    public function dataProviderValidate()
    {
        return [
            ['123456', false],
            ['password', false],
            ['1ba#', false],
            ['weakpassword', false],
            ['Strong4@password', true],
        ];
    }

    /**
     * @dataProvider dataProviderValidate
     *
     * @param string $value
     * @param boolean $expectedResult
     */
    public function testValidate($value, $expectedResult)
    {
        $validator = new PasswordValidator();
        $this->assertEquals($expectedResult, $validator->validate($value));
    }
}


text:
Colors a string white.

```js
chalk.white('Hello Sindre');
chalk.white.underline.bold('Hello Sindre');

let name = 'Sindre';
chalk.white('Hello %s', name);
// Hello Sindre
```


text:
using System;

/// <summary>
/// ctor(System.Int32,System.Int32,System.Int32)
/// </summary>
public class DateTimeCtor1
{
    #region Private Fields
    private int m_ErrorNo = 0;
    #endregion

    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;

        TestLibrary.TestFramework.LogInformation("[Negative]");
        retVal = NegTest1() && retVal;
        retVal = NegTest2() && retVal;
        retVal = NegTest3() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using valid value");

        try
        {
            retVal = retVal && VerifyDateTimeHelper(2006, 8, 28);
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using MAX/MIN values");

        try
        {
            retVal = retVal && VerifyDateTimeHelper(1, 1, 1);
            retVal = retVal && VerifyDateTimeHelper(9999, 12, 31);
            retVal = retVal && VerifyDateTimeHelper(1, 12, 31);
            retVal = retVal && VerifyDateTimeHelper(9999, 1, 1);
            retVal = retVal && VerifyDateTimeHelper(2000, 1, 31);
            retVal = retVal && VerifyDateTimeHelper(2000, 2, 29);
            retVal = retVal && VerifyDateTimeHelper(2001, 2, 28);
            retVal = retVal && VerifyDateTimeHelper(2001, 4, 30);
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using correct day/month pair");

        try
        {
            retVal = retVal && VerifyDateTimeHelper(2000, 2, 29);
            retVal = retVal && VerifyDateTimeHelper(2006, 2, 28);
            retVal = retVal && VerifyDateTimeHelper(2006, 4, 30);
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion

    #region Nagetive Test Cases
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999.");

        try
        {
            DateTime value = new DateTime(0, 1, 1);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        try
        {
            DateTime value = new DateTime(10000, 1, 1);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12");

        try
        {
            DateTime value = new DateTime(2006, 0, 1);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        try
        {
            DateTime value = new DateTime(2006, 13, 1);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool NegTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month");

        try
        {
            DateTime value = new DateTime(2006, 1, 0);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        try
        {
            DateTime value = new DateTime(2006, 1, 32);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        try
        {
            DateTime value = new DateTime(2006, 2, 29);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        try
        {
            DateTime value = new DateTime(2006, 4, 31);

            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            m_ErrorNo++;
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    public static int Main()
    {
        DateTimeCtor1 test = new DateTimeCtor1();

        TestLibrary.TestFramework.BeginTestCase("DateTimeCtor1");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }

    #region Private Methods
    private bool VerifyDateTimeHelper(int desiredYear, int desiredMonth, int desiredDay)
    {
        bool retVal = true;

        DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay);
        m_ErrorNo++;
        if ((desiredYear != value.Year) || (desiredMonth != value.Month) || (desiredDay != value.Day))
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value");
            TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() + ", desiredMonth = " + desiredMonth.ToString() + ", desiredDay = " + desiredDay.ToString() + ", actualYear = " + value.Year.ToString() + ", actualMonth = " + value.Month.ToString() + ", actualDay = " + value.Day.ToString());
            retVal = false;
        }

        m_ErrorNo++;
        if ((value.Hour != 0) || (value.Minute != 0) || (value.Second != 0))
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value");
            TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredHour = 0, desiredMinute = 0, desiredSecond = 0, actualHour = " + value.Hour.ToString() + ", actualMinute = " + value.Minute.ToString() + ", actualSecond = " + value.Second.ToString());
            retVal = false;
        }

        m_ErrorNo++;
        if (value.Kind != DateTimeKind.Unspecified)
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value");
            TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredKind = DateTimeKind.Unspecified" + ", actualKind = " + value.Kind.ToString());
            retVal = false;
        }

        return retVal;
    }
    #endregion
}


text:
package com.marathon.manage.vo;

public enum ResultEnum {
    //通用错误码
    SUCCESS("000", "成功"),ERROR("001","系统异常");

    // 成员变量
    private String status;
    private String statusDesc;

    ResultEnum(String code, String desc) {
        this.status = code;
        this.statusDesc = desc;
    }

    //覆盖方法
    @Override
    public String toString() {
        return this.status + "_" + this.statusDesc;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatusDesc() {
        return statusDesc;
    }

    public void setStatusDesc(String statusDesc) {
        this.statusDesc = statusDesc;
    }

}


text:
layout: post
title:  "Blaubot 2.0.0.beta.2"
date:   2016-07-14
categories: release
---

The second beta is now available from jCenter and MavenCentral.
We fixed some bugs and made sure that we can build on JDK8, which is used to build the latest Android API levels.

The most important bugs fixed in this version were

  * a problem with receiving and sending messages when `transmitReflexiveMessages` as well as `transmitIfNoSubscribers` were set to false on a channel.
  * a performance hit when a channel had no subscribers and a very low message rate.

# What comes next?
Android 6 currently breaks some Blaubot configurations, because they decided to restrict access to hardware identifiers such as the WiFi- or Bluetooth-Adapter's MAC-address, which are essential informations for some BlaubotAdapters (such as the BluetoothAdapter and Beacon).
There is ongoing work to make blaubot compatible with this breaking changes before removing the beta status.
Blaubot users who just use the Ethernet/WiFi-based adapters will be mostly save.
For more informations on that matter, check the [Android 6 changelog](https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html).

Check out the official [gitter-channel](/chat.html) for Blaubot to get help or keep in touch with other Blaubot users.


text:
tpm_plugins_variable_name="@tpm_plugins"

# manually expanding tilde char or `$HOME` variable.
_manual_expansion() {
	local path="$1"
	local expanded_tilde="${path/#\~/$HOME}"
	echo "${expanded_tilde/#\$HOME/$HOME}"
}

_tpm_path() {
	local string_path="$(tmux start-server\; show-environment -g TMUX_PLUGIN_MANAGER_PATH | cut -f2 -d=)/"
	_manual_expansion "$string_path"
}

_CACHED_TPM_PATH="$(_tpm_path)"

_tmux_conf_contents() {
	cat /etc/tmux.conf ~/.tmux.conf 2>/dev/null
	if [ "$1" == "full" ]; then # also output content from sourced files
		local file
		for file in $(_sourced_files); do
			cat $(_manual_expansion "$file") 2>/dev/null
		done
	fi
}

# return files sourced from tmux config files
_sourced_files() {
	_tmux_conf_contents |
		awk '/^[ \t]*source(-file)? +/ { gsub(/'\''/,""); gsub(/'\"'/,""); print $2 }'
}

# Want to be able to abort in certain cases
trap "exit 1" TERM
export TOP_PID=$$

_fatal_error_abort() {
	echo >&2 "Aborting."
	kill -s TERM $TOP_PID
}

# PUBLIC FUNCTIONS BELOW

tpm_path() {
	if [ "$_CACHED_TPM_PATH" == "/" ]; then
		echo >&2 "FATAL: Tmux Plugin Manager not configured in tmux.conf"
		_fatal_error_abort
	fi
	echo "$_CACHED_TPM_PATH"
}

tpm_plugins_list_helper() {
	# lists plugins from @tpm_plugins option
	echo "$(tmux start-server\; show-option -gqv "$tpm_plugins_variable_name")"

	# read set -g @plugin "tmux-plugins/tmux-example-plugin" entries
	_tmux_conf_contents "full" |
		awk '/^[ \t]*set(-option)? +-g +@plugin/ { gsub(/'\''/,""); gsub(/'\"'/,""); print $4 }'
}

# Allowed plugin name formats:
# 1. "git://github.com/user/plugin_name.git"
# 2. "user/plugin_name"
plugin_name_helper() {
	local plugin="$1"
	# get only the part after the last slash, e.g. "plugin_name.git"
	local plugin_basename="$(basename "$plugin")"
	# remove ".git" extension (if it exists) to get only "plugin_name"
	local plugin_name="${plugin_basename%.git}"
	echo "$plugin_name"
}

plugin_path_helper() {
	local plugin="$1"
	local plugin_name="$(plugin_name_helper "$plugin")"
	echo "$(tpm_path)${plugin_name}/"
}

plugin_already_installed() {
	local plugin="$1"
	local plugin_path="$(plugin_path_helper "$plugin")"
	[ -d "$plugin_path" ] &&
		cd "$plugin_path" &&
		git remote >/dev/null 2>&1
}