text:
import io

from stestr import output

class CallWhenProcFinishes:
    """Convert a process object to trigger a callback when returncode is set.

    This just wraps the entire object and when the returncode attribute access
    finds a set value, calls the callback.
    """

    def __init__(self, process, callback):
        """Adapt process

        :param process: A subprocess.Popen object.
        :param callback: The process to call when the process completes.
        """
        self._proc = process
        self._callback = callback
        self._done = False

    @property
    def stdin(self):
        return self._proc.stdin

    @property
    def stdout(self):
        return self._proc.stdout

    @property
    def stderr(self):
        return self._proc.stderr

    @property
    def returncode(self):
        result = self._proc.returncode
        if not self._done and result is not None:
            self._done = True
            self._callback()
        return result

    def wait(self):
        return self._proc.wait()

def _iter_internal_streams(input_streams, stream_type):
    streams = []
    for in_stream in input_streams:
        if in_stream[0] == stream_type:
            streams.append(in_stream[1])
    for stream_value in streams:
        if isinstance(stream_value, output.ReturnCodeToSubunit):
            if getattr(stream_value.source, 'detach', None):
                yield stream_value.source.detach()
            else:
                yield stream_value.source
        elif getattr(stream_value, 'read', None):
            yield stream_value
        else:
            yield io.BytesIO(stream_value)

def iter_streams(input_streams, stream_type):
    """Iterate over all the streams of type stream_type.

    :param stream_type: A simple string such as 'subunit' which matches
        one of the stream types defined for the cmd object this UI is
        being used with.
    :return: A generator of stream objects. stream objects have a read
        method and a close method which behave as for file objects.
    """
    for stream_spec in input_streams:
        _stream_spec = stream_spec[0]
        if '*' in _stream_spec or '?' in _stream_spec or '+' in _stream_spec:
            found = stream_type == _stream_spec[:-1]
        else:
            found = stream_type == _stream_spec
        if found:
            return _iter_internal_streams(input_streams, stream_type)
    raise KeyError(stream_type)

def cleanup_test_name(name, strip_tags=True, strip_scenarios=False):
    """Clean up the test name for display.

    By default we strip out the tags in the test because they don't help us
    in identifying the test that is run to it's result.

    Make it possible to strip out the testscenarios information (not to
    be confused with tempest scenarios) however that's often needed to
    identify generated negative tests.
    """
    if strip_tags:
        tags_start = name.find('[')
        tags_end = name.find(']')
        if tags_start > 0 and tags_end > tags_start:
            newname = name[:tags_start]
            newname += name[tags_end + 1:]
            name = newname

    if strip_scenarios:
        tags_start = name.find('(')
        tags_end = name.find(')')
        if tags_start > 0 and tags_end > tags_start:
            newname = name[:tags_start]
            newname += name[tags_end + 1:]
            name = newname

    return name


text:
class ActiveFireCollection {
  constructor(collection) {
    this.collection = collection;

  }

}
module.exports = ActiveFireCollection;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.eagle.hadoop.queue.model.scheduler;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.eagle.hadoop.queue.common.HadoopClusterConstants;
import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity;
import org.apache.eagle.log.entity.meta.*;

import java.util.List;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@Table("queue_map")
@ColumnFamily("f")
@Prefix("queueMap")
@Service(HadoopClusterConstants.QUEUE_MAPPING_SERVICE_NAME)
@TimeSeries(false)
@Partition( {"site"})
public class QueueStructureAPIEntity extends TaggedLogAPIEntity {
    @Column("a")
    private List<String> subQueues;
    @Column("b")
    private List<String> allSubQueues;
    @Column("c")
    private long lastUpdateTime;

    public List<String> getSubQueues() {
        return subQueues;
    }

    public void setSubQueues(List<String> subQueues) {
        this.subQueues = subQueues;
        valueChanged("subQueues");
    }

    public List<String> getAllSubQueues() {
        return allSubQueues;
    }

    public void setAllSubQueues(List<String> allSubQueues) {
        this.allSubQueues = allSubQueues;
        valueChanged("allSubQueues");
    }

    public long getLastUpdateTime() {
        return lastUpdateTime;
    }

    public void setLastUpdateTime(long lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
        valueChanged("lastUpdateTime");
    }

}


text:
Even before browsers ship native support for WebAssembly, developers can ship
applications on the Web using a [polyfill][] which converts WebAssembly to
JavaScript. Aside from packaging the application in a forward-looking way—so
that when browsers do support WebAssembly natively, the application will
immediately benefit—this can provide additional value in other ways:

* Small download size due to the [binary encoding](BinaryEncoding.md);
* Minor impact on startup performance (decoding the binary into JavaScript is
  fast);
* The same high throughput as in existing approaches of compiling C/C++
  applications to browsers such as [Emscripten][], [asm.js][] and [PNaCl][].

This polyfill further allows us to experiment on the early binary encoding and
get developer feedback before finalizing the format and supporting it natively
as part of [the MVP](MVP.md).

A working prototype to unpack a tentative binary format into JavaScript, as well
as to convert [asm.js][] into WebAssembly (useful for existing applications), is
in the [polyfill repo][].  We also leave open the possibility of multiple
polyfills existing to meet different developers' needs.

An **effective** polyfill should reuse much of the Web platform's existing
capabilities, as detailed in the browser embedding
[implementation details](Web.md#Implementation-Details).

  [polyfill]: https://remysharp.com/2010/10/08/what-is-a-polyfill
  [Emscripten]: http://emscripten.org
  [asm.js]: http://asmjs.org
  [PNaCl]: http://gonacl.com
  [polyfill repo]: https://github.com/WebAssembly/polyfill-prototype-1

## Polyfill Deviations

An **efficient** polyfill may purposely diverge from the specified WebAssembly
semantics: a polyfill doesn't need to be 100% correct with respect to the
WebAssembly specification to be useful in practice. There are corner cases
(often undefined behavior in C/C++) where JavaScript and asm.js don't have ideal
semantics to maintain correctness efficiently.

If needed, a polyfill could provide an option to ensure full correctness at the
expense of performance, though this is not expected to be necessary for portable
C/C++ code.

Some divergences that we've identified as potentially desirable:

* **[Misaligned heap access](AstSemantics.md#alignment)**: Since misaligned
  loads/stores are guaranteed to produce correct results and heap accesses in
  asm.js force alignment (e.g., `HEAP32[i>>2]` masks off the low two bits), an
  asm.js polyfill would need to translate *all* loads/stores into byte accesses
  (regardless of specified alignment) to be correct. To achieve competitive
  performance, the polyfill prototype defaults to incorrect behavior by emitting
  full-size accesses as if the index was never misaligned. Providing correct
  alignment information is important for portable WebAssembly performance in
  general; that information also guarantees that the polyfill is both correct
  and fast.
* **[Out of bounds heap access](AstSemantics.md#out-of-bounds)**: Regardless of
  semantics chosen for out of bounds access in WebAssembly, an asm.js polyfill
  will follow standard asm.js behavior:
  - Out of bound stores are ignored (treated as no-op);
  - Out of bound loads return zero for integer loads or NaN for floating point.
* **[32-bit integer operations](AstSemantics.md#32-bit-integer-operations)**:
  Regardless of WebAssembly behavior, an asm.js polyfill will follow its
  standard behavior:
  - Division by zero returns zero;
  - `INT32_MIN / -1` returns `INT32_MIN`;
  - Shift counts are implicitly masked.
* **[Datatype conversions](AstSemantics.md#datatype-conversions-truncations-reinterpretations-promotions-and-demotions)**:
  Regardless of WebAssembly behavior, an asm.js polyfill will follow its
  standard behavior:
  - Return zero when conversion from floating point to integer fails;
  - Optionally canonicalize NaN values.

## Polyfill Evolution

The MVP feature set is expected to be entirely polyfillable effectively and
efficiently. As WebAssembly evolves past MVP the working group will strive to:

* Standardize features which can be pollyfilled;
* Co-evolve with other web standards bodies, ensuring that upcoming WebAssembly
  features remain polyfillable.

There is, however, no hard requirement that WebAssembly features be polyfillable
past the MVP. If a feature is highly desirable but cannot be effectively or
efficiently polyfilled then WebAssembly may adopt the feature. This is not a
decision that will be taken lightly, and the WebAssembly working group will
attempt to make it possible for developers to avoid the feature or provide a
fallback through [feature detection](FeatureTest.md).


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using Bjd.util;

namespace Bjd.log {

    public class LogView : IDisposable{

        private readonly ListView _listView;
        private readonly List<OneLog> _ar = new List<OneLog>();
        private readonly Timer _timer;
        private readonly Kernel _kernel;

        public LogView(Kernel kernel,ListView listView){
            if (listView == null){
                return;
            }
            _kernel = kernel;
            _listView = listView;
            //タイマー(表示)イベント処理
            _timer = new Timer{Enabled = true, Interval = 100};
            _timer.Tick += TimerTick;
        }

        //タイマー(表示)イベント
        private void TimerTick(object sender, EventArgs e){
            if (_listView == null){
                return;
            }
            if (_ar.Count == 0)
                return;
            _timer.Enabled = false;
            lock (this){
                _listView.BeginUpdate();

                //Ver5.8.5 Java fix
                //「表示する最大行数」を超えた場合は削除する
                //Ver5.8.6 _kernel.ListOption!=null追加
                if (_kernel != null && _listView != null && _kernel.ListOption!=null){
                    var op = _kernel.ListOption.Get("Log");
                    if (op != null){
                        var linesMax = (int) op.GetValue("linesMax");
                        var linesDelete = (int) op.GetValue("linesDelete");
                        //「表示する最大行数」よりも「削除する行数」の方が大きい数値を設定されている場合、最大行数に修正する
                        if (linesMax < linesDelete)
                            linesDelete = linesMax;
                        if (_listView.Items.Count > linesMax) {
                            while (_listView.Items.Count > (linesMax - linesDelete)){
                                _listView.Items.RemoveAt(0);
                            }
                            GC.Collect();
                        }
                    }

                }

                //一回のイベントで処理する最大数は100行まで
                var list = new List<OneLog>();
                for (var i = 0; i < 300 && 0 < _ar.Count; i++){
                    list.Add(_ar[0]);
                    _ar.RemoveAt(0);
                }
                Disp(list);

                //Ver5.8.8
                //Java fix
//                //リモートクライアントへのログ送信
//                if (_kernel.RemoteConnect != null){
//                    //クライアントから接続されている場合
//                    foreach (var oneLog in list){
//
//                        var sv = _kernel.ListServer.Get("Remote");
//                        if (sv != null)
//                            sv.Append(oneLog);
//                    }
//                }

                _listView.EndUpdate();

            }
            //1行の高さを計算してスクロールする
            _listView.EnsureVisible(_listView.Items[_listView.Items.Count - 1].Index);
            _timer.Enabled = true;
        }

        public void Dispose(){
            if (_listView != null)
                _listView.Dispose();
        }

        public void SetFont(Font font){
            //Java fix
            if (font != null && _listView!=null){
                if (_listView.InvokeRequired){
                    _listView.BeginInvoke(new MethodInvoker(() => SetFont(font)));
                } else{
                    _listView.Font = font;
                }
            }
        }

        //ログビューへの表示(リモートからも使用される)
        public void Append(OneLog oneLog){
            if (_listView == null)
                return;
            lock (this){
                _ar.Add(oneLog);
            }
        }

        //選択されたログをクリップボードにコピーする
        public void SetClipboard(){
            if (_listView == null)
                return;

            var sb = new StringBuilder();
            var colMax = _listView.Columns.Count;
            for (int c = 0; c < colMax; c++){
                sb.Append(_listView.Columns[c].Text);
                sb.Append("\t");
            }
            sb.Append("\r\n");
            for (int i = 0; i < _listView.SelectedItems.Count; i++){
                for (int c = 0; c < colMax; c++){
                    sb.Append(_listView.SelectedItems[i].SubItems[c].Text);
                    sb.Append("\t");

                }
                sb.Append("\r\n");
            }
            //Ver6.1.0
            try{
                Clipboard.SetText(sb.ToString());
            } catch (Exception ex){
                Msg.Show(MsgKind.Error, ex.Message);
            }
        }

        //表示ログをクリア
        public void Clear(){
            if (_listView == null)
                return;
            _listView.Items.Clear();
        }

        //このメソッドはタイマースレッドからのみ使用される
        private void Disp(List<OneLog> list){
            try{
                foreach (OneLog oneLog in list){
                    if (_listView == null)
                        break;
                    //リストビューへの出力
                    ListViewItem item = _listView.Items.Add(oneLog.Dt());
                    item.SubItems.Add(oneLog.Kind());
                    item.SubItems.Add(oneLog.ThreadId());
                    item.SubItems.Add(oneLog.NameTag());
                    item.SubItems.Add(oneLog.RemoteHostname());
                    item.SubItems.Add(oneLog.MessageNo());
                    item.SubItems.Add(oneLog.Message());
                    item.SubItems.Add(oneLog.DetailInfomation());
                }
            }
            catch (Exception ex){
                var sb = new StringBuilder();
                sb.Append(ex.Message + "\r\n");
                foreach (var oneLog in list){
                    sb.Append(String.Format("{0} {1}\r\n", oneLog.MessageNo(),oneLog.Message()));
               }
                Msg.Show(MsgKind.Error, sb.ToString());
            }
        }
    }

}

    /*
    public class LogView:IDisposable {
        readonly Kernel _kernel;
        readonly ListView _listView;
        readonly Timer _timer;
        readonly List<OneLog> _ar = new List<OneLog>();

        public LogView(Kernel kernel,ListView listView) {
            if (listView == null)
                return;

            _kernel = kernel;
            _listView = listView;

            //タイマー(表示)イベント処理
            _timer = new Timer{Enabled = true, Interval = 100};

            _timer.Tick += TimerTick;
        }
        public void Dispose() {
            if (_listView != null)
                _listView.Dispose();

        }
        public void InitFont(){
            if (_kernel != null) {
                var font = (Font)_kernel.ListOption.Get("Log").GetValue("font");
                if (font != null)
                    _listView.Font = font;
            }
        }

        //ログビューへの表示(リモートからも使用される)
        public void Append(OneLog oneLog) {
            if (_listView == null)
                return;
            lock (this) {
                _ar.Add(oneLog);
            }
        }

        //必要であれば有効化する
//        public void Refresh() {
//            if (listView != null && listView.InvokeRequired) {// 別スレッドから呼び出された場合
//                listView.BeginInvoke(new MethodInvoker(() => Refresh()));
//            } else {
//                if (listView != null)
//                    timer_Tick(null, null);
//            }
//        }

        //選択されたログをクリップボードにコピーする
        public void SetClipboard() {
            if (_listView == null)
                return;

            var sb = new StringBuilder();
            var colMax = _listView.Columns.Count;
            for (int c = 0; c < colMax; c++) {
                sb.Append(_listView.Columns[c].Text);
                sb.Append("\t");
            }
            sb.Append("\r\n");
            for (int i = 0; i < _listView.SelectedItems.Count; i++) {
                for (int c = 0; c < colMax; c++) {
                    sb.Append(_listView.SelectedItems[i].SubItems[c].Text);
                    sb.Append("\t");

                }
                sb.Append("\r\n");
            }
            Clipboard.SetText(sb.ToString());
        }
        //表示ログをクリア
        public void Clear() {
            if (_listView == null)
                return;
            _listView.Items.Clear();
        }

        //タイマー(表示)イベント
        void TimerTick(object sender, EventArgs e) {
            if (_ar.Count == 0)
                return;
            _timer.Enabled = false;
            lock (this) {
                _listView.BeginUpdate();

                //あとでリアルのオプションを取得する方法を確立してから実装する

                //「表示する最大行数」を超えた場合は、2000行まで削除する
//                if (listView.Items.Count > kernel.Log2.LinesMax) {
//                    //「表示する最大行数」よりも「削除する行数」の方が大きい数値を設定されている場合、最大行数に修正する
//                    int linesDelete = kernel.Log2.LinesDelete;
//                    if (kernel.Log2.LinesMax < linesDelete)
//                        linesDelete = kernel.Log2.LinesMax;
//                    while (listView.Items.Count > (kernel.Log2.LinesMax - linesDelete)) {
//                        listView.Items.RemoveAt(0);
//                    }
//                }
                //一回のイベントで処理する最大数は100行まで
                var list = new List<OneLog>();
                for (int i = 0; i < 300 && 0 < _ar.Count; i++) {
                    list.Add(_ar[0]);
                    _ar.RemoveAt(0);
                }
                Disp(list);

                _listView.EndUpdate();

            }
            //1行の高さを計算してスクロールする
            _listView.EnsureVisible(_listView.Items[_listView.Items.Count - 1].Index);
            _timer.Enabled = true;
        }

        //このメソッドはタイマースレッドからのみ使用される
        void Disp(List<OneLog> list) {
            try {
                foreach (OneLog oneLog in list) {
                    if (_listView == null)
                        break;
                    //リストビューへの出力
                    ListViewItem item = _listView.Items.Add(oneLog.Dt());
                    item.SubItems.Add(oneLog.Kind());
                    item.SubItems.Add(oneLog.ThreadId());
                    item.SubItems.Add(oneLog.NameTag());
                    item.SubItems.Add(oneLog.RemoteHostname());
                    item.SubItems.Add(oneLog.MessageNo());
                    item.SubItems.Add(oneLog.Message());
                    item.SubItems.Add(oneLog.DetailInfomation());
                }
            } catch (Exception ex) {
                var sb = new StringBuilder();
                sb.Append(ex.Message + "\r\n");
                foreach (var oneLog in list) {
                    string.Format("{0} {1} {2}\r\n", oneLog.MessageNo, oneLog.Message);
                }
                Msg.Show(MsgKind.Error, sb.ToString());
            }
        }

    }

}
*/


text:
<?php

ini_set('display_errors',1);

// now let's get the actual article from wikipedia

function curlRequest($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// per Wikipedia's request, let's set the user agent
	curl_setopt($ch, CURLOPT_USERAGENT, 'RealTalkLorem/1.0 (http://realtalk-lorem.herokuapp.com)');
	$body = curl_exec($ch);
	return $body;
}

// parse the incoming data
$input = json_decode(file_get_contents('php://input'),true);
// validate the contents
if ($input == NULL || !array_key_exists("title",$input) || $input['title'] == "") {
	header('HTTP/1.1 400 Bad Request');
	return;
}

$title = $input['title'];

// now we search for the topic
$parseUrl = "http://en.wikipedia.org/w/api.php?action=parse&page=" . urlencode($title) . "&format=json";

$parse = json_decode(curlRequest($parseUrl),true);

// parse the response
$text = $parse['parse']['text']['*'];

// strip out any JS scripts from the source so it won't be accidentally executed
$dom = new DOMDocument();
$dom->loadHTML($text);
$scripts = $dom->getElementsByTagName('script');
for ($i = 0; $i < $scripts->length; $i++) {
	$scripts->item($i)->parentNode->removeChild($scripts->item($i));
}
$text = $dom->saveHTML();

$response = $input;
$response['contents'] = $text;

echo json_encode($response);

?>


text:
package jp.fieldnotes.hatunatu.util.exception;

import jp.fieldnotes.hatunatu.util.collection.ArrayUtil;

/**
 * プロパティが見つからなかった場合にスローされる例外です。
 *
 * @author higa
 *
 */
public class PropertyNotFoundRuntimeException extends SRuntimeException {

    private static final long serialVersionUID = -5177019197796206774L;

    private final Class<?> targetClass;

    private final String propertyName;

    /**
     * {@link PropertyNotFoundRuntimeException}を返します。
     *
     * @param targetClass
     *            ターゲットクラス
     * @param propertyName
     *            プロパティ名
     */
    public PropertyNotFoundRuntimeException(final Class<?> targetClass,
            final String propertyName) {
        super("EUTL0065", ArrayUtil.asArray(targetClass.getName(), propertyName));
        this.targetClass = targetClass;
        this.propertyName = propertyName;
    }

    /**
     * ターゲットクラスを返します。
     *
     * @return ターゲットクラス
     */
    public Class<?> getTargetClass() {
        return targetClass;
    }

    /**
     * プロパティ名を返します。
     *
     * @return プロパティ名
     */
    public String getPropertyName() {
        return propertyName;
    }

}


text:
from optparse import OptionParser

from pylibftdi import Driver
from pylibftdi import BitBangDevice

from ctypes.util import find_library

import sys
import time

# ----------------------------------------------------------------------------
# VARIABLE CLASSS
# ----------------------------------------------------------------------------

class app_data:
    def __init__(
        self,
        name = "DRControl",
        version = "0.12",
        date = "$Date$",
        rev = "$Rev$",
        author = "Sebastian Sjoholm"
        ):

        self.name = name
        self.version = version
        self.build = date
        self.rev = rev
        self.author = author

class cmdarg_data:
    def __init__(
        self,
        device = "",
        relay = "",
        command = "",
        verbose = False
        ):

        self.device = device
        self.relay = relay
        self.command = command
        self.verbose = verbose

'''
# Original
class relay_data(dict):

    address = {
            "1":"2",
            "2":"8",
            "3":"20",
            "4":"80",
            "5":"1",
            "6":"4",
            "7":"10",
            "8":"40",
            "all":"FF"
            }
'''

# For SainSmart 8 port USB model
class relay_data(dict):

    address = {
            "1":"1",
            "2":"2",
            "3":"4",
            "4":"8",
            "5":"10",
            "6":"20",
            "7":"40",
            "8":"80",
            "all":"FF"
            }

    def __getitem__(self, key): return self[key]
    def keys(self): return self.keys()

# ----------------------------------------------------------------------------
# testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.
# http://wiki.python.org/moin/BitManipulation
# ----------------------------------------------------------------------------

def testBit(int_type, offset):
    mask = 1 << offset
    return(int_type & mask)

# Original
'''
def get_relay_state( data, relay ):
    if relay == "1":
        return testBit(data, 1)
    if relay == "2":
        return testBit(data, 3)
    if relay == "3":
        return testBit(data, 5)
    if relay == "4":
        return testBit(data, 7)
    if relay == "5":
        return testBit(data, 2)
    if relay == "6":
        return testBit(data, 4)
    if relay == "7":
        return testBit(data, 6)
    if relay == "8":
        return testBit(data, 8)
'''

# For SainSmart 8 port USB model
def get_relay_state( data, relay ):
    if relay == "1":
        return testBit(data, 0)
    if relay == "2":
        return testBit(data, 1)
    if relay == "3":
        return testBit(data, 2)
    if relay == "4":
        return testBit(data, 3)
    if relay == "5":
        return testBit(data, 4)
    if relay == "6":
        return testBit(data, 5)
    if relay == "7":
        return testBit(data, 6)
    if relay == "8":
        return testBit(data, 7)

# ----------------------------------------------------------------------------
# LIST_DEVICES()
#
# Routine modified from the original pylibftdi example by Ben Bass
# ----------------------------------------------------------------------------

def list_devices():
    print "Vendor\t\tProduct\t\t\tSerial"
    dev_list = []
    for device in Driver().list_devices():
        device = map(lambda x: x.decode('latin1'), device)
        vendor, product, serial = device
        print "%s\t\t%s\t\t%s" % (vendor, product, serial)

# Adding an option to list ONLY the serial number(s)
# For use on my ArloBot programs

def list_serial_only():
    #print "Vendor\t\tProduct\t\t\tSerial"
    dev_list = []
    for device in Driver().list_devices():
        device = map(lambda x: x.decode('latin1'), device)
        vendor, product, serial = device
        print "%s" % (serial)

# ----------------------------------------------------------------------------
# SET_RELAY()
#
# Set specified relay to chosen state
# ----------------------------------------------------------------------------

def set_relay():

    if cmdarg.verbose:
        print "Device:\t\t" + cmdarg.device
        print "Send command:\tRelay " + cmdarg.relay + " (0x" + relay.address[cmdarg.relay] + ") to " + cmdarg.command.upper()

    try:
        with BitBangDevice(cmdarg.device) as bb:

            # Action towards specific relay
            if cmdarg.relay.isdigit():

                if int(cmdarg.relay) >= 1 and int(cmdarg.relay) <= 8:

                    # Turn relay ON
                    if cmdarg.command == "on":
                        if cmdarg.verbose:
                            print "Relay " + str(cmdarg.relay) + " to ON"
                        bb.port |= int(relay.address[cmdarg.relay], 16)

                    # Turn relay OFF
                    elif cmdarg.command == "off":
                        if cmdarg.verbose:
                            print "Relay "  + str(cmdarg.relay) + " to OFF"
                        bb.port &= ~int(relay.address[cmdarg.relay], 16)

                    # Print relay status
                    elif cmdarg.command == "state":
                        state = get_relay_state( bb.port, cmdarg.relay )
                        if state == 0:
                            if cmdarg.verbose:
                                print "Relay " + cmdarg.relay + " state:\tOFF (" + str(state) + ")"
                            else:
                                print "OFF"
                        else:
                            if cmdarg.verbose:
                                print "Relay " + cmdarg.relay + " state:\tON (" + str(state) + ")"
                            else:
                                print "ON"

            # Action towards all relays
            elif cmdarg.relay == "all":

                if cmdarg.command == "on":
                    if cmdarg.verbose:
                        print "Relay " + str(cmdarg.relay) + " to ON"
                    bb.port |= int(relay.address[cmdarg.relay], 16)

                elif cmdarg.command == "off":
                    if cmdarg.verbose:
                        print "Relay "  + str(cmdarg.relay) + " to OFF"
                    bb.port &= ~int(relay.address[cmdarg.relay], 16)

                elif cmdarg.command == "state":
                    #for i in range(1,8):
                    #print bb.port
                    for i in range(1,9):
                        state = get_relay_state( bb.port, str(i) )
                        if state == 0:
                            if cmdarg.verbose:
                                print "Relay " + str(i) + " state:\tOFF (" + str(state) + ")"
                            else:
                                print "OFF"
                        else:
                            if cmdarg.verbose:
                                print "Relay " + str(i) + " state:\tON (" + str(state) + ")"
                            else:
                                print "ON"

                else:
                    print "Error: Unknown command"

            else:
                print "Error: Unknown relay number"
                sys.exit(1)

    except Exception, err:
        print "Error: " + str(err)
        sys.exit(1)

def check():

    # Check python version
    if sys.hexversion < 0x02060000:
        print "Error: Your Python need to be 2.6 or newer"
        sys.exit(1)

    # Check availability on library, this check is also done in pylibftdi
    ftdi_lib = find_library('ftdi')
    if ftdi_lib is None:
        print "Error: The pylibftdi library not found"
        sys.exit(1)

if __name__ == '__main__':

    # Init objects
    cmdarg = cmdarg_data()
    relay = relay_data()
    app = app_data()

    # Do system check
    check()

    parser = OptionParser()
    parser.add_option("-d", "--device", action="store", type="string", dest="device", help="The device serial, example A6VV5PHY")
    parser.add_option("-l", "--list", action="store_true", dest="list", default=False, help="List all devices")
    parser.add_option("-s", "--serial", action="store_true", dest="list_serial_only", default=False, help="List device serial numbers only")
    parser.add_option("-r", "--relay", action="store", type="string", dest="relay", help="Relay to command by number: 1...8 or all")
    parser.add_option("-c", "--command", action="store", type="string", dest="command", help="State: on, off, state")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose, print all info on screen")

    (options, args) = parser.parse_args()

    if options.verbose:
        cmdarg.verbose = options.verbose
        print app.name + " " + app.version
    else:
        cmdarg.verbose = False

    if options.list:
        list_devices()
        sys.exit(0)

    if options.list_serial_only:
        list_serial_only()
        sys.exit(0)

    if options.relay or options.command:
        if not options.device:
            print "Error: Device missing"

    if options.device:
        if not options.relay:
            print "Error: Need to state which relay"
            sys.exit(1)
        if not options.command:
            print "Error: Need to specify which relay state"
            sys.exit(1)

        cmdarg.device = options.device
        cmdarg.relay = options.relay.lower()
        cmdarg.command = options.command.lower()

        set_relay()
        sys.exit(0)


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

namespace ModularityWithAutofac
{
    class Program
    {
        static void Main(string[] args)
        {
            var app = new App
            {

            };

            app.Run();
        }
    }
}


text:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const meow_1 = __importDefault(require("meow"));
const lodash_1 = __importDefault(require("lodash"));
function init(opt, helpText) {
    const help = helpText ? helpText : `
  Usage
    <script>

  Options
    --help         show usage information
    --verbose, -v  show additional information
                    DEFAULT: false
    `;
    const options = {
        flags: {
            verbose: {
                type: 'boolean',
                alias: 'v',
                default: false
            }
        }
    };
    if (opt) {
        lodash_1.default.merge(options, opt);
    }
    var cli = (0, meow_1.default)(help, options);
    if (cli.flags.verbose) {
        process.env.verbose = true.toString();
    }
}
module.exports = {
    parseCli: init
};


text:
This is a simple game to teach Morse Code.  It just sends one letter at a time, get it right and that bar goes down, get it wrong and it goes back up.  Your goal is to drain all of the bars.

Loosely based on [morse.exe](http://c2.com/~ward/morse/morse.html), a DOS-based game that helped me pass my Tech Plus ham radio license exam back when morse code was required.

[Play Now](http://jk3.us/morsegame/)

## Uses

* [d3](https://d3js.org/)
* [This gist](https://gist.github.com/eholk/0115691987090973cefe) (with modifications, js file included here)
* [keymaster](https://github.com/madrobby/keymaster)
* [Bootstrap](https://getbootstrap.com/)

## TODO

* Properly handle finishing the game
* Options for speed, time limit, and feedback
* Mobile-friendly version?


text:
#ifndef FRONTEND
#include "postgres.h"
#else
#include "postgres_fe.h"
#endif

#include <ctype.h>
#include <sys/stat.h>
#ifdef WIN32
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0500
#ifdef near
#undef near
#endif
#define near
#include <shlobj.h>
#else
#include <unistd.h>
#endif

#include "pg_config_paths.h"

#ifndef WIN32
#define IS_PATH_VAR_SEP(ch) ((ch) == ':')
#else
#define IS_PATH_VAR_SEP(ch) ((ch) == ';')
#endif

static void make_relative_path(char *ret_path, const char *target_path,
							   const char *bin_path, const char *my_exec_path);
static void trim_directory(char *path);
static void trim_trailing_separator(char *path);

/*
 * skip_drive
 *
 * On Windows, a path may begin with "C:" or "//network/".  Advance over
 * this and point to the effective start of the path.
 */
#ifdef WIN32

static char *
skip_drive(const char *path)
{
	if (IS_DIR_SEP(path[0]) && IS_DIR_SEP(path[1]))
	{
		path += 2;
		while (*path && !IS_DIR_SEP(*path))
			path++;
	}
	else if (isalpha((unsigned char) path[0]) && path[1] == ':')
	{
		path += 2;
	}
	return (char *) path;
}
#else

#define skip_drive(path)	(path)
#endif

/*
 *	has_drive_prefix
 *
 * Return true if the given pathname has a drive prefix.
 */
bool
has_drive_prefix(const char *path)
{
#ifdef WIN32
	return skip_drive(path) != path;
#else
	return false;
#endif
}

/*
 *	first_dir_separator
 *
 * Find the location of the first directory separator, return
 * NULL if not found.
 */
char *
first_dir_separator(const char *filename)
{
	const char *p;

	for (p = skip_drive(filename); *p; p++)
		if (IS_DIR_SEP(*p))
			return unconstify(char *, p);
	return NULL;
}

/*
 *	first_path_var_separator
 *
 * Find the location of the first path separator (i.e. ':' on
 * Unix, ';' on Windows), return NULL if not found.
 */
char *
first_path_var_separator(const char *pathlist)
{
	const char *p;

	/* skip_drive is not needed */
	for (p = pathlist; *p; p++)
		if (IS_PATH_VAR_SEP(*p))
			return unconstify(char *, p);
	return NULL;
}

/*
 *	last_dir_separator
 *
 * Find the location of the last directory separator, return
 * NULL if not found.
 */
char *
last_dir_separator(const char *filename)
{
	const char *p,
			   *ret = NULL;

	for (p = skip_drive(filename); *p; p++)
		if (IS_DIR_SEP(*p))
			ret = p;
	return unconstify(char *, ret);
}

/*
 *	make_native_path - on WIN32, change / to \ in the path
 *
 *	This effectively undoes canonicalize_path.
 *
 *	This is required because WIN32 COPY is an internal CMD.EXE
 *	command and doesn't process forward slashes in the same way
 *	as external commands.  Quoting the first argument to COPY
 *	does not convert forward to backward slashes, but COPY does
 *	properly process quoted forward slashes in the second argument.
 *
 *	COPY works with quoted forward slashes in the first argument
 *	only if the current directory is the same as the directory
 *	of the first argument.
 */
void
make_native_path(char *filename)
{
#ifdef WIN32
	char	   *p;

	for (p = filename; *p; p++)
		if (*p == '/')
			*p = '\\';
#endif
}

/*
 * This function cleans up the paths for use with either cmd.exe or Msys
 * on Windows. We need them to use filenames without spaces, for which a
 * short filename is the safest equivalent, eg:
 *		C:/Progra~1/
 */
void
cleanup_path(char *path)
{
#ifdef WIN32
	char	   *ptr;

	/*
	 * GetShortPathName() will fail if the path does not exist, or short names
	 * are disabled on this file system.  In both cases, we just return the
	 * original path.  This is particularly useful for --sysconfdir, which
	 * might not exist.
	 */
	GetShortPathName(path, path, MAXPGPATH - 1);

	/* Replace '\' with '/' */
	for (ptr = path; *ptr; ptr++)
	{
		if (*ptr == '\\')
			*ptr = '/';
	}
#endif
}

/*
 * join_path_components - join two path components, inserting a slash
 *
 * We omit the slash if either given component is empty.
 *
 * ret_path is the output area (must be of size MAXPGPATH)
 *
 * ret_path can be the same as head, but not the same as tail.
 */
void
join_path_components(char *ret_path,
					 const char *head, const char *tail)
{
	if (ret_path != head)
		strlcpy(ret_path, head, MAXPGPATH);

	/*
	 * Remove any leading "." in the tail component.
	 *
	 * Note: we used to try to remove ".." as well, but that's tricky to get
	 * right; now we just leave it to be done by canonicalize_path() later.
	 */
	while (tail[0] == '.' && IS_DIR_SEP(tail[1]))
		tail += 2;

	if (*tail)
	{
		/* only separate with slash if head wasn't empty */
		snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
				 "%s%s",
				 (*(skip_drive(head)) != '\0') ? "/" : "",
				 tail);
	}
}

/*
 *	Clean up path by:
 *		o  make Win32 path use Unix slashes
 *		o  remove trailing quote on Win32
 *		o  remove trailing slash
 *		o  remove duplicate adjacent separators
 *		o  remove trailing '.'
 *		o  process trailing '..' ourselves
 */
void
canonicalize_path(char *path)
{
	char	   *p,
			   *to_p;
	char	   *spath;
	bool		was_sep = false;
	int			pending_strips;

#ifdef WIN32

	/*
	 * The Windows command processor will accept suitably quoted paths with
	 * forward slashes, but barfs badly with mixed forward and back slashes.
	 */
	for (p = path; *p; p++)
	{
		if (*p == '\\')
			*p = '/';
	}

	/*
	 * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
	 * as argv[2], so trim off trailing quote.
	 */
	if (p > path && *(p - 1) == '"')
		*(p - 1) = '/';
#endif

	/*
	 * Removing the trailing slash on a path means we never get ugly double
	 * trailing slashes. Also, Win32 can't stat() a directory with a trailing
	 * slash. Don't remove a leading slash, though.
	 */
	trim_trailing_separator(path);

	/*
	 * Remove duplicate adjacent separators
	 */
	p = path;
#ifdef WIN32
	/* Don't remove leading double-slash on Win32 */
	if (*p)
		p++;
#endif
	to_p = p;
	for (; *p; p++, to_p++)
	{
		/* Handle many adjacent slashes, like "/a///b" */
		while (*p == '/' && was_sep)
			p++;
		if (to_p != p)
			*to_p = *p;
		was_sep = (*p == '/');
	}
	*to_p = '\0';

	/*
	 * Remove any trailing uses of "." and process ".." ourselves
	 *
	 * Note that "/../.." should reduce to just "/", while "../.." has to be
	 * kept as-is.  In the latter case we put back mistakenly trimmed ".."
	 * components below.  Also note that we want a Windows drive spec to be
	 * visible to trim_directory(), but it's not part of the logic that's
	 * looking at the name components; hence distinction between path and
	 * spath.
	 */
	spath = skip_drive(path);
	pending_strips = 0;
	for (;;)
	{
		int			len = strlen(spath);

		if (len >= 2 && strcmp(spath + len - 2, "/.") == 0)
			trim_directory(path);
		else if (strcmp(spath, ".") == 0)
		{
			/* Want to leave "." alone, but "./.." has to become ".." */
			if (pending_strips > 0)
				*spath = '\0';
			break;
		}
		else if ((len >= 3 && strcmp(spath + len - 3, "/..") == 0) ||
				 strcmp(spath, "..") == 0)
		{
			trim_directory(path);
			pending_strips++;
		}
		else if (pending_strips > 0 && *spath != '\0')
		{
			/* trim a regular directory name canceled by ".." */
			trim_directory(path);
			pending_strips--;
			/* foo/.. should become ".", not empty */
			if (*spath == '\0')
				strcpy(spath, ".");
		}
		else
			break;
	}

	if (pending_strips > 0)
	{
		/*
		 * We could only get here if path is now totally empty (other than a
		 * possible drive specifier on Windows). We have to put back one or
		 * more ".."'s that we took off.
		 */
		while (--pending_strips > 0)
			strcat(path, "../");
		strcat(path, "..");
	}
}

/*
 * Detect whether a path contains any parent-directory references ("..")
 *
 * The input *must* have been put through canonicalize_path previously.
 *
 * This is a bit tricky because we mustn't be fooled by "..a.." (legal)
 * nor "C:.." (legal on Unix but not Windows).
 */
bool
path_contains_parent_reference(const char *path)
{
	int			path_len;

	path = skip_drive(path);	/* C: shouldn't affect our conclusion */

	path_len = strlen(path);

	/*
	 * ".." could be the whole path; otherwise, if it's present it must be at
	 * the beginning, in the middle, or at the end.
	 */
	if (strcmp(path, "..") == 0 ||
		strncmp(path, "../", 3) == 0 ||
		strstr(path, "/../") != NULL ||
		(path_len >= 3 && strcmp(path + path_len - 3, "/..") == 0))
		return true;

	return false;
}

/*
 * Detect whether a path is only in or below the current working directory.
 * An absolute path that matches the current working directory should
 * return false (we only want relative to the cwd).  We don't allow
 * "/../" even if that would keep us under the cwd (it is too hard to
 * track that).
 */
bool
path_is_relative_and_below_cwd(const char *path)
{
	if (is_absolute_path(path))
		return false;
	/* don't allow anything above the cwd */
	else if (path_contains_parent_reference(path))
		return false;
#ifdef WIN32

	/*
	 * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
	 * relative to the cwd on that drive, or the drive's root directory if
	 * that drive has no cwd.  Because the path itself cannot tell us which is
	 * the case, we have to assume the worst, i.e. that it is not below the
	 * cwd.  We could use GetFullPathName() to find the full path but that
	 * could change if the current directory for the drive changes underneath
	 * us, so we just disallow it.
	 */
	else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
			 !IS_DIR_SEP(path[2]))
		return false;
#endif
	else
		return true;
}

/*
 * Detect whether path1 is a prefix of path2 (including equality).
 *
 * This is pretty trivial, but it seems better to export a function than
 * to export IS_DIR_SEP.
 */
bool
path_is_prefix_of_path(const char *path1, const char *path2)
{
	int			path1_len = strlen(path1);

	if (strncmp(path1, path2, path1_len) == 0 &&
		(IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
		return true;
	return false;
}

/*
 * Extracts the actual name of the program as called -
 * stripped of .exe suffix if any
 */
const char *
get_progname(const char *argv0)
{
	const char *nodir_name;
	char	   *progname;

	nodir_name = last_dir_separator(argv0);
	if (nodir_name)
		nodir_name++;
	else
		nodir_name = skip_drive(argv0);

	/*
	 * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
	 * called only once.
	 */
	progname = strdup(nodir_name);
	if (progname == NULL)
	{
		fprintf(stderr, "%s: out of memory\n", nodir_name);
		abort();				/* This could exit the postmaster */
	}

#if defined(__CYGWIN__) || defined(WIN32)
	/* strip ".exe" suffix, regardless of case */
	if (strlen(progname) > sizeof(EXE) - 1 &&
		pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
		progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
#endif

	return progname;
}

/*
 * dir_strcmp: strcmp except any two DIR_SEP characters are considered equal,
 * and we honor filesystem case insensitivity if known
 */
static int
dir_strcmp(const char *s1, const char *s2)
{
	while (*s1 && *s2)
	{
		if (
#ifndef WIN32
			*s1 != *s2
#else
		/* On windows, paths are case-insensitive */
			pg_tolower((unsigned char) *s1) != pg_tolower((unsigned char) *s2)
#endif
			&& !(IS_DIR_SEP(*s1) && IS_DIR_SEP(*s2)))
			return (int) *s1 - (int) *s2;
		s1++, s2++;
	}
	if (*s1)
		return 1;				/* s1 longer */
	if (*s2)
		return -1;				/* s2 longer */
	return 0;
}

/*
 * make_relative_path - make a path relative to the actual binary location
 *
 * This function exists to support relocation of installation trees.
 *
 *	ret_path is the output area (must be of size MAXPGPATH)
 *	target_path is the compiled-in path to the directory we want to find
 *	bin_path is the compiled-in path to the directory of executables
 *	my_exec_path is the actual location of my executable
 *
 * We determine the common prefix of target_path and bin_path, then compare
 * the remainder of bin_path to the last directory component(s) of
 * my_exec_path.  If they match, build the result as the part of my_exec_path
 * preceding the match, joined to the remainder of target_path.  If no match,
 * return target_path as-is.
 *
 * For example:
 *		target_path  = '/usr/local/share/postgresql'
 *		bin_path	 = '/usr/local/bin'
 *		my_exec_path = '/opt/pgsql/bin/postmaster'
 * Given these inputs, the common prefix is '/usr/local/', the tail of
 * bin_path is 'bin' which does match the last directory component of
 * my_exec_path, so we would return '/opt/pgsql/share/postgresql'
 */
static void
make_relative_path(char *ret_path, const char *target_path,
				   const char *bin_path, const char *my_exec_path)
{
	int			prefix_len;
	int			tail_start;
	int			tail_len;
	int			i;

	/*
	 * Determine the common prefix --- note we require it to end on a
	 * directory separator, consider eg '/usr/lib' and '/usr/libexec'.
	 */
	prefix_len = 0;
	for (i = 0; target_path[i] && bin_path[i]; i++)
	{
		if (IS_DIR_SEP(target_path[i]) && IS_DIR_SEP(bin_path[i]))
			prefix_len = i + 1;
		else if (target_path[i] != bin_path[i])
			break;
	}
	if (prefix_len == 0)
		goto no_match;			/* no common prefix? */
	tail_len = strlen(bin_path) - prefix_len;

	/*
	 * Set up my_exec_path without the actual executable name, and
	 * canonicalize to simplify comparison to bin_path.
	 */
	strlcpy(ret_path, my_exec_path, MAXPGPATH);
	trim_directory(ret_path);	/* remove my executable name */
	canonicalize_path(ret_path);

	/*
	 * Tail match?
	 */
	tail_start = (int) strlen(ret_path) - tail_len;
	if (tail_start > 0 &&
		IS_DIR_SEP(ret_path[tail_start - 1]) &&
		dir_strcmp(ret_path + tail_start, bin_path + prefix_len) == 0)
	{
		ret_path[tail_start] = '\0';
		trim_trailing_separator(ret_path);
		join_path_components(ret_path, ret_path, target_path + prefix_len);
		canonicalize_path(ret_path);
		return;
	}

no_match:
	strlcpy(ret_path, target_path, MAXPGPATH);
	canonicalize_path(ret_path);
}

/*
 * make_absolute_path
 *
 * If the given pathname isn't already absolute, make it so, interpreting
 * it relative to the current working directory.
 *
 * Also canonicalizes the path.  The result is always a malloc'd copy.
 *
 * In backend, failure cases result in ereport(ERROR); in frontend,
 * we write a complaint on stderr and return NULL.
 *
 * Note: interpretation of relative-path arguments during postmaster startup
 * should happen before doing ChangeToDataDir(), else the user will probably
 * not like the results.
 */
char *
make_absolute_path(const char *path)
{
	char	   *new;

	/* Returning null for null input is convenient for some callers */
	if (path == NULL)
		return NULL;

	if (!is_absolute_path(path))
	{
		char	   *buf;
		size_t		buflen;

		buflen = MAXPGPATH;
		for (;;)
		{
			buf = malloc(buflen);
			if (!buf)
			{
#ifndef FRONTEND
				ereport(ERROR,
						(errcode(ERRCODE_OUT_OF_MEMORY),
						 errmsg("out of memory")));
#else
				fprintf(stderr, _("out of memory\n"));
				return NULL;
#endif
			}

			if (getcwd(buf, buflen))
				break;
			else if (errno == ERANGE)
			{
				free(buf);
				buflen *= 2;
				continue;
			}
			else
			{
				int			save_errno = errno;

				free(buf);
				errno = save_errno;
#ifndef FRONTEND
				elog(ERROR, "could not get current working directory: %m");
#else
				fprintf(stderr, _("could not get current working directory: %s\n"),
						strerror(errno));
				return NULL;
#endif
			}
		}

		new = malloc(strlen(buf) + strlen(path) + 2);
		if (!new)
		{
			free(buf);
#ifndef FRONTEND
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
#else
			fprintf(stderr, _("out of memory\n"));
			return NULL;
#endif
		}
		sprintf(new, "%s/%s", buf, path);
		free(buf);
	}
	else
	{
		new = strdup(path);
		if (!new)
		{
#ifndef FRONTEND
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
#else
			fprintf(stderr, _("out of memory\n"));
			return NULL;
#endif
		}
	}

	/* Make sure punctuation is canonical, too */
	canonicalize_path(new);

	return new;
}

/*
 *	get_share_path
 */
void
get_share_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, PGSHAREDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_etc_path
 */
void
get_etc_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_include_path
 */
void
get_include_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_pkginclude_path
 */
void
get_pkginclude_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_includeserver_path
 */
void
get_includeserver_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
}

/*
 *	get_lib_path
 */
void
get_lib_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_pkglib_path
 */
void
get_pkglib_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_locale_path
 */
void
get_locale_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_doc_path
 */
void
get_doc_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_html_path
 */
void
get_html_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_man_path
 */
void
get_man_path(const char *my_exec_path, char *ret_path)
{
	make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
}

/*
 *	get_home_path
 *
 * On Unix, this actually returns the user's home directory.  On Windows
 * it returns the PostgreSQL-specific application data folder.
 */
bool
get_home_path(char *ret_path)
{
#ifndef WIN32
	char		pwdbuf[BUFSIZ];
	struct passwd pwdstr;
	struct passwd *pwd = NULL;

	(void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
	if (pwd == NULL)
		return false;
	strlcpy(ret_path, pwd->pw_dir, MAXPGPATH);
	return true;
#else
	char	   *tmppath;

	/*
	 * Note: We use getenv() here because the more modern SHGetFolderPath()
	 * would force the backend to link with shell32.lib, which eats valuable
	 * desktop heap.  XXX This function is used only in psql, which already
	 * brings in shell32 via libpq.  Moving this function to its own file
	 * would keep it out of the backend, freeing it from this concern.
	 */
	tmppath = getenv("APPDATA");
	if (!tmppath)
		return false;
	snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
	return true;
#endif
}

/*
 * get_parent_directory
 *
 * Modify the given string in-place to name the parent directory of the
 * named file.
 *
 * If the input is just a file name with no directory part, the result is
 * an empty string, not ".".  This is appropriate when the next step is
 * join_path_components(), but might need special handling otherwise.
 *
 * Caution: this will not produce desirable results if the string ends
 * with "..".  For most callers this is not a problem since the string
 * is already known to name a regular file.  If in doubt, apply
 * canonicalize_path() first.
 */
void
get_parent_directory(char *path)
{
	trim_directory(path);
}

/*
 *	trim_directory
 *
 *	Trim trailing directory from path, that is, remove any trailing slashes,
 *	the last pathname component, and the slash just ahead of it --- but never
 *	remove a leading slash.
 */
static void
trim_directory(char *path)
{
	char	   *p;

	path = skip_drive(path);

	if (path[0] == '\0')
		return;

	/* back up over trailing slash(es) */
	for (p = path + strlen(path) - 1; IS_DIR_SEP(*p) && p > path; p--)
		;
	/* back up over directory name */
	for (; !IS_DIR_SEP(*p) && p > path; p--)
		;
	/* if multiple slashes before directory name, remove 'em all */
	for (; p > path && IS_DIR_SEP(*(p - 1)); p--)
		;
	/* don't erase a leading slash */
	if (p == path && IS_DIR_SEP(*p))
		p++;
	*p = '\0';
}

/*
 *	trim_trailing_separator
 *
 * trim off trailing slashes, but not a leading slash
 */
static void
trim_trailing_separator(char *path)
{
	char	   *p;

	path = skip_drive(path);
	p = path + strlen(path);
	if (p > path)
		for (p--; p > path && IS_DIR_SEP(*p); p--)
			*p = '\0';
}


text:
layout: post
title: 'GREENHAM: ONE HUNDRED YEARS OF WAR & PEACE EVENT SURVEY'
date: 2017-09-20 14:24:27
main_image_path: /uploads/greenham-wp17-1.jpg
video_embed:
images:
  - image_path:
    description:
---

Around 5000 turned up to watch the final curtain call for Greenham: 100 Years of War and Peace. Greenham:WP17 was a large scale outdoor event celebrating 20 years of the Greenham Trust. On the evenings of the 8th and 9th September 2017 the story of Greenham Common came alive through an amazing spectacle of performance, songs, light projections and live art.

Did you attend the event?

If so we are keen to hear what you thought and would appreciate if you could complete the 2 minute feedback survey below;

[Please click here to take the survey](https://www.surveymonkey.co.uk/r/DL8DT7S)


text:
using System;

namespace _03.Megapixels
{
    class Program
    {
        static void Main(string[] args)
        {
            var width = double.Parse(Console.ReadLine());
            var height = double.Parse(Console.ReadLine());
            double image = (width * height) / 1000000;
            Console.WriteLine($"{width}x{height} => {Math.Round(image,1)}MP");
        }
    }
}


text:
> git clone git://github.com/nooodle/noodleconfware.git

Install node by using brew or through the website http://nodejs.org/#download

> cd noodleconfware

> cp local.json-dist local.json

> npm install

### Set up speaker whitelist

> cp speakers.json-dist speakers.json

Add your emails in that file

### Run the site

> node app.js

## Tests

> make test


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE glassfish-ejb-jar PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 EJB 3.1//EN" "http://glassfish.org/dtds/glassfish-ejb-jar_3_1-1.dtd">
<glassfish-ejb-jar>
    <enterprise-beans/>
</glassfish-ejb-jar>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2006 The Apache Software Foundation.

  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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.myfaces</groupId>
    <artifactId>myfaces</artifactId>
    <version>9</version>
  </parent>

  <groupId>org.apache.myfaces.trinidadbuild</groupId>
  <artifactId>maven-plugin-parent</artifactId>
  <version>1.2.14-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Apache Trinidad Maven Plugin Parent</name>

  <issueManagement>
    <system>jira</system>
    <url>http://issues.apache.org/jira/browse/TRINIDAD</url>
  </issueManagement>

  <ciManagement>
    <system>continuum</system>
    <url>http://myfaces.zones.apache.org:8080/continuum</url>
    <notifiers>
      <notifier>
        <type>mail</type>
        <sendOnSuccess>true</sendOnSuccess>
        <configuration>
          <address>commits@myfaces.apache.org</address>
        </configuration>
      </notifier>
    </notifiers>
  </ciManagement>

  <inceptionYear>2001</inceptionYear>

  <mailingLists>
    <mailingList>
      <name>MyFaces Users (use [Trinidad] prefix)</name>
      <post>users@myfaces.apache.org</post>
      <subscribe>users-subscribe@myfaces.apache.org</subscribe>
      <unsubscribe>users-unsubscribe@myfaces.apache.org</unsubscribe>
      <archive>http://mail-archives.apache.org/mod_mbox/myfaces-users/</archive>
    </mailingList>
    <mailingList>
      <name>MyFaces Developers (use [Trinidad] prefix)</name>
      <post>dev@myfaces.apache.org</post>
      <subscribe>dev-subscribe@myfaces.apache.org</subscribe>
      <unsubscribe>dev-unsubscribe@myfaces.apache.org</unsubscribe>
      <archive>http://mail-archives.apache.org/mod_mbox/myfaces-dev/</archive>
    </mailingList>
    <mailingList>
      <name>MyFaces issues</name>
      <post>Do not post</post>
      <subscribe>issues-subscribe@myfaces.apache.org</subscribe>
      <unsubscribe>issues-unsubscribe@myfaces.apache.org</unsubscribe>
      <archive>http://mail-archives.apache.org/mod_mbox/myfaces-issues/</archive>
    </mailingList>
    <mailingList>
      <name>MyFaces commits</name>
      <post>Do not post</post>
      <subscribe>commits-subscribe@myfaces.apache.org</subscribe>
      <unsubscribe>commits-unsubscribe@myfaces.apache.org</unsubscribe>
      <archive>http://mail-archives.apache.org/mod_mbox/myfaces-commits/</archive>
    </mailingList>
  </mailingLists>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <inherited>true</inherited>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <configuration>
          <preparationGoals>clean verify install</preparationGoals>
          <autoVersionSubmodules>true</autoVersionSubmodules>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-remote-resources-plugin</artifactId>
        <version>1.0-alpha-6</version>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <configuration>
              <resourceBundles>
                <resourceBundle>org.apache:apache-jar-resource-bundle:1.1</resourceBundle>
              </resourceBundles>
              <properties>
                <addLicense>true</addLicense>
              </properties>
            </configuration>
          </execution>
        </executions>
      </plugin>
	  <plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature> org.maven.ide.eclipse.maven2Nature</projectnature>
						<projectnature> org.eclipse.jem.workbench.JavaEMFNature</projectnature>
						<projectnature> org.eclipse.wst.jsdt.core.jsNature </projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand> org.maven.ide.eclipse.maven2Builder </buildcommand>
						<forceRecheck>true</forceRecheck>
					</additionalBuildcommands>
					<useProjectReferences>true</useProjectReferences>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
					<encoding>${project.build.sourceEncoding}</encoding>
					<projectNameTemplate>[artifactId]-[version]</projectNameTemplate>
				</configuration>
			</plugin>

		<plugin>
			<artifactId>maven-source-plugin</artifactId>
			<version>2.1.2</version>
			<executions>
			  <execution>
				<phase>package</phase>
				<goals>
				  <goal>jar</goal>
				</goals>
			  </execution>
			</executions>
       </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.8</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

    </plugins>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.1</version>
          <configuration>
            <archive>
              <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
              </manifest>
            </archive>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>2.0.1</version>
      </plugin>
      <plugin>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <rulesets>
            <ruleset>/rulesets/basic.xml</ruleset>
            <ruleset>/rulesets/unusedcode.xml</ruleset>
          </rulesets>
          <linkXref>true</linkXref>
          <minimumTokens>100</minimumTokens>
          <targetJdk>1.5</targetJdk>
        </configuration>
      </plugin>
    </plugins>
  </reporting>

  <scm>
    <connection>scm:svn:http://svn.apache.org/repos/asf/myfaces/trinidad-maven/trunk</connection>
    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/myfaces/trinidad-maven/trunk</developerConnection>
    <url>http://svn.apache.org/viewvc/myfaces/trinidad-maven/trunk</url>
  </scm>

  <modules>
    <module>maven-faces-plugin</module>
    <module>maven-javacc-plugin</module>
    <module>maven-i18n-plugin</module>
    <module>maven-jdev-plugin</module>
    <module>maven-javascript-plugin</module>
    <module>maven-xrts-plugin</module>
    <module>maven-tagdoc-plugin</module>
  </modules>

  <!--<distributionManagement>
    <site>
      <id>apache-site</id>
      <url>scpexe://minotaur.apache.org/www/myfaces.apache.org/trinidad/plugins/</url>
    </site>
  </distributionManagement> -->

  <distributionManagement>
    <repository>
      <id>Internal</id>
      <name>Logus Internal Repository</name>
      <url>http://maven.logusinfo.com.br/repository/internal/</url>
    </repository>
    <snapshotRepository>
      <id>Snapshots</id>
      <name>Snapshot Repository</name>
      <url>http://maven.logusinfo.com.br/repository/snapshots</url>
    </snapshotRepository>
  </distributionManagement>

  <!--
    NOTE: When preparing the release (mvn release:prepare) you may get an error when the
          plugin is committing the TAG
          There is an odd workaround for that:

          # mvn release:prepare -Papache-release
          => fails
          # svn up -r head
          # mvn release:prepare -Papache-release -Dresume

  -->
</project>


text:
#ifndef MOULETTE_TESTABLE_HH
# define MOULETTE_TESTABLE_HH

# include <string>
# include <boost/filesystem/path.hpp>

# include <moulette/test-result.hh>

namespace moulette
{
  class Testable
  {
  public:
    Testable();
    virtual ~Testable() {}

    void run();
    virtual bool isTestSuite() const = 0;
    virtual void set(const std::string & key, const std::string & value);
    virtual const TestResult & result() const = 0;
    virtual const std::string & name() const;
    virtual const std::string & type() const = 0;

    boost::filesystem::path path;

  protected:
    virtual void test() = 0;

    std::string name_;
  };
}

#endif /* !MOULETTE_TESTABLE_HH */


text:
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkTextCodec - Virtual class to act as an interface for all text codecs
//
// .SECTION Description
// A virtual class interface for codecs that readers/writers can rely on
//
// .SECTION Thanks
// Thanks to Tim Shed from Sandia National Laboratories for his work
// on the concepts and to Marcus Hanwell and Jeff Baumes of Kitware for
// keeping me out of the weeds
//
// .SECTION See Also
// vtkTextCodecFactory
//

#ifndef vtkTextCodec_h
#define vtkTextCodec_h

#include "vtkIOCoreModule.h" // For export macro
#include "vtkObject.h"
#include "vtkUnicodeString.h" // for the value type and for function return.

class VTKIOCORE_EXPORT vtkTextCodec : public vtkObject
{
public:
  vtkTypeMacro(vtkTextCodec, vtkObject);

  // Description:
  // The name this codec goes by - should match the string the factory will take
  // to create it
  virtual const char* Name();
  void PrintSelf(ostream& os, vtkIndent indent);

  virtual bool CanHandle(const char* NameString);

  // Description:
  // is the given sample valid for this codec?  The stream will not be advanced.
  virtual bool IsValid(istream& InputStream);

  // Description:
  // a base class that any output iterators need to derive from to use the first
  // signature of to_unicode.  Templates will not allow the vtable to
  // re-reference to the correct class so even though we only need the interface
  // we have to use derivation.
  class OutputIterator
  {
  public:
    virtual OutputIterator& operator++(int) = 0;
    virtual OutputIterator& operator*() = 0;
    virtual OutputIterator& operator=(const vtkUnicodeString::value_type value) = 0;

    OutputIterator() {}    virtual ~OutputIterator() {}

  private:
    OutputIterator(const OutputIterator&) VTK_DELETE_FUNCTION;
    const OutputIterator& operator=(const OutputIterator&) VTK_DELETE_FUNCTION;
  };

  // Description:
  // Iterate through the sequence represented by the stream assigning the result
  // to the output iterator.  The stream will be advanced to its end so
  // subsequent use would need to reset it.
  virtual void ToUnicode(istream& InputStream,
                         vtkTextCodec::OutputIterator& output) = 0;

  // Description:
  // convinience method to take data from the stream and put it into a
  // vtkUnicodeString.
  vtkUnicodeString ToUnicode(istream & inputStream);

  // Description:
  // Return the next code point from the sequence represented by the stream
  // advancing the stream through however many places needed to assemble that
  // code point.
  virtual vtkUnicodeString::value_type NextUnicode(istream& inputStream) = 0;

protected:
  vtkTextCodec();
  ~vtkTextCodec();

private:
  vtkTextCodec(const vtkTextCodec &) VTK_DELETE_FUNCTION;
  void operator=(const vtkTextCodec &) VTK_DELETE_FUNCTION;

};

#endif


text:
import os

def getRootDir():
    return os.path.join(os.getcwd(), os.path.dirname(__file__))


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Gallery</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/full-slider.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Fairytail

                        Wallpapers

                        Funny Gif

                        Fan Arts

Caption 3

Caption 3

Caption 3

Caption 3

Caption 3

Caption 3

Caption 3

Copyright © MMP 2017


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMethodsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('methods', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('file_id')->unsined()->nullable();
            $table->integer('method_type_id')->unsigned()->nullable();
            $table->string('name')->comment('方法名稱');
            $table->string('type')->comment('方法類型')->nullable();
            $table->string('description')->comment('方法描述');
            $table->timestamps();

            //foreign Key Set
            $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
            $table->foreign('method_type_id')->references('id')->on('method_types')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('methods');
    }
}


text:
redirect_to: deploy_keys.md#adding-deploy-keys-to-multiple-projects
---

This document was moved to [another location](deploy_keys.md#adding-deploy-keys-to-multiple-projects).


text:
let kuro
exports.init = function(bot) { kuro = bot }

exports.run = function(msg) {
	msg.delete()
	msg.channel.send('', {
		embed: {
			title: msg.guild.name,
			description: `Member Count: ${msg.guild.memberCount}`,
			color: kuro.config.embedColor
		}
	})
}


text:
require 'chef' / 'node'

class ChefServerSlice::Nodes < ChefServerSlice::Application

  provides :html, :json

  before :fix_up_node_id
  before :login_required
  before :authorized_node, :only => [ :update, :destroy ]

  def index
    @node_list = Chef::Node.list
    display(@node_list.collect { |n| absolute_slice_url(:node, escape_node_id(n)) })
  end

  def show
    begin
      @node = Chef::Node.load(params[:id])
    rescue Net::HTTPServerException => e
      raise NotFound, "Cannot load node #{params[:id]}"
    end
    display @node
  end

  def new
    @node = Chef::Node.new
    @available_recipes = get_available_recipes
    @available_roles = Chef::Role.list.sort
    @run_list = @node.run_list
    render
  end

  def edit
    begin
      @node = Chef::Node.load(params[:id])
    rescue Net::HTTPServerException => e
      raise NotFound, "Cannot load node #{params[:id]}"
    end
    @available_recipes = get_available_recipes
    @available_roles = Chef::Role.list.sort
    @run_list = @node.run_list
    render
  end

  def create
    if params.has_key?("inflated_object")
      @node = params["inflated_object"]
      exists = true
      begin
        Chef::Node.load(@node.name)
      rescue Net::HTTPServerException
        exists = false
      end
      raise Forbidden, "Node already exists" if exists
      self.status = 201
      @node.save
      display({ :uri => absolute_slice_url(:node, escape_node_id(@node.name)) })
    else
      begin
        @node = Chef::Node.new
        @node.name params[:name]
        @node.attribute = JSON.parse(params[:attributes])
        @node.run_list params[:for_node]
        @node.save
        redirect(slice_url(:nodes), :message => { :notice => "Created Node #{@node.name}" })
      rescue
        @node.attribute = JSON.parse(params[:attributes])
        @available_recipes = get_available_recipes
        @available_roles = Chef::Role.list.sort
        @run_list = params[:for_node]
        @_message = { :error => $! }
        render :new
      end
    end
  end

  def update
    begin
      @node = Chef::Node.load(params[:id])
    rescue Net::HTTPServerException => e
      raise NotFound, "Cannot load node #{params[:id]}"
    end

    if params.has_key?("inflated_object")
      updated = params['inflated_object']
      @node.run_list.reset(updated.run_list)
      @node.attribute = updated.attribute
      @node.save
      display(@node)
    else
      begin
        @node.run_list.reset(params[:for_node] ? params[:for_node] : [])
        @node.attribute = JSON.parse(params[:attributes])
        @node.save
        @_message = { :notice => "Updated Node" }
        render :show
      rescue
        @available_recipes = get_available_recipes
        @available_roles = Chef::Role.list.sort
        @run_list = Chef::RunList.new
        @run_list.reset(params[:for_node])
        render :edit
      end
    end
  end

  def destroy
    begin
      @node = Chef::Node.load(params[:id])
    rescue Net::HTTPServerException => e
      raise NotFound, "Cannot load node #{params[:id]}"
    end
    @node.destroy
    if request.accept == 'application/json'
      display @node
    else
      redirect(absolute_slice_url(:nodes), {:message => { :notice => "Node #{params[:id]} deleted successfully" }, :permanent => true})
    end
  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
North American species of Crepidotus 97 (1965)

#### Original name
Crepidotus fusisporus var. rameus Hesler & A.H. Sm.

### Remarks
null


text:
using DragonSpark.Model.Operations;
using Microsoft.AspNetCore.Identity;

namespace DragonSpark.Application.Security.Identity.Profile;

public interface ICreate<T> : ISelecting<Login<T>, IdentityResult> {}


text:
package unicredit.spark.hbase

import java.text.SimpleDateFormat
import java.util.{ Calendar, TreeSet, UUID }

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.permission.FsPermission
import org.apache.hadoop.fs.{ FileSystem, Path }
import org.apache.hadoop.hbase.client.{ HBaseAdmin, HTable }
import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.hadoop.hbase.mapreduce.{ HFileOutputFormat2, LoadIncrementalHFiles }
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.{ HColumnDescriptor, HTableDescriptor, KeyValue, TableName }
import org.apache.hadoop.mapreduce.Job
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner
import org.apache.spark.SparkContext.{ rddToOrderedRDDFunctions, rddToPairRDDFunctions }
import org.apache.spark.rdd.RDD
import org.apache.spark.{ Partitioner, SparkConf, SparkContext }

import scala.collection.JavaConversions.asScalaSet
import scala.reflect.ClassTag

trait HFileSupport {
  implicit def seqRddToHFileRdd[K: ClassTag, V](rdd: RDD[(K, Seq[V])]): HFileSeqRDD[K, V] = new HFileSeqRDD[K, V](rdd)

  implicit def mapRddToHFileRdd[K: ClassTag, C, V](rdd: RDD[(K, Map[C, V])]): HFileMapRDD[K, C, V] = new HFileMapRDD[K, C, V](rdd)

  /**
   * If the table exists, checks whether it contains the desired column family, and return false otherwise.
   * If table does not exist, computes the split keys and creates a table with the split keys and the
   * desired column family.
   *
   * @param tableName name of the table
   * @param cFamily name of the column family
   * @param filename path of the input tsv file
   * @param regionSize desired size of table regions, expressed as a number followed by B, K, M, G (e.g. "10G")
   * @param header name of the row key header, in case the tsv contains headers, it can be null otherwise
   *               the row key must be the first field in a tsv line
   * @param takeSnapshot if true and the table exists, take a snapshot of the table
   *
   * @return true if table exists or it is created and has the required column family, false otherwise
   */
  def prepareTable(tableName: String,
    cFamily: String,
    filename: String,
    regionSize: String,
    header: String,
    takeSnapshot: Boolean)(implicit config: HBaseConfig): Boolean =
    prepareTable(config.get, tableName, cFamily, takeSnapshot, computeSplits(config.get, filename, regionSize, header))

  /**
   * If the table exists, checks whether it contains the desired column family, and return false otherwise.
   * If table does not exist, computes the split keys and creates a table with the split keys and the
   * desired column family.
   *
   * @param tableName name of the table
   * @param cFamily name of the column family
   * @param keys RDD containing all the row keys, used to compute split keys in case the table does not exist,
   *             not used otherwise
   * @param splitsCount desired number of splits for the table, not used if table exists
   * @param takeSnapshot if true and the table exists, take a snapshot of the table
   *
   * @return true if table exists or it is created and has the required column family, false otherwise
   */
  def prepareTable(tableName: String,
    cFamily: String,
    keys: RDD[String],
    splitsCount: Int,
    takeSnapshot: Boolean)(implicit config: HBaseConfig): Boolean =
    prepareTable(config.get, tableName, cFamily, takeSnapshot, computeSplits(keys, splitsCount))

  private def prepareTable(conf: Configuration,
    tableName: String,
    cFamily: String,
    takeSnapshot: Boolean,
    computeSplits: => Seq[String]): Boolean = {
    val hBaseAdmin = new HBaseAdmin(conf)

    val tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName))

    if (hBaseAdmin.tableExists(tableName)) {
      // check if passed cFamily exists
      val families = hBaseAdmin.getTableDescriptor(tableName.getBytes).getFamiliesKeys
      if (!families.contains(cFamily.getBytes)) {
        println("\nTable [" + tableName + "] exists but column family [" + cFamily + "] is missing")
        print("column families found:")
        for (family <- families)
          print(" " + new String(family))
        println()
        return false
      }

      if (takeSnapshot) {
        val tName = tableDescriptor.getTableName
        val sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        val suffix = sdf.format(Calendar.getInstance().getTime)
        hBaseAdmin.snapshot(tableName + "_" + suffix, tName)
      }
    } else {
      tableDescriptor.addFamily(new HColumnDescriptor(cFamily))

      val splitKeys = computeSplits
      if (splitKeys.isEmpty)
        hBaseAdmin.createTable(tableDescriptor)
      else {
        val splitKeysBytes = splitKeys.map(_.getBytes).toArray
        hBaseAdmin.createTable(tableDescriptor, splitKeysBytes)
      }
    }
    true
  }

  private def computeSplits(rdd: RDD[String], splitsCount: Int): Seq[String] = {
    rdd.map((_, 1))
      .sortByKey(numPartitions = splitsCount)
      .mapPartitions(_.take(1))
      .map(_._1)
      .collect().toList.tail
  }

  private def computeSplits(conf: Configuration, filename: String, regionSizeStr: String, header: String): Seq[String] = {

    def computeSize(sizeString: String) = {
      val sizeReg = """^([0-9]+)(B|K|M|G)?$""".r
      sizeReg findFirstMatchIn sizeString match {
        case Some(m) =>
          val num = m.group(1).toLong
          m.group(2) match {
            case "B" => num
            case "K" => num * 1024
            case "M" => num * 1024 * 1024
            case "G" => num * 1024 * 1024 * 1024
            case _ => num
          }
        case None => throw new Exception
      }
    }

    val file = new Path(filename)
    val fs = file.getFileSystem(conf)
    val fileLength = fs.getContentSummary(file).getLength

    val regionSize = computeSize(regionSizeStr)
    val splitsCount = fileLength / regionSize + 1

    val sparkConf = new SparkConf().setAppName(this.getClass.getName.split('$')(0) + ".computeSplits")
    val sc = new SparkContext(sparkConf)

    val input = sc.textFile(filename)
      .map { line => line.split("\t").head }

    val inputNoHeader = if (header != null) input.filter(_ != header) else input
    val splits = computeSplits(inputNoHeader, splitsCount.toInt)

    sc.stop()

    splits
  }
}

case class KeyDuplicatedException(key: String) extends Exception(f"rowkey [${key}] is not unique")

sealed abstract class HFileRDD extends Serializable {

  implicit def asBytes(n: Any): Array[Byte] = n match {
    case b: Boolean => Bytes.toBytes(b)
    case d: Double => Bytes.toBytes(d)
    case f: Float => Bytes.toBytes(f)
    case i: Int => Bytes.toBytes(i)
    case l: Long => Bytes.toBytes(l)
    case s: Short => Bytes.toBytes(s)
    case s: String => Bytes.toBytes(s)
    case a: Array[Byte] => a
  }

  private class HFilePartitioner(conf: Configuration, splits: Array[Array[Byte]]) extends Partitioner {
    val fraction = conf.getInt(LoadIncrementalHFiles.MAX_FILES_PER_REGION_PER_FAMILY, 32)

    override def getPartition(key: Any): Int = {
      val h = (key.hashCode() & 0x7fffffff) % fraction
      for (i <- 1 until splits.length)
        if (Bytes.compareTo(key, splits(i)) < 0) return (i - 1) * fraction + h

      (splits.length - 1) * fraction + h
    }

    override def numPartitions: Int = splits.length * fraction
  }

  protected def loadToHBase[K: ClassTag, C, V](rdd: RDD[(K, Seq[(C, V)])], tableName: String, cFamilyStr: String)(implicit config: HBaseConfig) = {
    val conf = config.get
    val hTable = new HTable(conf, tableName)
    val cFamily = cFamilyStr.getBytes

    val job = new Job(conf, this.getClass.getName.split('$')(0))

    HFileOutputFormat2.configureIncrementalLoad(job, hTable)

    // prepare path for HFiles output
    val fs = FileSystem.get(conf)
    val hFilePath = new Path("/tmp", tableName + "_" + UUID.randomUUID())
    fs.makeQualified(hFilePath)

    try {
      rdd
        .partitionBy(new HFilePartitioner(conf, hTable.getStartKeys))
        .mapPartitions({ p =>
          p.toSeq.sortWith {
            (r1, r2) =>
              val ord = Bytes.compareTo(r1._1, r2._1)
              if (ord == 0) throw KeyDuplicatedException(r1._1.toString)
              ord < 0
          }.toIterator
        }, true)
        .flatMap {
          case (key, columns) =>
            val hKey = new ImmutableBytesWritable()
            hKey.set(key)
            val kvs = new TreeSet[KeyValue](KeyValue.COMPARATOR)
            for ((hb, v) <- columns) kvs.add(new KeyValue(hKey.get(), cFamily, hb, v))
            kvs.toSeq map (kv => (hKey, kv))
        }
        .saveAsNewAPIHadoopFile(hFilePath.toString, classOf[ImmutableBytesWritable], classOf[KeyValue], classOf[HFileOutputFormat2], job.getConfiguration)

      // prepare HFiles for incremental load
      // set folders permissions read/write/exec for all
      val rwx = new FsPermission("777")
      val listFiles = fs.listStatus(hFilePath)
      listFiles foreach { f =>
        fs.setPermission(f.getPath, rwx)
        // create a "_tmp" folder that can be used for HFile splitting, so that we can
        // set permissions correctly. This is a workaround for unsecured HBase. It should not
        // be necessary for SecureBulkLoadEndpoint (see https://issues.apache.org/jira/browse/HBASE-8495
        // and http://comments.gmane.org/gmane.comp.java.hadoop.hbase.user/44273)
        if (f.isDir) FileSystem.mkdirs(fs, new Path(f.getPath, "_tmp"), rwx)
      }

      val lih = new LoadIncrementalHFiles(conf)
      lih.doBulkLoad(hFilePath, hTable)
    } finally {
      fs.deleteOnExit(hFilePath)

      // clean HFileOutputFormat2 stuff
      fs.deleteOnExit(new Path(TotalOrderPartitioner.getPartitionFile(job.getConfiguration)))
    }
  }
}

final class HFileSeqRDD[K: ClassTag, V](seqRdd: RDD[(K, Seq[V])]) extends HFileRDD {
  /**
   * Load the underlying RDD to HBase, using HFiles.
   *
   * The RDD is assumed to be an instance of `RDD[(K, Seq[V])`,
   * where the first value is the rowkey and the second is a sequence of values to be
   * associated to column names in `headers`.
   */
  def loadToHBase(tableName: String, cFamilyStr: String, headers: Seq[String])(implicit config: HBaseConfig) = {
    val sc = seqRdd.context
    val headersBytes = sc.broadcast(headers map (_.getBytes))
    val rdd = seqRdd.map { case (k, v) => (k, headersBytes.value zip v) }
    super.loadToHBase(rdd, tableName, cFamilyStr)
  }
}

final class HFileMapRDD[K: ClassTag, C, V](mapRdd: RDD[(K, Map[C, V])]) extends HFileRDD {
  /**
   * Load the underlying RDD to HBase, using HFiles.
   *
   * The RDD is assumed to be an instance of `RDD[(K, Map[C, V])]`,
   * where the first value is the rowkey and the second is a map that
   * associates column names to values.
   */
  def loadToHBase(tableName: String, cFamilyStr: String)(implicit config: HBaseConfig) = {
    val rdd = mapRdd.map { case (k, cv) => (k, cv.toSeq) }
    super.loadToHBase(rdd, tableName, cFamilyStr)
  }
}


text:
/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/guide/browser-support
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

/** IE9, IE10, IE11, and Chrome <55 requires all of the following polyfills.
 *  This also includes Android Emulators with older versions of Chrome and Google Search/Googlebot
 */

// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';

/**
 * Web Animations `@angular/platform-browser/animations`
 * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
 * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
 */
// import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/**
 * By default, zone.js will patch all possible macroTask and DomEvents
 * user can disable parts of macroTask/DomEvents patch by setting following flags
 * because those flags need to be set before `zone.js` being loaded, and webpack
 * will put import in the top of bundle, so user need to create a separate file
 * in this directory (for example: zone-flags.ts), and put the following flags
 * into that file, and then add the following code before importing zone.js.
 * import './zone-flags.ts';
 *
 * The flags allowed in zone-flags.ts are listed here.
 *
 * The following flags will work for all browsers.
 *
 * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch
 * requestAnimationFrame
 * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
 * (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch
 * specified eventNames
 *
 *  in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
 *  with the following flag, it will bypass `zone.js` patch for IE/Edge
 *
 *  (window as any).__Zone_enable_cross_context_check = true;
 *
 */

/***************************************************************************************************
 * Zone JS is required by default for Angular itself.
 */
import 'zone.js/dist/zone'; // Included with Angular CLI.

/***************************************************************************************************
 * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
 */
import '@angular/localize/init';

// Note that `computeMsgId` is a private API at this stage. It will probably be exported directly
// from `@angular/localize` at some point.
import {computeMsgId} from '@angular/compiler';
import {loadTranslations} from '@angular/localize';

// Load some runtime translations
loadTranslations({
  // This message is in a template so it uses the legacy message id
  ['2f8d6ae7ef7b0a53392bc23d0968d074ae02a318']: 'Bonjour {$INTERPOLATION}!',
  // This message is in application code so it uses the normal message id
  [computeMsgId('Welcome to the i18n app.')]: 'Bienvenue sur l\'application i18n.',
});

/***************************************************************************************************
 * APPLICATION IMPORTS
 */


text:
<!DOCTYPE html>

<title>Canvas test: 2d.composite.transparent.destination-out</title>

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

2d.composite.transparent.destination-out

Actual output:

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

Expected output:


text:
from app import db
from app.models import User
from tests.test_base import BaseTest
from tests.testhelper import login

class LoginTest(BaseTest):
    def test_admin_login(self):
        admin = User(email='admin@example.com', password='adminpassword',
                     username='admin')
        admin.admin = True
        db.session().add(admin)
        db.session().commit()

        with self.client as c:
            rv = login(c, 'admin', 'adminpassword')
            self.assertTrue('admin_index_page_2382' in str(rv.data))

    def test_normal_login(self):
        user = User(email='john.doe@example.com', password='john1234', username='johnny')
        db.session().add(user)
        db.session().commit()

        with self.client as c:
            rv = login(c, 'johnny', 'john1234')
            self.assertTrue('index_page_7890' in str(rv.data))


text:
import junit.framework.TestCase;

public class AssertFalse extends TestCase {

  public void testOne() {
      assertFalse(result());
  }

  boolean result() {
    return false;
  }
}


text:
/**
 * Created by necklace on 2017/1/17.
 */
import React from "react";
import BaseComponent from "./BaseComponent";
import {ChainTypes as grapheneChainTypes} from "bitsharesjs";
import AltContainer from "alt-container";
import {RecentTransactions} from "./dashboard/Operation";

//stores
import AccountStore from "../stores/AccountStore";

const {operations} = grapheneChainTypes;

class LastOperation extends BaseComponent {
    constructor(props) {
        super(props);
    }
    getHistory(accountsList, filterOp, customFilter) {
        let history = [];
        let seen_ops = new Set();
        for (let account of accountsList) {
            if(account) {
                let h = account.get("history");
                if (h) history = history.concat(h.toJS().filter(op => !seen_ops.has(op.id) && seen_ops.add(op.id)));
            }
        }
        if (filterOp) {
            history = history.filter(a => {
                return a.op[0] === operations[filterOp];
            });
        }

        if (customFilter) {
            history = history.filter(a => {
                let finalValue = customFilter.fields.reduce((final, filter) => {
                    switch (filter) {
                        case "asset_id":
                            return final && a.op[1]["amount"][filter] === customFilter.values[filter];
                            break;
                        default:
                            return final && a.op[1][filter] === customFilter.values[filter];
                            break;
                    }
                }, true)
                return finalValue;
            });
        }
        return history;
    }

    render() {
        let {linkedAccounts} = this.props;
        let accountCount = linkedAccounts.size;

        return (

                        {this.formatMessage("lastOperation_operation")}
                        {this.formatMessage("lastOperation_info")}

                    {accountCount ? <RecentTransactions
                        accountsList={linkedAccounts}
                        limit={10}
                    /> :

                    }

        );
    }
}

class LastOperationContainer extends React.Component {
    render() {
        return (
            <AltContainer
                stores={[AccountStore]}
                inject={{
                    linkedAccounts: () => {
                        return AccountStore.getState().linkedAccounts;
                    }
                }}>
                <LastOperation/>
            </AltContainer>
        );
    }
}
export default LastOperationContainer;


text:
static const NSString *kCountryCode = @"country_code";
static const NSString *kCountry		= @"country";
static const NSString *kTown		= @"town";
static const NSString *kLocation	= @"geo";
static const NSString *kCoordinate	= @"pairs";

@implementation KivaLocation

- (id)initWithDictionary:(NSDictionary *)dictionary {
	if (self = [super init]) {
		_countryCode = [dictionary objectForKey:kCountryCode];
		_country = [dictionary objectForKey:kCountry];
		_town = [dictionary objectForKey:kTown];
		_coordinate = nil;

		NSDictionary *geo = [dictionary objectForKey:kLocation];
		if (geo) {
			NSString *cordinateValue = [geo objectForKey:kCoordinate];
			NSArray *values = [cordinateValue componentsSeparatedByString:@" "];
			if ([values count] >= 2) {
				_coordinate = [[CLLocation alloc] initWithLatitude:[[values objectAtIndex:0] doubleValue] longitude:[[values objectAtIndex:1] doubleValue]];
			}
		}
	}

	return self;
}

- (NSString *)description {
	return [NSString stringWithFormat:@"KivaLocation[countryCode = %@, country = %@, town = %@, coordinate = %@]",
			_countryCode,
			_country,
			_town,
			_coordinate];
}

@end


text:
package org.swtk.eng.tokenizer.chars;

import java.util.Map;

public class CharTokenizerResult {

	private Map<Integer, Character>		codes;

	private CharTokenizerContract	contract;

	private Map<String, Integer>		frequency;

	public Map<Integer, Character> getCodes() {
		return codes;
	}

	public CharTokenizerContract getContract() {
		return contract;
	}

	public Map<String, Integer> getFrequency() {
		return frequency;
	}

	public void setCodes(Map<Integer, Character> codes) {
		this.codes = codes;
	}

	public void setContract(CharTokenizerContract contract) {
		this.contract = contract;
	}

	public void setFrequency(Map<String, Integer> frequency) {
		this.frequency = frequency;
	}
}