text:
#include "threads/file_lock.h"

#include "errors/fatal.h"
#include "threads/thread.h"
#include "utility/validate_aligned_storage.h"

#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include <windows.h>
#undef Yield
#endif

namespace CppCommon {

//! @cond INTERNALS

// In case we are on a system with glibc version earlier than 2.20
#ifndef F_OFD_GETLK
#define F_OFD_GETLK  36
#define F_OFD_SETLK  37
#define F_OFD_SETLKW 38
#endif

class FileLock::Impl
{
public:
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
    Impl() : _file(0) {}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
    Impl() : _file(nullptr) {}
#endif

    ~Impl()
    {
        try
        {
            Reset();
        }
        catch (const SystemException& ex)
        {
            fatality(SystemException(ex.string()));
        }
    }

    const Path& path() const noexcept { return _path; }

    void Assign(const Path& path)
    {
        // Reset the previous file-lock
        Reset();

        _path = path;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        _file = open(_path.string().c_str(), O_CREAT | O_RDWR, 0644);
        if (_file < 0)
            throwex FileSystemException("Cannot create or open file-lock file!").Attach(path);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Retries in CreateFile, see http://support.microsoft.com/kb/316609
        const std::wstring wpath = _path.wstring();
        const int attempts = 1000;
        const int sleep = 100;
        for (int attempt = 0; attempt < attempts; ++attempt)
        {
            _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
            if (_file == INVALID_HANDLE_VALUE)
            {
                Sleep(sleep);
                continue;
            }
            return;
        }
        throwex FileSystemException("Cannot create or open file-lock file!").Attach(path);
#endif
    }

    void Reset()
    {
        if (!_file)
            return;

#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = close(_file);
        if (result != 0)
            fatality(FileSystemException("Cannot close the file-lock descriptor!").Attach(_path));
        _file = 0;

        // Remove the file-lock file
        unlink(_path.string().c_str());
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        if (!CloseHandle(_file))
            fatality(FileSystemException("Cannot close the file-lock handle!").Attach(_path));
        _file = nullptr;
#endif
    }

    bool TryLockRead()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_RDLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLK, &lock);
        if (result == -1)
        {
           if  (errno == EAGAIN)
               return false;
           else
               throwex FileSystemException("Failed to try lock for read!").Attach(_path);
        }
        else
            return true;
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_SH | LOCK_NB);
        if (result != 0)
        {
           if  (errno == EWOULDBLOCK)
               return false;
           else
               throwex FileSystemException("Failed to try lock for read!").Attach(_path);
        }
        else
            return true;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0;
#endif
    }

    bool TryLockWrite()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_WRLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLK, &lock);
        if (result == -1)
        {
           if  (errno == EAGAIN)
               return false;
           else
               throwex FileSystemException("Failed to try lock for write!").Attach(_path);
        }
        else
            return true;
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_EX | LOCK_NB);
        if (result != 0)
        {
           if  (errno == EWOULDBLOCK)
               return false;
           else
               throwex FileSystemException("Failed to try lock for write!").Attach(_path);
        }
        else
            return true;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0;
#endif
    }

    void LockRead()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_RDLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLKW, &lock);
        if (result == -1)
            throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_SH);
        if (result != 0)
            throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped))
            throwex FileSystemException("Failed to lock for read!").Attach(_path);
#endif
    }

    void LockWrite()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_WRLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLKW, &lock);
        if (result == -1)
            throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_EX);
        if (result != 0)
            throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))
            throwex FileSystemException("Failed to lock for write!").Attach(_path);
#endif
    }

    void UnlockRead()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_UNLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLK, &lock);
        if (result != 0)
            throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_UN);
        if (result != 0)
            throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
            throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#endif
    }

    void UnlockWrite()
    {
#if defined(linux) || defined(__linux) || defined(__linux__)
        struct flock lock;
        lock.l_type = F_UNLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_pid = 0;
        int result = fcntl(_file, F_OFD_SETLK, &lock);
        if (result != 0)
            throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = flock(_file, LOCK_UN);
        if (result != 0)
            throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)  || defined(__CYGWIN__)
        OVERLAPPED overlapped;
        ZeroMemory(&overlapped, sizeof(OVERLAPPED));
        if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
            throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#endif
    }

private:
    Path _path;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
    int _file;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
    HANDLE _file;
#endif
};

//! @endcond

FileLock::FileLock()
{
    // Check implementation storage parameters
    [[maybe_unused]] ValidateAlignedStorage<sizeof(Impl), alignof(Impl), StorageSize, StorageAlign> _;
    static_assert((StorageSize >= sizeof(Impl)), "FileLock::StorageSize must be increased!");
    static_assert(((StorageAlign % alignof(Impl)) == 0), "FileLock::StorageAlign must be adjusted!");

    // Create the implementation instance
    new(&_storage)Impl();
}

FileLock::FileLock(const Path& path) : FileLock()
{
    // Check implementation storage parameters
    [[maybe_unused]] ValidateAlignedStorage<sizeof(Impl), alignof(Impl), StorageSize, StorageAlign> _;
    static_assert((StorageSize >= sizeof(Impl)), "FileLock::StorageSize must be increased!");
    static_assert(((StorageAlign % alignof(Impl)) == 0), "FileLock::StorageAlign must be adjusted!");

    // Create the implementation instance
    new(&_storage)Impl();

    Assign(path);
}

FileLock::~FileLock()
{
    // Delete the implementation instance
    reinterpret_cast<Impl*>(&_storage)->~Impl();
}

FileLock& FileLock::operator=(const Path& path)
{
    Assign(path);
    return *this;
}

const Path& FileLock::path() const noexcept { return impl().path(); }

void FileLock::Assign(const Path& path) { impl().Assign(path); }
void FileLock::Reset() { impl().Reset(); }

bool FileLock::TryLockRead() { return impl().TryLockRead(); }
bool FileLock::TryLockWrite() { return impl().TryLockWrite(); }

bool FileLock::TryLockReadFor(const Timespan& timespan)
{
    // Calculate a finish timestamp
    Timestamp finish = NanoTimestamp() + timespan;

    // Try to acquire read lock at least one time
    if (TryLockRead())
        return true;
    else
    {
        // Try lock or yield for the given timespan
        while (NanoTimestamp() < finish)
        {
            if (TryLockRead())
                return true;
            else
                Thread::Yield();
        }

        // Failed to acquire read lock
        return false;
    }
}

bool FileLock::TryLockWriteFor(const Timespan& timespan)
{
    // Calculate a finish timestamp
    Timestamp finish = NanoTimestamp() + timespan;

    // Try to acquire write lock at least one time
    if (TryLockWrite())
        return true;
    else
    {
        // Try lock or yield for the given timespan
        while (NanoTimestamp() < finish)
        {
            if (TryLockWrite())
                return true;
            else
                Thread::Yield();
        }

        // Failed to acquire write lock
        return false;
    }
}

void FileLock::LockRead() { impl().LockRead(); }
void FileLock::LockWrite() { impl().LockWrite(); }
void FileLock::UnlockRead() { impl().UnlockRead(); }
void FileLock::UnlockWrite() { impl().UnlockWrite(); }

} // namespace CppCommon


text:
export function handleApiErrors (response) {
  if (!response.ok) throw Error(response.statusText)
  return response
}

redpajama_set_name: RedPajamaGithub


text:
package ny2.ats.core.exception;

import ny2.ats.core.event.EventType;

/**
 * 想定外のイベントを受信した際に出力するException
 */
public class UnExpectedEventException extends ATSRuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 想定外のイベント名を出力する
     * @param eventType
     */
    public UnExpectedEventException(EventType eventType) {
        super("Received Not Registered Event: " + eventType.name());
    }

    public UnExpectedEventException(String message) {
        super(message);
    }

}


text:
var vows = require('vows')
var assert = require('assert')
var names = require('../../lib/scale/names')

vows.describe('scale.names').addBatch({
  'all names': function () {
    assert.equal(names().length, 89)
  },
  'by notes': function () {
    assert.deepEqual(names('C D E F G A B C'), ['C major', 'C ionian'])
    assert.deepEqual(names('D E F G A B C'), ['D dorian'])
  },
  'with aliases': function () {
    assert.deepEqual(names('G A B C D E F G'), [ 'G mixolydian', 'G dominant' ])
  }
}).export(module)


text:
"use strict";

var ClientManager = new require("../clientManager");
var program = require("commander");
var colors = require("colors/safe");
var server = require("../server");
var Helper = require("../helper");

program
	.command("start")
	.option("-H, --host <ip>", "host")
	.option("-P, --port <port>", "port")
	.option("-B, --bind <ip>", "bind")
	.option("    --public", "mode")
	.option("    --private", "mode")
	.description("Start the server")
	.action(function(options) {
		var users = new ClientManager().getUsers();

		var mode = Helper.config.public;
		if (options.public) {
			mode = true;
		} else if (options.private) {
			mode = false;
		}

		if (!mode && !users.length && !Helper.config.ldap.enable) {
			log.warn("No users found.");
			log.info(`Create a new user with ${colors.bold("lounge add <name>")}.`);

			return;
		}

		Helper.config.host = options.host || Helper.config.host;
		Helper.config.port = options.port || Helper.config.port;
		Helper.config.bind = options.bind || Helper.config.bind;
		Helper.config.public = mode;

		server();
	});


text:
This gulp plugin is based on [gulp-hihlight](http://github.com/johannestroeger/gulp-highlight). It has been modified to allow for manual language and options configuration.

`gulp-snippet-highlight` Uses [highlight.js](https://highlightjs.org/) to compile single html snippets. If no `language` option is specified, your snippet will be compiled with an `html` code highlighter as a default.

You can also pass in highlight.js configuration object as per highlight.js [docs](http://highlightjs.readthedocs.org/en/latest/api.html#configure-options):
- `tabReplace`: a string used to replace TAB characters in indentation.
- `useBR`: a flag to generate <br> tags instead of new-line characters in the output, useful when code is marked up using a non-pre container.
- `classPrefix`: a string prefix added before class names in the generated markup, used for backwards compatibility with stylesheets.
- `languages`: an array of language names and aliases restricting auto detection to only these languages.
Accepts an object r

## Install

```
npm install --save-dev gulp-snippet-highlight
```

## Example

```js
var gulp = require('gulp');
var highlight = require('gulp-snippet-highlight');

gulp.task('highlight-snippet', function () {
  return gulp.src("./src/snippet.html")
    .pipe(highlight({
       language: "html",
       configure: {},
    }))
    .pipe(gulp.dest("./docs"));
});

```

## License

MIT © [Kris Zima](https://github.com/kzima)


text:
if (typeof Array.prototype.forEach != 'function') {
	Array.prototype.forEach = function(callback){
		for (var i = 0; i < this.length; i++){
			callback.apply(this, [this[i], i, this]);
		}
	};
}
if (!document.querySelectorAll) {
    document.querySelectorAll = function (selectors) {
        var style = document.createElement('style'), elements = [], element;
        document.documentElement.firstChild.appendChild(style);
        document._qsa = [];

        style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
        window.scrollBy(0, 0);
        style.parentNode.removeChild(style);

        while (document._qsa.length) {
            element = document._qsa.shift();
            element.style.removeAttribute('x-qsa');
            elements.push(element);
        }
        document._qsa = null;
        return elements;
    };
}
if (!document.getElementsByClassName) {
  document.getElementsByClassName = function(search) {
    var d = document, elements, pattern, i, results = [];
    if (d.querySelectorAll) { // IE8
      return d.querySelectorAll("." + search);
    }
    if (d.evaluate) { // IE6, IE7
      pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
      elements = d.evaluate(pattern, d, null, 0, null);
      while ((i = elements.iterateNext())) {
        results.push(i);
      }
    } else {
      elements = d.getElementsByTagName("*");
      pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
      for (i = 0; i < elements.length; i++) {
        if ( pattern.test(elements[i].className) ) {
          results.push(elements[i]);
        }
      }
    }
    return results;
  }
}