/*jslint browser: true*/
/*global require, exports*/

/**
 * Try parsing simple regular expression to syntax tree.
 *
 * Basic grammars:
 *   Empty: S -> ϵ
 *   Cat:   S -> S S
 *   Or:    S -> S | S
 *   Star:  S -> S *
 *   Text:  S -> [0-9a-zA-Z]
 *   S -> ( S )
 *
 * Extension:
 *   Plus:  S -> S + -> S S *
 *   Ques:  S -> S ? -> (S | ϵ)
 *
 * @param {string} text The input regular expression
 * @return {string|object} Returns a string that is an error message if failed to parse the expression,
 *                         otherwise returns an object which is the syntax tree.
 */
function parseRegex(text) {
    'use strict';
    function parseSub(text, begin, end, first) {
        var i,
            sub,
            last = 0,
            node = {'begin': begin, 'end': end},
            virNode,
            tempNode,
            stack = 0,
            parts = [];
        if (text.length === 0) {
            return 'Error: empty input at ' + begin + '.';
        }
        if (first) {
            for (i = 0; i <= text.length; i += 1) {
                if (i === text.length || (text[i] === '|' && stack === 0)) {
                    if (last === 0 && i === text.length) {
                        return parseSub(text, begin + last, begin + i, false);
                    }
                    sub = parseSub(text.substr(last, i - last), begin + last, begin + i, true);
                    if (typeof sub === 'string') {
                        return sub;
                    }
                    parts.push(sub);
                    last = i + 1;
                } else if (text[i] === '(') {
                    stack += 1;
                } else if (text[i] === ')') {
                    stack -= 1;
                }
            }
            if (parts.length === 1) {
                return parts[0];
            }
            node.type = 'or';
            node.parts = parts;
        } else {
            for (i = 0; i < text.length; i += 1) {
                if (text[i] === '(') {
                    last = i + 1;
                    i += 1;
                    stack = 1;
                    while (i < text.length && stack !== 0) {
                        if (text[i] === '(') {
                            stack += 1;
                        } else if (text[i] === ')') {
                            stack -= 1;
                        }
                        i += 1;
                    }
                    if (stack !== 0) {
                        return 'Error: missing right bracket for ' + (begin + last) + '.';
                    }
                    i -= 1;
                    sub = parseSub(text.substr(last, i - last), begin + last, begin + i, true);
                    if (typeof sub === 'string') {
                        return sub;
                    }
                    sub.begin -= 1;
                    sub.end += 1;
                    parts.push(sub);
                } else if (text[i] === '*') {
                    if (parts.length === 0) {
                        return 'Error: unexpected * at ' + (begin + i) + '.';
                    }
                    tempNode = {'begin': parts[parts.length - 1].begin, 'end': parts[parts.length - 1].end + 1};
                    tempNode.type = 'star';
                    tempNode.sub = parts[parts.length - 1];
                    parts[parts.length - 1] = tempNode;
                } else if (text[i] === '+') {
                    if (parts.length === 0) {
                        return 'Error: unexpected + at ' + (begin + i) + '.';
                    }
                    virNode = {'begin': parts[parts.length - 1].begin, 'end': parts[parts.length - 1].end + 1};
                    virNode.type = 'star';
                    virNode.sub = parts[parts.length - 1];
                    tempNode = {'begin': parts[parts.length - 1].begin, 'end': parts[parts.length - 1].end + 1};
                    tempNode.type = 'cat';
                    tempNode.parts = [parts[parts.length - 1], virNode];
                    parts[parts.length - 1] = tempNode;
                } else if (text[i] === '?') {
                    if (parts.length === 0) {
                        return 'Error: unexpected + at ' + (begin + i) + '.';
                    }
                    virNode = {'begin': parts[parts.length - 1].begin, 'end': parts[parts.length - 1].end + 1};
                    virNode.type = 'empty';
                    virNode.sub = parts[parts.length - 1];
                    tempNode = {'begin': parts[parts.length - 1].begin, 'end': parts[parts.length - 1].end + 1};
                    tempNode.type = 'or';
                    tempNode.parts = [parts[parts.length - 1], virNode];
                    parts[parts.length - 1] = tempNode;
                } else if (text[i] === 'ϵ') {
                    tempNode = {'begin': begin + i, 'end': begin + i + 1};
                    tempNode.type = 'empty';
                    parts.push(tempNode);
                } else {
                    tempNode = {'begin': begin + i, 'end': begin + i + 1};
                    tempNode.type = 'text';
                    tempNode.text = text[i];
                    parts.push(tempNode);
                }
            }
            if (parts.length === 1) {
                return parts[0];
            }
            node.type = 'cat';
            node.parts = parts;
        }
        return node;
    }
    return parseSub(text, 0, text.length, true);
}

/**
 * Convert regular expression to nondeterministic finite automaton.
 *
 * @param {string} text @see parseRegex()
 * @return {object|string}
 */
function regexToNfa(text) {
    'use strict';
    function generateGraph(node, start, end, count) {
        var i, last, temp, tempStart, tempEnd;
        if (!start.hasOwnProperty('id')) {
            start.id = count;
            count += 1;
        }
        switch (node.type) {
        case 'empty':
            start.edges.push(['ϵ', end]);
            break;
        case 'text':
            start.edges.push([node.text, end]);
            break;
        case 'cat':
            last = start;
            for (i = 0; i < node.parts.length - 1; i += 1) {
                temp = {'type': '', 'edges': []};
                count = generateGraph(node.parts[i], last, temp, count);
                last = temp;
            }
            count = generateGraph(node.parts[node.parts.length - 1], last, end, count);
            break;
        case 'or':
            for (i = 0; i < node.parts.length; i += 1) {
                tempStart = {'type': '', 'edges': []};
                tempEnd = {'type': '', 'edges': [['ϵ', end]]};
                start.edges.push(['ϵ', tempStart]);
                count = generateGraph(node.parts[i], tempStart, tempEnd, count);
            }
            break;
        case 'star':
            tempStart = {'type': '', 'edges': []};
            tempEnd = {'type': '', 'edges': [['ϵ', tempStart], ['ϵ', end]]};
            start.edges.push(['ϵ', tempStart]);
            start.edges.push(['ϵ', end]);
            count = generateGraph(node.sub, tempStart, tempEnd, count);
            break;
        }
        if (!end.hasOwnProperty('id')) {
            end.id = count;
            count += 1;
        }
        return count;
    }
    var ast = parseRegex(text),
        start = {'type': 'start', 'edges': []},
        accept = {'type': 'accept', 'edges': []};
    if (typeof ast === 'string') {
        return ast;
    }
    generateGraph(ast, start, accept, 0);
    return start;
}

/**
 * Convert nondeterministic finite automaton to deterministic finite automaton.
 *
 * @param {object} nfa @see regexToNfa(), the function assumes that the given NFA is valid.
 * @return {object} dfa Returns the first element of the DFA.
 */
function nfaToDfa(nfa) {
    'use strict';
    function getClosure(nodes) {
        var i,
            closure = [],
            stack = [],
            symbols = [],
            type = '',
            top;
        for (i = 0; i < nodes.length; i += 1) {
            stack.push(nodes[i]);
            closure.push(nodes[i]);
            if (nodes[i].type === 'accept') {
                type = 'accept';
            }
        }
        while (stack.length > 0) {
            top = stack.pop();
            for (i = 0; i < top.edges.length; i += 1) {
                if (top.edges[i][0] === 'ϵ') {
                    if (closure.indexOf(top.edges[i][1]) < 0) {
                        stack.push(top.edges[i][1]);
                        closure.push(top.edges[i][1]);
                        if (top.edges[i][1].type === 'accept') {
                            type = 'accept';
                        }
                    }
                } else {
                    if (symbols.indexOf(top.edges[i][0]) < 0) {
                        symbols.push(top.edges[i][0]);
                    }
                }
            }
        }
        closure.sort(function (a, b) {
            return a.id - b.id;
        });
        symbols.sort();
        return {
            'key': closure.map(function (x) {
                return x.id;
            }).join(','),
            'items': closure,
            'symbols': symbols,
            'type': type,
            'edges': [],
            'trans': {}
        };
    }
    function getClosedMove(closure, symbol) {
        var i,
            j,
            node,
            nexts = [];
        for (i = 0; i < closure.items.length; i += 1) {
            node = closure.items[i];
            for (j = 0; j < node.edges.length; j += 1) {
                if (symbol === node.edges[j][0]) {
                    if (nexts.indexOf(node.edges[j][1]) < 0) {
                        nexts.push(node.edges[j][1]);
                    }
                }
            }
        }
        return getClosure(nexts);
    }
    function toAlphaCount(n) {
        var a = 'A'.charCodeAt(0),
            z = 'Z'.charCodeAt(0),
            len = z - a + 1,
            s = '';
        while (n >= 0) {
            s = String.fromCharCode(n % len + a) + s;
            n = Math.floor(n / len) - 1;
        }
        return s;
    }
    var i,
        first = getClosure([nfa]),
        states = {},
        front = 0,
        top,
        closure,
        queue = [first],
        count = 0;
    first.id = toAlphaCount(count);
    states[first.key] = first;
    while (front < queue.length) {
        top = queue[front];
        front += 1;
        for (i = 0; i < top.symbols.length; i += 1) {
            closure = getClosedMove(top, top.symbols[i]);
            if (!states.hasOwnProperty(closure.key)) {
                count += 1;
                closure.id = toAlphaCount(count);
                states[closure.key] = closure;
                queue.push(closure);
            }
            top.trans[top.symbols[i]] = states[closure.key];
            top.edges.push([top.symbols[i], states[closure.key]]);
        }
    }
    return first;
}

/**
 * Convert the DFA to its minimum form using Hopcroft's algorithm.
 *
 * @param {object} dfa @see nfaToDfa(), the function assumes that the given DFA is valid.
 * @return {object} dfa Returns the first element of the minimum DFA.
 */
function minDfa(dfa) {
    'use strict';
    function getReverseEdges(start) {
        var i, top, symbol, next,
            front = 0,
            queue = [start],
            visited = {},
            symbols = {},   // The input alphabet
            idMap = {},     // Map id to states
            revEdges = {};  // Map id to the ids which connects to the id with an alphabet
        visited[start.id] = true;
        while (front < queue.length) {
            top = queue[front];
            front += 1;
            idMap[top.id] = top;
            for (i = 0; i < top.symbols.length; i += 1) {
                symbol = top.symbols[i];
                if (!symbols.hasOwnProperty(symbol)) {
                    symbols[symbol] = true;
                }
                next = top.trans[symbol];
                if (!revEdges.hasOwnProperty(next.id)) {
                    revEdges[next.id] = {};
                }
                if (!revEdges[next.id].hasOwnProperty(symbol)) {
                    revEdges[next.id][symbol] = [];
                }
                revEdges[next.id][symbol].push(top.id);
                if (!visited.hasOwnProperty(next.id)) {
                    visited[next.id] = true;
                    queue.push(next);
                }
            }
        }
        return [Object.keys(symbols), idMap, revEdges];
    }
    function hopcroft(symbols, idMap, revEdges) {
        var i, j, k, keys, key, key1, key2, top, group1, group2, symbol, revGroup,
            ids = Object.keys(idMap).sort(),
            partitions = {},
            front = 0,
            queue = [],
            visited = {};
        group1 = [];
        group2 = [];
        for (i = 0; i < ids.length; i += 1) {
            if (idMap[ids[i]].type === 'accept') {
                group1.push(ids[i]);
            } else {
                group2.push(ids[i]);
            }
        }
        key = group1.join(',');
        partitions[key] = group1;
        queue.push(key);
        visited[key] = 0;
        if (group2.length !== 0) {
            key = group2.join(',');
            partitions[key] = group2;
            queue.push(key);
        }
        while (front < queue.length) {
            top = queue[front];
            front += 1;
            if (top) {
                top = top.split(',');
                for (i = 0; i < symbols.length; i += 1) {
                    symbol = symbols[i];
                    revGroup = {};
                    for (j = 0; j < top.length; j += 1) {
                        if (revEdges.hasOwnProperty(top[j]) && revEdges[top[j]].hasOwnProperty(symbol)) {
                            for (k = 0; k < revEdges[top[j]][symbol].length; k += 1) {
                                revGroup[revEdges[top[j]][symbol][k]] = true;
                            }
                        }
                    }
                    keys = Object.keys(partitions);
                    for (j = 0; j < keys.length; j += 1) {
                        key = keys[j];
                        group1 = [];
                        group2 = [];
                        for (k = 0; k < partitions[key].length; k += 1) {
                            if (revGroup.hasOwnProperty(partitions[key][k])) {
                                group1.push(partitions[key][k]);
                            } else {
                                group2.push(partitions[key][k]);
                            }
                        }
                        if (group1.length !== 0 && group2.length !== 0) {
                            delete partitions[key];
                            key1 = group1.join(',');
                            key2 = group2.join(',');
                            partitions[key1] = group1;
                            partitions[key2] = group2;
                            if (visited.hasOwnProperty(key1)) {
                                queue[visited[key1]] = null;
                                visited[key1] = queue.length;
                                queue.push(key1);
                                visited[key2] = queue.length;
                                queue.push(key2);
                            } else if (group1.length <= group2.length) {
                                visited[key1] = queue.length;
                                queue.push(key1);
                            } else {
                                visited[key2] = queue.length;
                                queue.push(key2);
                            }
                        }
                    }
                }
            }
        }
        return Object.values(partitions);
    }
    function buildMinNfa(start, partitions, idMap, revEdges) {
        var i, j, temp, node, symbol,
            nodes = [],
            group = {},
            edges = {};
        partitions.sort(function (a, b) {
            var ka = a.join(','), kb = b.join(',');
            if (ka < kb) {
                return -1;
            }
            if (ka > kb) {
                return 1;
            }
            return 0;
        });
        for (i = 0; i < partitions.length; i += 1) {
            if (partitions[i].indexOf(start.id) >= 0) {
                if (i > 0) {
                    temp = partitions[i];
                    partitions[i] = partitions[0];
                    partitions[0] = temp;
                }
                break;
            }
        }
        for (i = 0; i < partitions.length; i += 1) {
            node = {
                id: (i + 1).toString(),
                key: partitions[i].join(','),
                items: [],
                symbols: [],
                type: idMap[partitions[i][0]].type,
                edges: [],
                trans: {},
            };
            for (j = 0; j < partitions[i].length; j += 1) {
                node.items.push(idMap[partitions[i][j]]);
                group[partitions[i][j]] = i;
            }
            edges[i] = {};
            nodes.push(node);
        }
        Object.keys(revEdges).forEach(function (to) {
            Object.keys(revEdges[to]).forEach(function (symbol) {
                revEdges[to][symbol].forEach(function (from) {
                    if (!edges[group[from]].hasOwnProperty(group[to])) {
                        edges[group[from]][group[to]] = {};
                    }
                    edges[group[from]][group[to]][symbol] = true;
                });
            });
        });
        Object.keys(edges).forEach(function (from) {
            Object.keys(edges[from]).forEach(function (to) {
                symbol = Object.keys(edges[from][to]).sort().join(',');
                nodes[from].symbols.push(symbol);
                nodes[from].edges.push([symbol, nodes[to]]);
                nodes[from].trans[symbol] = nodes[to];
            });
        });
        return nodes[0];
    }
    var edgesTuple = getReverseEdges(dfa),
        symbols = edgesTuple[0],
        idMap = edgesTuple[1],
        revEdges = edgesTuple[2],
        partitions = hopcroft(symbols, idMap, revEdges);
    return buildMinNfa(dfa, partitions, idMap, revEdges);
}

if (typeof require === 'function') {
    exports.parseRegex = parseRegex;
    exports.regexToNfa = regexToNfa;
    exports.nfaToDfa = nfaToDfa;
    exports.minDfa = minDfa;
}

{'repo_name': 'CyberZHG/toolbox', 'stars': '319', 'repo_language': 'JavaScript', 'file_name': 'left_fact.js', 'mime_type': 'text/plain', 'hash': 6581356309297123670, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('reviewers', '0003_auto_20150727_1017'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='editorsubscription',
            name='addon',
        ),
        migrations.RemoveField(
            model_name='editorsubscription',
            name='user',
        ),
        migrations.DeleteModel(
            name='EditorSubscription',
        ),
    ]

{'repo_name': 'mozilla/zamboni', 'stars': '482', 'repo_language': 'Python', 'file_name': 'test_users.json', 'mime_type': 'text/plain', 'hash': -5004590961350179181, 'source_dataset': 'data'}


// Copyright 2019 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.

package vfs

import "sync/atomic"

// SyncingFileOptions holds the options for a syncingFile.
type SyncingFileOptions struct {
	BytesPerSync    int
	PreallocateSize int
}

type syncingFile struct {
	File
	fd              uintptr
	useSyncRange    bool
	bytesPerSync    int64
	preallocateSize int64
	atomic          struct {
		// The offset at which dirty data has been written.
		offset int64
		// The offset at which data has been synced. Note that if SyncFileRange is
		// being used, the periodic syncing of data during writing will only ever
		// sync up to offset-1MB. This is done to avoid rewriting the tail of the
		// file multiple times, but has the side effect of ensuring that Close will
		// sync the file's metadata.
		syncOffset int64
	}
	preallocatedBlocks int64
	syncData           func() error
	syncTo             func(offset int64) error
	timeDiskOp         func(op func())
}

// NewSyncingFile wraps a writable file and ensures that data is synced
// periodically as it is written. The syncing does not provide persistency
// guarantees for these periodic syncs, but is used to avoid latency spikes if
// the OS automatically decides to write out a large chunk of dirty filesystem
// buffers. The underlying file is fully synced upon close.
func NewSyncingFile(f File, opts SyncingFileOptions) File {
	s := &syncingFile{
		File:            f,
		bytesPerSync:    int64(opts.BytesPerSync),
		preallocateSize: int64(opts.PreallocateSize),
	}
	// Ensure a file that is opened and then closed will be synced, even if no
	// data has been written to it.
	s.atomic.syncOffset = -1

	type fd interface {
		Fd() uintptr
	}
	if d, ok := f.(fd); ok {
		s.fd = d.Fd()
	}
	type dhChecker interface {
		timeDiskOp(op func())
	}
	if d, ok := f.(dhChecker); ok {
		s.timeDiskOp = d.timeDiskOp
	} else {
		s.timeDiskOp = func(op func()) {
			op()
		}
	}

	s.init()

	if s.syncData == nil {
		s.syncData = s.File.Sync
	}
	return s
}

// NB: syncingFile.Write is unsafe for concurrent use!
func (f *syncingFile) Write(p []byte) (n int, err error) {
	_ = f.preallocate(atomic.LoadInt64(&f.atomic.offset) + int64(n))

	n, err = f.File.Write(p)
	if err != nil {
		return n, err
	}
	// The offset is updated atomically so that it can be accessed safely from
	// Sync.
	atomic.AddInt64(&f.atomic.offset, int64(n))
	if err := f.maybeSync(); err != nil {
		return 0, err
	}
	return n, nil
}

func (f *syncingFile) preallocate(offset int64) error {
	if f.fd == 0 || f.preallocateSize == 0 {
		return nil
	}

	newPreallocatedBlocks := (offset + f.preallocateSize - 1) / f.preallocateSize
	if newPreallocatedBlocks <= f.preallocatedBlocks {
		return nil
	}

	length := f.preallocateSize * (newPreallocatedBlocks - f.preallocatedBlocks)
	offset = f.preallocateSize * f.preallocatedBlocks
	f.preallocatedBlocks = newPreallocatedBlocks
	return preallocExtend(f.fd, offset, length)
}

func (f *syncingFile) ratchetSyncOffset(offset int64) {
	for {
		syncOffset := atomic.LoadInt64(&f.atomic.syncOffset)
		if syncOffset >= offset {
			return
		}
		if atomic.CompareAndSwapInt64(&f.atomic.syncOffset, syncOffset, offset) {
			return
		}
	}
}

func (f *syncingFile) Sync() error {
	// We update syncOffset (atomically) in order to avoid spurious syncs in
	// maybeSync. Note that even if syncOffset is larger than the current file
	// offset, we still need to call the underlying file's sync for persistence
	// guarantees (which are not provided by sync_file_range).
	f.ratchetSyncOffset(atomic.LoadInt64(&f.atomic.offset))
	return f.syncData()
}

func (f *syncingFile) maybeSync() error {
	if f.bytesPerSync <= 0 {
		return nil
	}

	// From the RocksDB source:
	//
	//   We try to avoid sync to the last 1MB of data. For two reasons:
	//   (1) avoid rewrite the same page that is modified later.
	//   (2) for older version of OS, write can block while writing out
	//       the page.
	//   Xfs does neighbor page flushing outside of the specified ranges. We
	//   need to make sure sync range is far from the write offset.
	const syncRangeBuffer = 1 << 20 // 1 MB
	offset := atomic.LoadInt64(&f.atomic.offset)
	if offset <= syncRangeBuffer {
		return nil
	}

	const syncRangeAlignment = 4 << 10 // 4 KB
	syncToOffset := offset - syncRangeBuffer
	syncToOffset -= syncToOffset % syncRangeAlignment
	syncOffset := atomic.LoadInt64(&f.atomic.syncOffset)
	if syncToOffset < 0 || (syncToOffset-syncOffset) < f.bytesPerSync {
		return nil
	}

	if f.fd == 0 {
		return f.Sync()
	}

	// Note that syncTo will always be called with an offset < atomic.offset. The
	// syncTo implementation may choose to sync the entire file (i.e. on OSes
	// which do not support syncing a portion of the file). The syncTo
	// implementation must call ratchetSyncOffset with as much of the file as it
	// has synced.
	return f.syncTo(syncToOffset)
}

func (f *syncingFile) Close() error {
	// Sync any data that has been written but not yet synced. Note that if
	// SyncFileRange was used, atomic.syncOffset will be less than
	// atomic.offset. See syncingFile.syncToRange.
	if atomic.LoadInt64(&f.atomic.offset) > atomic.LoadInt64(&f.atomic.syncOffset) {
		if err := f.Sync(); err != nil {
			return err
		}
	}
	return f.File.Close()
}

{'repo_name': 'cockroachdb/pebble', 'stars': '716', 'repo_language': 'Go', 'file_name': 'rocksdb_disabled.go', 'mime_type': 'text/plain', 'hash': -8858905775425122142, 'source_dataset': 'data'}


// Copyright (c) 2016-2020 Daniel Frey and Dr. Colin Hirsch
// Please see LICENSE for license or visit https://github.com/taocpp/taopq/

#ifndef SRC_TEST_GETENV_HPP  // NOLINT(llvm-header-guard)
#define SRC_TEST_GETENV_HPP

// This is an internal header used for unit-tests.

#include <cstdlib>
#include <stdexcept>
#include <string>

#if defined( _MSC_VER )
#include <memory>
#endif

namespace tao::pq::internal
{
#if defined( _MSC_VER )

   [[nodiscard]] inline auto getenv( const std::string& name ) -> std::string
   {
      char* buf = nullptr;
      std::size_t sz = 0;
      if( _dupenv_s( &buf, &sz, name.c_str() ) == 0 && buf != nullptr ) {
         const std::unique_ptr< char, decltype( &std::free ) > up( buf, &std::free );
         return std::string( up.get(), sz );
      }
      throw std::runtime_error( "environment variable not found: " + name );
   }

   [[nodiscard]] inline auto getenv( const std::string& name, const std::string& default_value ) -> std::string
   {
      char* buf = nullptr;
      std::size_t sz = 0;
      if( _dupenv_s( &buf, &sz, name.c_str() ) == 0 && buf != nullptr ) {
         const std::unique_ptr< char, decltype( &std::free ) > up( buf, &std::free );
         return std::string( up.get(), sz );
      }
      return default_value;
   }

#else

   [[nodiscard]] inline auto getenv( const std::string& name ) -> std::string
   {
      const char* result = std::getenv( name.c_str() );
      return ( result != nullptr ) ? result : throw std::runtime_error( "environment variable not found: " + name );
   }

   [[nodiscard]] inline auto getenv( const std::string& name, const std::string& default_value ) -> std::string
   {
      const char* result = std::getenv( name.c_str() );
      return ( result != nullptr ) ? result : default_value;
   }

#endif

}  // namespace tao::pq::internal

#endif

{'repo_name': 'taocpp/taopq', 'stars': '135', 'repo_language': 'C++', 'file_name': 'taopqConfig.cmake.in', 'mime_type': 'text/plain', 'hash': 3559415618147100641, 'source_dataset': 'data'}


/*!
 * Copyright 2010 - 2017 Hitachi Vantara.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.pentaho.di.purge;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import junit.framework.Assert;

import org.apache.log4j.Level;
import org.junit.Test;

public class PurgeUtilityLoggerTest {

  final static String PURGE_PATH = "purgePath";

  @SuppressWarnings( "null" )
  @Test
  public void textLoggerTest() {
    OutputStream out = new ByteArrayOutputStream();
    PurgeUtilityLog.layoutClass = PurgeUtilityTextLayout.class;
    PurgeUtilityLogger.createNewInstance( out, PURGE_PATH, Level.DEBUG );
    PurgeUtilityLogger logger = PurgeUtilityLogger.getPurgeUtilityLogger();
    logger.setCurrentFilePath( "file1" );
    logger.info( "info on 1st file" );
    logger.setCurrentFilePath( "file2" );
    logger.debug( "debug on file2" );
    String nullString = null;
    try {
      nullString.getBytes(); // Generate an error to log
    } catch ( Exception e ) {
      logger.error( e );
    }

    logger.endJob();

    String logOutput = out.toString();

    Assert.assertTrue( logOutput.contains( PURGE_PATH ) );
    Assert.assertTrue( logOutput.contains( "info on 1st file" ) );
    Assert.assertTrue( logOutput.contains( "debug on file2" ) );
    Assert.assertTrue( logOutput.contains( "java.lang.NullPointerException" ) );
  }

  @SuppressWarnings( "null" )
  @Test
  public void htmlLoggerTest() {
    OutputStream out = new ByteArrayOutputStream();
    PurgeUtilityLog.layoutClass = PurgeUtilityHTMLLayout.class;
    PurgeUtilityLogger.createNewInstance( out, PURGE_PATH, Level.DEBUG );
    PurgeUtilityLogger logger = PurgeUtilityLogger.getPurgeUtilityLogger();
    logger.setCurrentFilePath( "file1" );
    logger.info( "info on 1st file" );
    logger.setCurrentFilePath( "file2" );
    logger.debug( "debug on file2" );
    String nullString = null;
    try {
      nullString.getBytes(); // Generate an error to log
    } catch ( Exception e ) {
      logger.error( e );
    }

    logger.endJob();

    String logOutput = out.toString();

    Assert.assertTrue( logOutput.contains( PURGE_PATH ) );
    Assert.assertTrue( logOutput.contains( "info on 1st file" ) );
    Assert.assertTrue( logOutput.contains( "debug on file2" ) );
    Assert.assertTrue( logOutput.contains( "java.lang.NullPointerException" ) );
  }

}

{'repo_name': 'pentaho/pentaho-kettle', 'stars': '4116', 'repo_language': 'Java', 'file_name': 'subfloor.xml', 'mime_type': 'text/plain', 'hash': 960815367592443693, 'source_dataset': 'data'}


<!-- YAML
added: v0.1.90
-->

* `path` {string} Socket 应该被连接到的路径。将会被传入到 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]。查看[识别 IPC 连接的路径][Identifying paths for IPC connections]。
* `connectListener` {Function} [`net.createConnection()`][] 方法的通用参数，在初始化的 socket 上的 `'connect'` 事件的单次监听器。将会被传入到 [`socket.connect(path[, connectListener])`][`socket.connect(path)`]。
* 返回: {net.Socket} 新创建的 socket，用来开始连接。

初始化一个 [IPC][] 连接。

该方法使用所有默认选项创建一个新的 [`net.Socket`][]，使用 [`socket.connect(path[, connectListener])`][`socket.connect(path)`] 立即初始化连接，然后返回初始化连接的 `net.Socket`。

{'repo_name': 'nodejscn/node-api-cn', 'stars': '1214', 'repo_language': 'JavaScript', 'file_name': 'accessing_core_node_js_modules.md', 'mime_type': 'text/plain', 'hash': 3345831916053162369, 'source_dataset': 'data'}


CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/ReactiveCocoa
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/ReactiveCocoa" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/DKNightVersion" "${PODS_ROOT}/Headers/Public/DZNEmptyDataSet" "${PODS_ROOT}/Headers/Public/FMDB" "${PODS_ROOT}/Headers/Public/LKDBHelper" "${PODS_ROOT}/Headers/Public/MJRefresh" "${PODS_ROOT}/Headers/Public/Masonry" "${PODS_ROOT}/Headers/Public/PINCache" "${PODS_ROOT}/Headers/Public/PINOperation" "${PODS_ROOT}/Headers/Public/PINRemoteImage" "${PODS_ROOT}/Headers/Public/ReactiveCocoa" "${PODS_ROOT}/Headers/Public/RealReachability" "${PODS_ROOT}/Headers/Public/SDWebImage" "${PODS_ROOT}/Headers/Public/Texture" "${PODS_ROOT}/Headers/Public/YYCache" "${PODS_ROOT}/Headers/Public/YYImage" "${PODS_ROOT}/Headers/Public/YYModel" "${PODS_ROOT}/Headers/Public/YYText" "${PODS_ROOT}/Headers/Public/YYWebImage"
PODS_BUILD_DIR = $BUILD_DIR
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/ReactiveCocoa
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES

{'repo_name': 'zhnnnnn/ZHNCosmos', 'stars': '463', 'repo_language': 'Objective-C', 'file_name': 'EmotionsInfo.plist', 'mime_type': 'text/xml', 'hash': -100921671355512827, 'source_dataset': 'data'}


/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    * Neither the name of "The Computer Language Benchmarks Game" nor the
    name of "The Computer Language Shootout Benchmarks" nor the names of
    its contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

/* The Computer Language Benchmarks Game
 * http://shootout.alioth.debian.org/
 *
 * contributed by The Go Authors.
 * based on pidigits.c (by Paolo Bonzini & Sean Bartlett,
 *                      modified by Michael Mellor)
 */

package main

import (
	"flag"
	"fmt"
	"math/big"
)

var n = flag.Int("n", 27, "number of digits")
var silent = flag.Bool("s", false, "don't print result")

var (
	tmp1  = big.NewInt(0)
	tmp2  = big.NewInt(0)
	tmp3  = big.NewInt(0)
	y2    = big.NewInt(0)
	bigk  = big.NewInt(0)
	numer = big.NewInt(1)
	accum = big.NewInt(0)
	denom = big.NewInt(1)
	ten   = big.NewInt(10)
)

func extract_digit() int64 {
	if numer.Cmp(accum) > 0 {
		return -1
	}

	// Compute (numer * 3 + accum) / denom
	tmp1.Lsh(numer, 1)
	tmp1.Add(tmp1, numer)
	tmp1.Add(tmp1, accum)
	tmp1.DivMod(tmp1, denom, tmp2)

	// Now, if (numer * 4 + accum) % denom...
	tmp2.Add(tmp2, numer)

	// ... is normalized, then the two divisions have the same result.
	if tmp2.Cmp(denom) >= 0 {
		return -1
	}

	return tmp1.Int64()
}

func next_term(k int64) {
	y2.SetInt64(k*2 + 1)
	bigk.SetInt64(k)

	tmp1.Lsh(numer, 1)
	accum.Add(accum, tmp1)
	accum.Mul(accum, y2)
	numer.Mul(numer, bigk)
	denom.Mul(denom, y2)
}

func eliminate_digit(d int64) {
	tmp3.SetInt64(d)
	accum.Sub(accum, tmp3.Mul(denom, tmp3))
	accum.Mul(accum, ten)
	numer.Mul(numer, ten)
}

func printf(s string, arg ...interface{}) {
	if !*silent {
		fmt.Printf(s, arg...)
	}
}

func main() {
	flag.Parse()

	var m int // 0 <= m < 10
	for i, k := 0, int64(0); ; {
		d := int64(-1)
		for d < 0 {
			k++
			next_term(k)
			d = extract_digit()
		}

		printf("%c", d+'0')

		i++
		m = i % 10
		if m == 0 {
			printf("\t:%d\n", i)
		}
		if i >= *n {
			break
		}
		eliminate_digit(d)
	}

	if m > 0 {
		printf("%s\t:%d\n", "          "[m:10], *n)
	}
}

{'repo_name': 'AsuraTeam/zcloud', 'stars': '175', 'repo_language': 'Go', 'file_name': 'link.go', 'mime_type': 'text/plain', 'hash': -6783469735501648445, 'source_dataset': 'data'}


/* Minimal wrapper to build an individual busybox applet.
 *
 * Copyright 2005 Rob Landley <rob@landley.net
 *
 * Licensed under GPLv2, see file LICENSE in this source tree.
 */

const char *applet_name;

#include <stdio.h>
#include <stdlib.h>
#include "usage.h"

int main(int argc, char **argv)
{
	applet_name = argv[0];
	return APPLET_main(argc, argv);
}

void bb_show_usage(void)
{
	fputs(APPLET_full_usage "\n", stdout);
	exit(EXIT_FAILURE);
}

{'repo_name': 'isdrupter/busybotnet', 'stars': '120', 'repo_language': 'C', 'file_name': 'test_visit.c', 'mime_type': 'text/x-c', 'hash': 8426978060710965595, 'source_dataset': 'data'}