text:
from collections import namedtuple

import asyncio
from asyncio import coroutine

from pyadds.annotate import cached, delayed, Conotate
from pyadds.str import name_of
from pyadds.logging import log

from .ctx import withtp, withctrl, withctx
from .idd import IdPath
from .packet import Tag

class Unit:
    """
    flo unit with the functionality the flow is build of
    """
    @withctx
    def __init__(self, *, ctx=None, name=None):
        self.name = name or name_of(self)
        self.id = ctx.register(self).id

    @coroutine
    def __setup__(self):
        pass

    @coroutine
    def __teardown__(self):
        pass

    @cached
    def ports(self):
        """ports of the unit"""
        return list(unbound.iter(self, bind=True))

    @property
    def inports(self):
        """ports for incoming data"""
        return [p for p in self.ports if p.kind == 'target']

    @property
    def outports(self):
        """outgoing data ports"""
        return [p for p in self.ports if p.kind == 'source']

    @property
    def inlinks(self):
        """incoming links"""
        return list(chain.from_iterable(p.links for p in self.inports))

    @property
    def outlinks(self):
        """outgoing links"""
        return list(chain.from_iterable(p.links for p in self.outports))

    @withtp
    def __or__(self, other, tp):
        # XXX add extraction to toplogoy
        tp.par(tp[self.id].space, tp[other.id].space)
        return other

    @withtp
    def __and__(self, other, tp):
        # XXX add extraction to toplogoy
        tp.join(tp[self.id].space, tp[other.id].space)
        return other

    @withtp
    def __pow__(self, n, tp):
        tp[self.id].space.replicate = n
        return self

    def __rshift__(self, other):
        self.out >> other
        return other

    def __rrshift__(self, other):
        other >> self.process
        return self

    def __sub__(self, other):
        return self.out -- other

    def __rsub__(self, other):
        return other -- self.process

    def __pos__(self):
        return self

    def __neg__(self):
        return self

    def __add__(self, insert):
        class Insert:
            def __rshift__(_, other):
                ( self -- other )
                ( self >> insert >> other )
                return other
        return Insert()

    @withctrl
    def join(self, ctrl):
        asyncio.get_event_loop().run_until_complete(
                ctrl.await(self))

    def __str__(self):
        return str(self.id)

    def __repr__(self):
        return repr(self.id)

class Sync(namedtuple('Sync', 'target, source')):
    def __call__(self, source, target):
        sy = lambda x: getattr(Syncs, x)
        out = sy(self.source)(source.path).prefixed('out-')
        ins = sy(self.target)(target.path).prefixed('in-')
        return out+ins.sub(1,)

class Syncs:
    """ port syncronization types"""
    def syncer(*args):
        path = None
        def sync(path):
            ids = tuple(path[s] for s in args if path[s])
            return IdPath(args, ids)
        sync.__name__ = args[-1] if args else 'any'
        return sync

    any = syncer('topology')
    space = syncer('topology', 'space')
    unit = syncer('topology', 'space', 'unit')
    port = syncer('topology', 'space', 'unit', 'port')

@log
class Port:
    def __init__(self, unit, name, definition, **hints):
        self.unit = unit
        self.name = name
        self.definition = definition
        self.hints = hints

    @cached
    def method(self):
        return self.definition.__get__(self.unit)

    @coroutine
    @withctrl
    def run(self, load=None, tag=None, ctrl=None, **kws):
        tp = ctrl.tp

        if tag is None:
            tag = Tag()
        tag = tag.add(**kws)

        self.__log.info('running {!r} >> {!r}'.format(load >> tag, self))

        # get context bla ...
        call = CallHelper()
        # XXX set call to be local ...
        tp.add_link(call.out, self)

        yield from ctrl.activate(call)

        yield from call.process(load, tag)

        yield from ctrl.await(call)
        yield from ctrl.close(call)

        tp.remove_links(call.out, self)
        tp.unregister(call)

    def async(self, *args, **kws):
        return self.run(*args, **kws)

    def execute(self, *args, **kws):
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(self.run(*args, **kws))

    @withctrl
    def delay(self, *args, ctrl, **kws):
        return ctrl.queue(self.run(*args, **kws))

    @property
    def __self__(self):
        return self.unit

    @property
    def __name__(self):
        return self.name

    def __call__(self, *args, **kws):
        loop = asyncio.get_event_loop()
        if loop.is_running():
            return self.method(*args, **kws)
        else:
            return self.execute(*args, **kws)

    def __str__(self):
        return '{}.{}'.format(self.unit, self.name)

    def __repr__(self):
        return '{!r}.{}'.format(self.unit, self.name)

    @withtp
    def __rshift__(self, other, tp):
        if not isinstance(other, Port):
            return NotImplemented
        tp.add_link(self, other)
        return other

    @withtp
    def __sub__(self, other, tp):
        if not isinstance(other, Port):
            return NotImplemented
        return tp.remove_links(self, other)

    def __pos__(self):
        return self

    def __neg__(self):
        return self

@log
class InPort(Port):
    __kind__ = 'target'

    @cached
    def handle(self):
        return self.method

@log
class OutPort(Port):
    __kind__ = 'source'

    @cached
    def channels(self):
        return []

    @coroutine
    def handle(self, pid, packet):
        self.__log.debug('no handler on %s for  %s by %s', self, packet, pid)

    @withctrl
    def __iter__(self, ctrl):
        tp = ctrl.tp
        run = asyncio.get_event_loop().run_until_complete

        self.__log.info('yielding from {!r}'.format(self))

        yld = YieldHelper()
        tp.add_link(self, yld.process)

        run(ctrl.activate(yld))
        run(ctrl.replay())
        yield from yld
        run(ctrl.close(yld))

        tp.remove_links(self, yld.process)
        tp.unregister(yld)

class unbound(Conotate, cached):
    __port__ = None
    hints = {'sync': Sync('unit', 'any')}

    def __default__(self, unit):
        return self.__port__(unit, self.name, self.definition, **self.hints)

class inport(unbound):
    __port__ = InPort

class outport(unbound):
    __port__ = OutPort

def sync(target='unit', source='any'):
    def annotate(port):
        port.hints['sync'] = Sync(target, source)
        return port
    return annotate

async = sync('port')

class Parts:
    def __init__(self, *args, **kws):
        super().__init__(*args, **kws)
        process, out = self.__flow__()
        if process:
            self.process = process
        if out:
            self.out = out

    def __rshift__(self, other):
        self.out >> other
        return other

    def __rrshift__(self, other):
        other >> self.process
        return self

    def iter(self, *args, **kws):
        self.process.delay(*args, **kws)
        yield from self.out

class part(cached):
    pass

class CallHelper(Unit):
    @outport
    def out(): pass

    @inport
    def process(self, load, tag):
        yield from load >> tag >> self.out

@log
class YieldHelper(Unit):
    @coroutine
    def __setup__(self):
        self.q = asyncio.Queue(8)

    @inport
    def process(self, load, tag):
        pk = load >> tag
        self.__log.debug('yielder got %s', pk)
        yield from self.q.put(pk)

    @withctrl
    def __iter__(self, ctrl):
        run = asyncio.get_event_loop().run_until_complete
        await = asyncio.async(ctrl.await(self))
        while True:
            get = asyncio.async(self.q.get())
            run(asyncio.wait([await, get],
                             return_when=asyncio.FIRST_COMPLETED))
            if get.done():
                yield get.result()
            if await.done():
                break

        while self.q.qsize():
            yield run(self.q.get())


text:
package main

import (
	"fmt"
)

func vardiacFun(fun string, params ...int) {
	fmt.Printf(" \"%s\" and Parameter type: %T\n", fun, params)
	fmt.Println(params)
	for _, elem := range params { //loop of the parameter
		fmt.Println(elem)
	}
}

func main() {
	vardiacFun("some", 1, 3, 4, 5, 6)
}

redpajama_set_name: RedPajamaGithub


text:
set(CTEST_SITE "aaargh.kitware.com")
set(CTEST_BUILD_CONFIGURATION Debug)
set(CTEST_CMAKE_GENERATOR "Unix Makefiles")
set(CTEST_BUILD_FLAGS "-k -j36")
set(CTEST_TEST_ARGS PARALLEL_LEVEL 36)

set(CTEST_BUILD_NAME "Linux-EL7_Clang5_ASan")
set(dashboard_model Nightly)
set(CTEST_DASHBOARD_ROOT ${CMAKE_CURRENT_BINARY_DIR}/${CTEST_BUILD_NAME})

include(${CMAKE_CURRENT_LIST_DIR}/../EnvironmentModules.cmake)
module(purge)

set(CTEST_MEMORYCHECK_TYPE "AddressSanitizer")
set(dashboard_do_memcheck ON)
set(dashboard_track "Analysis")

set(ENV{CC}  /opt/clang/latest/bin/clang)
set(ENV{CXX} /opt/clang/latest/bin/clang++)

set(dashboard_cache "
CMAKE_C_FLAGS=-fsanitize=address -fno-omit-frame-pointer
CMAKE_CXX_FLAGS=-fsanitize=address -fno-omit-frame-pointer

ADIOS2_USE_Fortran:STRING=OFF
")

include(${CMAKE_CURRENT_LIST_DIR}/../adios_common.cmake)


text:
#include "core/svg/SVGInteger.h"

#include "core/html/parser/HTMLParserIdioms.h"
#include "core/svg/SVGAnimationElement.h"

namespace blink {

SVGInteger::SVGInteger(int value)
    : m_value(value)
{
}

SVGInteger* SVGInteger::clone() const
{
    return create(m_value);
}

String SVGInteger::valueAsString() const
{
    return String::number(m_value);
}

SVGParsingError SVGInteger::setValueAsString(const String& string)
{
    m_value = 0;

    if (string.isEmpty())
        return SVGParseStatus::NoError;

    bool valid = true;
    m_value = stripLeadingAndTrailingHTMLSpaces(string).toIntStrict(&valid);
    // toIntStrict returns 0 if valid == false.
    return valid ? SVGParseStatus::NoError : SVGParseStatus::ExpectedInteger;
}

void SVGInteger::add(SVGPropertyBase* other, SVGElement*)
{
    setValue(m_value + toSVGInteger(other)->value());
}

void SVGInteger::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, SVGPropertyBase* from, SVGPropertyBase* to, SVGPropertyBase* toAtEndOfDuration, SVGElement*)
{
    ASSERT(animationElement);

    SVGInteger* fromInteger = toSVGInteger(from);
    SVGInteger* toInteger = toSVGInteger(to);
    SVGInteger* toAtEndOfDurationInteger = toSVGInteger(toAtEndOfDuration);

    float animatedFloat = m_value;
    animationElement->animateAdditiveNumber(percentage, repeatCount, fromInteger->value(), toInteger->value(), toAtEndOfDurationInteger->value(), animatedFloat);
    m_value = static_cast<int>(roundf(animatedFloat));
}

float SVGInteger::calculateDistance(SVGPropertyBase* other, SVGElement*)
{
    return abs(m_value - toSVGInteger(other)->value());
}

} // namespace blink


text:
#pragma once

#include "Base/BaseTypes.h"

namespace DAVA
{
/**
     \ingroup utils
     \brief Class to work with UTF8 strings
 */
namespace UTF8Utils
{
/**
    List of errors for SafeEncodeToWideString function
*/
enum eSafeEncodeError
{
    NONE = 0, //!< no errors
    NON_UTF8_SYMBOLS_REPLACED, //!< original string contains non-utf8 symbols which was replaced by '?'
    STRING_NOT_ENCODED //!< original string wasn't encoded
};

/**
        \brief convert UTF8 string to WideString
        \param[in] string string in UTF8 format
        \param[in] size size of buffer allocated for this string
        \param[out] resultString result unicode string
     */
void EncodeToWideString(const uint8* string, size_type size, WideString& resultString);

/**
        \brief convert UTF8 string to WideString without throwing utf8::exception
        \param[in] string string in UTF8 format
        \param[in] size size of buffer allocated for this string
        \param[out] resultString result unicode string
        \param[out] encodeError encoding error
*/
void SafeEncodeToWideString(const uint8* string, size_t size, WideString& result, eSafeEncodeError& encodeError);

/**
        \brief convert UTF8 string to WideString
        \param[in] utf8String string in UTF8 format
        \return string in unicode
     */
inline WideString EncodeToWideString(const String& utf8String)
{
    WideString str;
    EncodeToWideString(reinterpret_cast<const uint8*>(utf8String.c_str()), utf8String.length(), str);
    return str;
}

/**
        \brief convert UTF8 string to WideString without throwing utf8::exception
        \param[in] utf8String string in UTF8 format
        \param[out] encodeError encoding error
        \return string in unicode
*/
inline WideString SafeEncodeToWideString(const String& utf8String, eSafeEncodeError& encodeError)
{
    WideString str;
    SafeEncodeToWideString(reinterpret_cast<const uint8*>(utf8String.c_str()), utf8String.length(), str, encodeError);
    return str;
}
/**
     \brief convert WideString string to UTF8
     \param[in] wstring string in WideString format
     \returns string in UTF8 format, contained in DAVA::String
     */
String EncodeToUTF8(const WideString& wstring);
String EncodeToUTF8(const char32_t* str);

template <typename CHARTYPE>
String MakeUTF8String(const CHARTYPE* value);

template <>
inline String MakeUTF8String<char8>(const char8* value)
{
    return String(value);
}

template <>
inline String MakeUTF8String<char16>(const char16* value)
{
    return EncodeToUTF8(WideString(value));
}

template <>
inline String MakeUTF8String<char32_t>(const char32_t* value)
{
    return EncodeToUTF8(value);
}

/**
Trim whitespace at begin and end of specified UTF8 string.
Behavior depends by current system locale: http://en.cppreference.com/w/cpp/string/wide/iswspace
*/
String Trim(const String& str);

/**
Trim whitespace at begin of specified UTF8 string.
Behavior depends by current system locale: http://en.cppreference.com/w/cpp/string/wide/iswspace
*/
String TrimLeft(const String& str);

/**
Trim whitespace at end of specified UTF8 string.
Behavior depends by current system locale: http://en.cppreference.com/w/cpp/string/wide/iswspace
*/
String TrimRight(const String& str);

} // namespace UTF8Utils

//////////////////////////////////////////////////////////////////////////

} // namespace DAVA


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using FNVHasherDLL;
using System.Numerics;

namespace TS4_STBL_Editor
{
    public partial class Editor : Form
    {
        private DataGridViewSettings settings0 = new DataGridViewSettings();
        private DataGridViewSettings settings1 = new DataGridViewSettings();
        private DataGridViewSettings settings2 = new DataGridViewSettings();

        public DataGridView tempDataGridView;
        public delegate void UpdateProgressBar(double num);
        public UpdateProgressBar updateProgressBar;
        public DataTable dataTable;
        public bool isTextChanged = false;

        public Editor()
        {
            InitializeComponent();
        }
        private void Editor_Load(object sender, EventArgs e)
        {
            DataTable mainDataTable = new DataTable();

            DataColumn dc;
            dc = new DataColumn(dataGridView1.Columns[0].HeaderText);
            mainDataTable.Columns.Add(dc);
            dc = new DataColumn(dataGridView1.Columns[1].HeaderText);
            mainDataTable.Columns.Add(dc);
            dc = new DataColumn(dataGridView1.Columns[2].HeaderText);
            mainDataTable.Columns.Add(dc);
            DataRow dr;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                dr = mainDataTable.NewRow();
                dr[0] = dataTable.Rows[i][0];
                dr[1] = dataTable.Rows[i][1];
                dr[2] = dataTable.Rows[i][1];
                mainDataTable.Rows.Add(dr);
            }

            settings0.StoreSettings(dataGridView1, 0);
            settings1.StoreSettings(dataGridView1, 1);
            settings2.StoreSettings(dataGridView1, 2);

            dataGridView1.Columns.Clear();
            dataGridView1.DataSource = mainDataTable;

            RestoreDataGridViewSettings();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.HeaderCell.Value = (row.Index + 1).ToString();
                updateProgressBar((double)row.Index / (double)dataTable.Rows.Count);
            }
        }

        private void saveAndExit()
        {
            if (dataGridView1.Rows.Count != 0)
            {
                DataTable dt = (DataTable)dataGridView1.DataSource;
                DataTable tempDataTable = dataTable.Clone();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    tempDataTable.Rows.Add();
                    tempDataTable.Rows[i][0] = dt.Rows[i][0];
                    tempDataTable.Rows[i][1] = dt.Rows[i][2];
                }

                dataTable.Rows.Clear();
                dataTable = tempDataTable.Copy();
            }
            isTextChanged = true;
            Close();
        }

        private void OKBtn_Click(object sender, EventArgs e)
        {
            saveAndExit();
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Add_New_String_Click(object sender, EventArgs e)
        {
            AddString addString = new AddString();
            addString.ShowDialog();
            if (addString.isOK)
            {
                DataTable dt = (DataTable)dataGridView1.DataSource;
                DataRow dr;
                dr = dt.NewRow();
                dr[0] = addString.textID;
                dr[2] = addString.dataGridText;
                dt.Rows.Add(dr);
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].HeaderCell.Value = (dataGridView1.Rows.Count).ToString();
            }
            addString.Dispose();
        }

        private void RestoreDataGridViewSettings()
        {
            dataGridView1.Columns[0].AutoSizeMode = settings0.autoSizeColumnMode;
            dataGridView1.Columns[0].DefaultCellStyle = settings0.cellStyle;
            dataGridView1.Columns[0].DefaultHeaderCellType = settings0.defaultHeaderCellType;
            dataGridView1.Columns[0].Frozen = settings0.frozen;
            dataGridView1.Columns[0].HeaderText = settings0.headerText;
            dataGridView1.Columns[0].MinimumWidth = settings0.minimumWidth;
            dataGridView1.Columns[0].Name = settings0.name;
            dataGridView1.Columns[0].ReadOnly = settings0.readOnly;
            dataGridView1.Columns[0].Resizable = settings0.resizable;
            dataGridView1.Columns[0].SortMode = settings0.sortMode;
            dataGridView1.Columns[0].Width = settings0.width;

            dataGridView1.Columns[1].AutoSizeMode = settings1.autoSizeColumnMode;
            dataGridView1.Columns[1].DefaultCellStyle = settings1.cellStyle;
            dataGridView1.Columns[1].DefaultHeaderCellType = settings1.defaultHeaderCellType;
            dataGridView1.Columns[1].Frozen = settings1.frozen;
            dataGridView1.Columns[1].HeaderText = settings1.headerText;
            dataGridView1.Columns[1].MinimumWidth = settings1.minimumWidth;
            dataGridView1.Columns[1].Name = settings1.name;
            dataGridView1.Columns[1].ReadOnly = settings1.readOnly;
            dataGridView1.Columns[1].Resizable = settings1.resizable;
            dataGridView1.Columns[1].SortMode = settings1.sortMode;
            dataGridView1.Columns[1].Width = settings1.width;

            dataGridView1.Columns[2].AutoSizeMode = settings2.autoSizeColumnMode;
            dataGridView1.Columns[2].DefaultCellStyle = settings2.cellStyle;
            dataGridView1.Columns[2].DefaultHeaderCellType = settings2.defaultHeaderCellType;
            dataGridView1.Columns[2].Frozen = settings2.frozen;
            dataGridView1.Columns[2].HeaderText = settings2.headerText;
            dataGridView1.Columns[2].MinimumWidth = settings2.minimumWidth;
            dataGridView1.Columns[2].Name = settings2.name;
            dataGridView1.Columns[2].ReadOnly = settings2.readOnly;
            dataGridView1.Columns[2].Resizable = settings2.resizable;
            dataGridView1.Columns[2].SortMode = settings2.sortMode;
            dataGridView1.Columns[2].Width = settings2.width;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                MessageBox.Show("Value " +
                    dataGridView1.SelectedRows[0].Cells[0].Value.ToString() +
                    " - " + dataGridView1.SelectedRows[0].Cells[1].Value.ToString() +
                    " copied!");

                StringHolder sh = new StringHolder();
                sh.textIDFld = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                sh.displayTextFld = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();

                MainUI.copiedValuesStrHolders.Add(sh);
            }
        }

        private void Paste_ALL_copied_values_Click(object sender, EventArgs e)
        {
            for (int x = 0; x < MainUI.copiedValuesStrHolders.Count; x++)
            {
                StringHolder sh = MainUI.copiedValuesStrHolders[x];

                DataTable dt = (DataTable)dataGridView1.DataSource;
                DataRow dr;
                dr = dt.NewRow();
                dr[0] = sh.textIDFld;
                dr[2] = sh.displayTextFld;
                dt.Rows.Add(dr);
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].HeaderCell.Value = (dataGridView1.Rows.Count).ToString();

            }

        }

        private void Show_copied_values_Click(object sender, EventArgs e)
        {
            StringPicker sp = new StringPicker(null);
            sp.Show();
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {

            //if (dataGridView1.SelectedRows.Count > 0)
            //{
            //    if (e.Button == MouseButtons.Left)
            //    {
            //        //if (addstr != null)
            //        //{
            //        //    addstr.setFldsValues(MainUI.strHolders[listView1.SelectedIndices[0]]);
            //        //}
            //    }
            //    else
            //    {
            //        CopySelectedRows();
            //    }
            //}
        }

        //private void label3_Click(object sender, EventArgs e)
        //{
        //    HowToCopyMultipleRows a = new HowToCopyMultipleRows();
        //    a.ShowDialog();
        //}

        private void Copy_Values_By_IDs_Click(object sender, EventArgs e)
        {
            string idsStr = "";
            if (ShowInputDialog(ref idsStr) == DialogResult.OK)
            {
                string[] idsArray = idsStr.Split(new string[] { "," }, StringSplitOptions.None);
                for (int x = 0; x < idsArray.Length; x++)
                {
                    string id = idsArray[x];
                    if (id.Length > 3)
                    {

                        if (id.StartsWith("0x") || id.StartsWith("0X"))
                        {
                            id = id.Replace("0X", "0x");
                        }
                        else
                        {
                            id = FNVHasherStrFunctions.decimalToHex(id);
                        }

                        if (dataGridView1.Rows.Count != 0)
                        {
                            for (int i = 0; i < dataGridView1.Rows.Count; i++)
                            {
                                if (dataGridView1.Rows[i].Cells[0].Value.ToString().Equals(id))
                                {
                                    dataGridView1.Rows[i].Selected = true;
                                }
                            }

                        }
                    }
                }
                CopySelectedRows();
            }
        }

        private static DialogResult ShowInputDialog(ref string input)
        {
            System.Drawing.Size size = new System.Drawing.Size(400, 70);
            Form inputBox = new Form();

            inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            inputBox.ClientSize = size;
            inputBox.Text = "Enter ids, comma separated";

            System.Windows.Forms.TextBox textBox = new TextBox();
            textBox.Size = new System.Drawing.Size(size.Width - 10, 23);
            textBox.Location = new System.Drawing.Point(5, 5);
            textBox.Text = input;
            inputBox.Controls.Add(textBox);

            Button okButton = new Button();
            okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
            okButton.Name = "okButton";
            okButton.Size = new System.Drawing.Size(75, 23);
            okButton.Text = "&OK";
            okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);
            inputBox.Controls.Add(okButton);

            Button cancelButton = new Button();
            cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            cancelButton.Name = "cancelButton";
            cancelButton.Size = new System.Drawing.Size(75, 23);
            cancelButton.Text = "&Cancel";
            cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);
            inputBox.Controls.Add(cancelButton);

            inputBox.AcceptButton = okButton;
            inputBox.CancelButton = cancelButton;

            DialogResult result = inputBox.ShowDialog();
            input = textBox.Text;
            return result;
        }

        private void Copy_selected_rows_Click(object sender, EventArgs e)
        {
            //CopySelectedRows();
        }

        private void CopySelectedRows()
        {
            for (int x = 0; x < dataGridView1.SelectedRows.Count; x++)
            {
                StringHolder sh = new StringHolder();
                sh.textIDFld = dataGridView1.SelectedRows[x].Cells[0].Value.ToString();
                sh.displayTextFld = dataGridView1.SelectedRows[x].Cells[1].Value.ToString();

                MainUI.copiedValuesStrHolders.Add(sh);
            }

            MessageBox.Show(dataGridView1.SelectedRows.Count + " rows copied!");
        }

        private void deleteThisElementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cell = contextMenuStrip1.Tag as DataGridViewCell;

            var confirmResult = MessageBox.Show("Are you sure to delete this item ??",
                                     "Confirm Delete!!",
                                     MessageBoxButtons.YesNo);
            if (confirmResult == DialogResult.Yes)
            {
                dataGridView1.Rows.RemoveAt(cell.OwningRow.Index);

            }
            else
            {
                // If 'No', do something here.
            }
        }

        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                dataGridView1.CurrentCell.OwningRow.Selected = true;
                contextMenuStrip1.Tag = dataGridView1.CurrentCell;
                contextMenuStrip1.Show(dataGridView1, e.Location);
            }

        }

        private void copyThisRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cell = contextMenuStrip1.Tag as DataGridViewCell;
            var row = cell.OwningRow;
            StringHolder sh = new StringHolder();
            sh.textIDFld = row.Cells[0].Value.ToString();
            sh.displayTextFld = row.Cells[1].Value.ToString();

            MainUI.copiedValuesStrHolders.Add(sh);
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
            {
                this.Close();
                return true;
            } else
            {
                if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.S) == Keys.S)  // Ctrl-S Save
                {
                    saveAndExit();
                }
            }
            return base.ProcessDialogKey(keyData);
        }

        private void copySelectedRowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopySelectedRows();
        }
    }
}


text:
using namespace std;
using boost::shared_ptr;

boost::shared_ptr<FileInterface> FileInterface::createFileInterface(const std::string& type,
                                                                    const std::string& name,
                                                                    bool framed) {
  if (0 == type.compare("std")) {
    return shared_ptr<FileInterface>(new StdFile(name, framed));
  } else if (0 == type.compare("hdfs")) {
    return shared_ptr<FileInterface>(new HdfsFile(name));
  } else {
    return shared_ptr<FileInterface>();
  }
}

std::vector<std::string> FileInterface::list(const std::string& path, const std::string &fsType) {
  std::vector<std::string> files;
  shared_ptr<FileInterface> concrete_file = createFileInterface(fsType, path);
  if (concrete_file) {
    concrete_file->listImpl(path, files);
  }
  return files;
}

FileInterface::FileInterface(const std::string& name, bool frame)
  : framed(frame), filename(name) {
}

FileInterface::~FileInterface() {
}

StdFile::StdFile(const std::string& name, bool frame)
  : FileInterface(name, frame), inputBuffer(NULL), bufferSize(0) {
}

StdFile::~StdFile() {
  if (inputBuffer) {
    delete[] inputBuffer;
    inputBuffer = NULL;
  }
}

bool StdFile::openRead() {
  return open(fstream::in);
}

bool StdFile::openWrite() {
  // open file for write in append mode
  ios_base::openmode mode = fstream::out | fstream::app;
  return open(mode);
}

bool StdFile::openTruncate() {
  // open an existing file for write and truncate its contents
  ios_base::openmode mode = fstream::out | fstream::app | fstream::trunc;
  return open(mode);
}

bool StdFile::open(ios_base::openmode mode) {

  if (file.is_open()) {
    return false;
  }

  file.open(filename.c_str(), mode);

  return file.good();
}

bool StdFile::isOpen() {
  return file.is_open();
}

void StdFile::close() {
  if (file.is_open()) {
    file.close();
  }
}

string StdFile::getFrame(unsigned data_length) {

  if (framed) {
    char buf[UINT_SIZE];
    serializeUInt(data_length, buf);
    return string(buf, UINT_SIZE);

  } else {
    return string();
  }
}

bool StdFile::write(const std::string& data) {

  if (!file.is_open()) {
    return false;
  }

  file << data;
  if (file.bad()) {
    return false;
  }
  return true;
}

void StdFile::flush() {
  if (file.is_open()) {
    file.flush();
  }
}

bool StdFile::readNext(std::string& _return) {

  if (!inputBuffer) {
    bufferSize = INITIAL_BUFFER_SIZE;
    inputBuffer = new char[bufferSize];
  }

  if (framed) {
    unsigned size;
    file.read(inputBuffer, UINT_SIZE);  // assumes INITIAL_BUFFER_SIZE > UINT_SIZE
    if (file.good() && (size = unserializeUInt(inputBuffer))) {

      // check if size is larger than half the max uint size
      if (size >= (((unsigned)1) << (UINT_SIZE*8 - 1))) {
        LOG_OPER("WARNING: attempting to read message of size %d bytes", size);

        // Do not try to make bufferSize any larger than this or you might overflow
        bufferSize = size;
      }

      while (size > bufferSize) {
        bufferSize = 2 * bufferSize;
        delete[] inputBuffer;
        inputBuffer = new char[bufferSize];
      }
      file.read(inputBuffer, size);
      if (file.good()) {
        _return.assign(inputBuffer, size);
        return true;
      } else {
        int offset = file.tellg();
        LOG_OPER("ERROR: Failed to read file %s at offset %d",
                 filename.c_str(), offset);
        return false;
      }
    }
  } else {
    file.getline(inputBuffer, bufferSize);
    if (file.good()) {
      _return = inputBuffer;
      return true;
    }
  }
  return false;
}

unsigned long StdFile::fileSize() {
  unsigned long size = 0;
  try {
    size = boost::filesystem::file_size(filename.c_str());
  } catch(std::exception const& e) {
    LOG_OPER("Failed to get size for file <%s> error <%s>", filename.c_str(), e.what());
    size = 0;
  }
  return size;
}

void StdFile::listImpl(const std::string& path, std::vector<std::string>& _return) {
  try {
    if (boost::filesystem::exists(path)) {
      boost::filesystem::directory_iterator dir_iter(path), end_iter;

      for ( ; dir_iter != end_iter; ++dir_iter) {
        _return.push_back(dir_iter->filename());
      }
    }
  } catch (std::exception const& e) {
    LOG_OPER("exception <%s> listing files in <%s>",
             e.what(), path.c_str());
  }
}

void StdFile::deleteFile() {
  boost::filesystem::remove(filename);
}

bool StdFile::createDirectory(std::string path) {
  try {
    boost::filesystem::create_directory(path);
  } catch(std::exception const& e) {
    LOG_OPER("Exception < %s > trying to create directory", e.what());
    return false;
  }

  return true;
}

bool StdFile::createSymlink(std::string oldpath, std::string newpath) {
  if (symlink(oldpath.c_str(), newpath.c_str()) == 0) {
    return true;
  }

  return false;
}

// Buffer had better be at least UINT_SIZE long!
unsigned FileInterface::unserializeUInt(const char* buffer) {
  unsigned retval = 0;
  int i;
  for (i = 0; i < UINT_SIZE; ++i) {
    retval |= (unsigned char)buffer[i] << (8 * i);
  }
  return retval;
}

void FileInterface::serializeUInt(unsigned data, char* buffer) {
  int i;
  for (i = 0; i < UINT_SIZE; ++i) {
    buffer[i] = (unsigned char)((data >> (8 * i)) & 0xFF);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:x="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="60dp"
    x:ngScope="Login"
    tools:ignore="MissingPrefix" >

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/password"
        x:ngModel="user.username" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:layout_above="@+id/submit"
        x:ngModel="user.password"/>

    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_centerInParent="true"
        x:ngDisabled="user.username.length() < 6 || user.password.length() < 6"
        x:ngClick="onSubmit($view.context)"/>

    <Button
        android:id="@+id/hidden"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        x:ngClick="intArg(@id/submit)"/>

</RelativeLayout>


text:
thus
====

Create a JavaScript scope in which ```thus```'s first argument is referred to as ```this```.

This is primarily a convenience function for writing CoffeeScript:

```coffeescript
thus express(), ->
	@set 'view engine', 'jade'
	@listen 8080
```

Expressed in JS, that would be:

```javascript
thus(express(), function() {
	this.set('view engine', 'jade');
	this.listen(8080);
});
```

Which is functionally equivalent to:

```javascript
var app = express();
app.set('view engine', 'jade');
app.listen(8080);
```

Might seem stupid, but I like writing code this way.


text:
<?xml version="1.0" ?>
<!-- ========================================================================== -->
<!-- AccountQueryRq.xml                                                         -->
<!--                                                                            -->
<!-- INTUIT CONFIDENTIAL.                                                       -->
<!-- Copyright (c) 2001-2013 Intuit Inc. All rights reserved.                   -->
<!-- Use is subject to the terms specified at:                                  -->
<!--          http://developer.intuit.com/legal/devsite_tos.html                -->
<!--                                                                            -->
<!--                                                                            -->
<!-- ========================================================================== -->
<!-- Summary: Sample illustrating the account query request.                    -->
<!-- This XML file contains a single request to query accounts.                 -->
<!--                                                                            -->
<!-- Description:                                                               -->
<!-- This XML file contains a single request to query all accounts. It does not -->
<!-- filter the output so lots of accounts could cause this to be a bit slow.   -->
<!-- ========================================================================== -->
<!-- Language: xml                                                            -->
<!-- Structure: QBXML                                                            -->
<!-- QuickBooks: any                                                            -->
<!-- Deployment: any                                                            -->
<!-- ========================================================================== -->
<?qbxml version="3.0"?>
<QBXML>
   <QBXMLMsgsRq onError="stopOnError">
      <AccountQueryRq requestID="1">
      </AccountQueryRq>
   </QBXMLMsgsRq>
</QBXML>


text:
service redis-server start

exec sudo -u app morbo -l "http://*:3001" /app/chat.pl


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rc. Secc. Accad. Sci. Ist. Bologna, sér. 6 6: 123 (1909)

#### Original name
Pilobolus borzianus var. geminatus Morini, 1909

### Remarks
null


text:
function dbSize() {
  return db.stats().fileSize/(1024*1024) + " MiB";
}

print("DB file size: " + dbSize())
print()

print("Dropping all collections...")
var droppedCount = 0;
var colls = db.getCollectionNames();
for (i in colls) {
  var name = colls[i];
  if (name.startsWith("system.") || name.startsWith("Slam")) {
    print("  not dropped: " + name);
  }
  else {
    var col = db.getCollection(name);
    //print("dropping " + name + " (" + col.totalSize()/(1024*1024.0) + " MB)");
    var dropped = col.drop();
    if (!dropped) print("  drop failed: " + name + "; " + db.getLastError());
    else droppedCount += 1;
  }
}
print("  dropped " + droppedCount + " collections")
print()

print("Recovering unused space...")
db.repairDatabase()
print("  done")
print()

print("DB file size: " + dbSize())
print()


text:
package org.elasticsearch.update;

import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.DocumentMissingException;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalSettingsPlugin;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;

public class TimestampTTLBWIT extends ESIntegTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Arrays.asList(
                UpdateIT.FieldIncrementScriptPlugin.class,
                UpdateIT.ExtractContextInSourceScriptPlugin.class,
                UpdateIT.PutFieldValuesScriptPlugin.class,
                InternalSettingsPlugin.class
        );
    }

    public void testSort() throws Exception {
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_timestamp").field("enabled", true).endObject()
                .endObject().endObject();
        assertAcked(prepareCreate("test")
                .setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id)
                .addMapping("type", mapping));
        ensureGreen();
        final int numDocs = randomIntBetween(10, 20);
        IndexRequestBuilder[] indexReqs = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; ++i) {
            indexReqs[i] = client().prepareIndex("test", "type", Integer.toString(i)).setTimestamp(Integer.toString(randomInt(1000)))
                    .setSource();
        }
        indexRandom(true, indexReqs);

        SortOrder order = randomFrom(SortOrder.values());

        SearchResponse searchResponse = client().prepareSearch()
                .setQuery(matchAllQuery())
                .setSize(randomIntBetween(1, numDocs + 5))
                .addSort("_timestamp", order)
                .addField("_timestamp")
                .execute().actionGet();
        assertNoFailures(searchResponse);
        SearchHit[] hits = searchResponse.getHits().hits();
        Long previousTs = order == SortOrder.ASC ? 0 : Long.MAX_VALUE;
        for (int i = 0; i < hits.length; ++i) {
            SearchHitField timestampField = hits[i].getFields().get("_timestamp");
            Long timestamp = timestampField.<Long>getValue();
            assertThat(previousTs, order == SortOrder.ASC ? lessThanOrEqualTo(timestamp) : greaterThanOrEqualTo(timestamp));
            previousTs = timestamp;
        }
    }

    public void testUpdate() throws Exception {
        assertAcked(prepareCreate("test").addAlias(new Alias("alias"))
                .setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id)
                .addMapping("type1", XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("type1")
                        .startObject("_timestamp").field("enabled", true).endObject()
                        .startObject("_ttl").field("enabled", true).endObject()
                        .endObject()
                        .endObject()));

        ensureGreen();

        try {
            client().prepareUpdate(indexOrAlias(), "type1", "1")
                    .setScript(new Script("field", ScriptService.ScriptType.INLINE, "field_inc", null)).execute().actionGet();
            fail();
        } catch (DocumentMissingException e) {
            // all is well
        }

        // check TTL is kept after an update without TTL
        client().prepareIndex("test", "type1", "2").setSource("field", 1).setTTL(86400000L).setRefreshPolicy(IMMEDIATE).get();
        GetResponse getResponse = client().prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet();
        long ttl = ((Number) getResponse.getField("_ttl").getValue()).longValue();
        assertThat(ttl, greaterThan(0L));
        client().prepareUpdate(indexOrAlias(), "type1", "2")
                .setScript(new Script("field", ScriptService.ScriptType.INLINE, "field_inc", null)).execute().actionGet();
        getResponse = client().prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet();
        ttl = ((Number) getResponse.getField("_ttl").getValue()).longValue();
        assertThat(ttl, greaterThan(0L));

        // check TTL update
        client().prepareUpdate(indexOrAlias(), "type1", "2")
                .setScript(new Script("", ScriptService.ScriptType.INLINE, "put_values",
                        Collections.singletonMap("_ctx", Collections.singletonMap("_ttl", 3600000)))).execute().actionGet();
        getResponse = client().prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet();
        ttl = ((Number) getResponse.getField("_ttl").getValue()).longValue();
        assertThat(ttl, greaterThan(0L));
        assertThat(ttl, lessThanOrEqualTo(3600000L));

        // check timestamp update
        client().prepareIndex("test", "type1", "3").setSource("field", 1).setRefreshPolicy(IMMEDIATE).get();
        client().prepareUpdate(indexOrAlias(), "type1", "3")
                .setScript(new Script("", ScriptService.ScriptType.INLINE, "put_values",
                        Collections.singletonMap("_ctx", Collections.singletonMap("_timestamp", "2009-11-15T14:12:12")))).execute()
                .actionGet();
        getResponse = client().prepareGet("test", "type1", "3").setFields("_timestamp").execute().actionGet();
        long timestamp = ((Number) getResponse.getField("_timestamp").getValue()).longValue();
        assertThat(timestamp, equalTo(1258294332000L));
    }

    public void testContextVariables() throws Exception {
        assertAcked(prepareCreate("test").addAlias(new Alias("alias"))
                        .setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id)
                        .addMapping("type1", XContentFactory.jsonBuilder()
                                .startObject()
                                .startObject("type1")
                                .startObject("_timestamp").field("enabled", true).endObject()
                                .startObject("_ttl").field("enabled", true).endObject()
                                .endObject()
                                .endObject())
                        .addMapping("subtype1", XContentFactory.jsonBuilder()
                                .startObject()
                                .startObject("subtype1")
                                .startObject("_parent").field("type", "type1").endObject()
                                .startObject("_timestamp").field("enabled", true).endObject()
                                .startObject("_ttl").field("enabled", true).endObject()
                                .endObject()
                                .endObject())
        );
        ensureGreen();

        // Index some documents
        long timestamp = System.currentTimeMillis();
        client().prepareIndex()
                .setIndex("test")
                .setType("type1")
                .setId("parentId1")
                .setTimestamp(String.valueOf(timestamp-1))
                .setSource("field1", 0, "content", "bar")
                .execute().actionGet();

        long ttl = 10000;
        client().prepareIndex()
                .setIndex("test")
                .setType("subtype1")
                .setId("id1")
                .setParent("parentId1")
                .setRouting("routing1")
                .setTimestamp(String.valueOf(timestamp))
                .setTTL(ttl)
                .setSource("field1", 1, "content", "foo")
                .execute().actionGet();

        // Update the first object and note context variables values
        UpdateResponse updateResponse = client().prepareUpdate("test", "subtype1", "id1")
                .setRouting("routing1")
                .setScript(new Script("", ScriptService.ScriptType.INLINE, "extract_ctx", null))
                .execute().actionGet();

        assertEquals(2, updateResponse.getVersion());

        GetResponse getResponse = client().prepareGet("test", "subtype1", "id1").setRouting("routing1").execute().actionGet();
        Map<String, Object> updateContext = (Map<String, Object>) getResponse.getSourceAsMap().get("update_context");
        assertEquals("test", updateContext.get("_index"));
        assertEquals("subtype1", updateContext.get("_type"));
        assertEquals("id1", updateContext.get("_id"));
        assertEquals(1, updateContext.get("_version"));
        assertEquals("parentId1", updateContext.get("_parent"));
        assertEquals("routing1", updateContext.get("_routing"));
        assertThat(((Integer) updateContext.get("_ttl")).longValue(), allOf(greaterThanOrEqualTo(ttl-3000), lessThanOrEqualTo(ttl)));

        // Idem with the second object
        updateResponse = client().prepareUpdate("test", "type1", "parentId1")
                .setScript(new Script("", ScriptService.ScriptType.INLINE, "extract_ctx", null))
                .execute().actionGet();

        assertEquals(2, updateResponse.getVersion());

        getResponse = client().prepareGet("test", "type1", "parentId1").execute().actionGet();
        updateContext = (Map<String, Object>) getResponse.getSourceAsMap().get("update_context");
        assertEquals("test", updateContext.get("_index"));
        assertEquals("type1", updateContext.get("_type"));
        assertEquals("parentId1", updateContext.get("_id"));
        assertEquals(1, updateContext.get("_version"));
        assertNull(updateContext.get("_parent"));
        assertNull(updateContext.get("_routing"));
        assertNull(updateContext.get("_ttl"));
    }

    private static String indexOrAlias() {
        return randomBoolean() ? "test" : "alias";
    }
}


text:
//
//  VhDeviceBind.m
//  HomeMate
//
//  Created by Orvibo on 15/8/12.
//  Copyright © 2017年 Orvibo. All rights reserved.
//

#import "HMDeviceBind.h"
#import "HMDeviceConfig.h"
#import "BLUtility.h"
#import "DeviceUnbindCmd.h"
#import "HMConstant.h"
#import "DeviceUnbindCmd.h"

@interface HMDeviceBind ()
@property (assign, nonatomic)int serialNumber;
@end

@implementation HMDeviceBind

/**
 *  解绑设备
 *
 *  @param device
 */
- (void)unBindDevice:(HMAPDevice *)device callback:(BindCallback)callback {

    DLog(@"一直解绑");
    if (self.isStop) {
        DLog(@"---------------绑定成功,停止解绑----------------");

        return;
    }

    DeviceUnbindCmd *deviceUnbind = [DeviceUnbindCmd object];
    if (self.serialNumber == 0) {
        self.serialNumber = [BLUtility getTimestamp];
    }

    // 固定流水号,多次发送时只缓存一个指令
    deviceUnbind.serialNo = self.serialNumber;

    DLog(@"---------------发送解绑命令 serialNumber  %d----------------",self.serialNumber);

    if (device.mac.length) {
        deviceUnbind.uid = device.mac;
    }else {
        deviceUnbind.uid = @"";
        DLog(@"解绑Uid 为空");

    }
    deviceUnbind.sendToServer = YES;
    DLog(@"-------------------ap 解绑 发送解绑命令--------------------------");
    sendCmd(deviceUnbind, ^(KReturnValue returnValue, NSDictionary *returnDic){
        if (returnValue == KReturnValueSuccess){
            self.serialNumber = 0;
            DLog(@"-------------------ap 解绑成功 直接发送绑定命令--------------------------");
            [HMAPConfigAPI startBindDevice];
            DLog(@"解绑成功");

        }else if (returnValue == KReturnValueMainframeDisconnect
                  || returnValue == KReturnValueConnectError) {
            DLog(@"解绑网络不存在,再次发送解绑命令");
            sleep(1);
            [self unBindDevice:device callback:callback];

        }else {
            callback(KReturnValueServerUnbindFail,returnDic);
        }
    });

}
/**
 *  绑定设备
 *
 *  @param device
 *  @param callback
 */
- (void)bindDevice:(HMAPDevice *)device callback:(BindCallback)callback {

    DLog(@"-----------解绑成功,开始绑定-------------");

    [self bindWifiDevice:device callback:callback];

}
- (void)bindWifiDevice:(HMAPDevice *)device callback:(BindCallback)callback {

    DeviceBindCmd * cmd  = [[DeviceBindCmd alloc] init];
    cmd.bindUID = device.mac ?: @"";
    cmd.ssid = [HMDeviceConfig defaultConfig].ssid;

    [self sendBindCmd:cmd callback:callback];

}

- (void)sendBindCmd:(DeviceBindCmd *)cmd callback:(BindCallback)callback {

    DLog(@"-----------解绑成功,发送绑定命令-------------");

    sendCmd(cmd, ^(KReturnValue returnValue, NSDictionary *returnDic) {
        callback(returnValue, returnDic);

    });
}

/**
 *  是否取消绑定
 *
 *  @param isStop
 */
- (void)stopBindDevice:(BOOL)isStop {
    self.isStop = isStop;
}
@end


text:
FOUNDATION_EXPORT double ApplicativeSwiftVersionNumber;

//! Project version string for ApplicativeSwift.
FOUNDATION_EXPORT const unsigned char ApplicativeSwiftVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <ApplicativeSwift/PublicHeader.h>


text:
'use strict';

var ReactElement = require('ReactElement');
var ReactInstanceHandles = require('ReactInstanceHandles');
var ReactMarkupChecksum = require('ReactMarkupChecksum');
var ReactServerRenderingTransaction =
  require('ReactServerRenderingTransaction');

var emptyObject = require('emptyObject');
var instantiateReactComponent = require('instantiateReactComponent');
var invariant = require('invariant');

/**
 * @param {ReactElement} element
 * @return {string} the HTML markup
 */
function renderToString(element) {
  invariant(
    ReactElement.isValidElement(element),
    'renderToString(): You must pass a valid ReactElement.'
  );

  var transaction;
  try {
    var id = ReactInstanceHandles.createReactRootID();
    transaction = ReactServerRenderingTransaction.getPooled(false);

    return transaction.perform(function() {
      var componentInstance = instantiateReactComponent(element, null);
      var markup =
        componentInstance.mountComponent(id, transaction, emptyObject);
      return ReactMarkupChecksum.addChecksumToMarkup(markup);
    }, null);
  } finally {
    ReactServerRenderingTransaction.release(transaction);
  }
}

/**
 * @param {ReactElement} element
 * @return {string} the HTML markup, without the extra React ID and checksum
 * (for generating static pages)
 */
function renderToStaticMarkup(element) {
  invariant(
    ReactElement.isValidElement(element),
    'renderToStaticMarkup(): You must pass a valid ReactElement.'
  );

  var transaction;
  try {
    var id = ReactInstanceHandles.createReactRootID();
    transaction = ReactServerRenderingTransaction.getPooled(true);

    return transaction.perform(function() {
      var componentInstance = instantiateReactComponent(element, null);
      return componentInstance.mountComponent(id, transaction, emptyObject);
    }, null);
  } finally {
    ReactServerRenderingTransaction.release(transaction);
  }
}

module.exports = {
  renderToString: renderToString,
  renderToStaticMarkup: renderToStaticMarkup,
};


text:
package org.apache.directory.server.integ;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import netscape.ldap.LDAPConnection;

import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.util.JndiUtils;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.server.constants.ServerDNConstants;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.apache.directory.server.ldap.LdapServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerIntegrationUtils extends IntegrationUtils
{
    /** The class logger */
    private static final Logger LOG = LoggerFactory.getLogger( ServerIntegrationUtils.class );
    private static final String CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";

    private static final String DEFAULT_HOST = "localhost";
    private static final int DEFAULT_PORT = 10389;
    private static final String DEFAULT_ADMIN = ServerDNConstants.ADMIN_SYSTEM_DN;
    private static final String DEFAULT_PASSWORD = "secret";

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContext( LdapServer ldapServer ) throws Exception
    {
        return getWiredContext( ldapServer, null );
    }

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContext( LdapServer ldapServer, String principalDn, String password )
        throws Exception
    {
        LOG.debug( "Creating a wired context to local LDAP server on port {}", ldapServer.getPort() );
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, principalDn );
        env.put( Context.SECURITY_CREDENTIALS, password );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );

        return new InitialLdapContext( env, null );
    }

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContext( LdapServer ldapServer, Control[] controls ) throws Exception
    {
        LOG.debug( "Creating a wired context to local LDAP server on port {}", ldapServer.getPort() );
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        return new InitialLdapContext( env, JndiUtils.toJndiControls(
            ldapServer.getDirectoryService().getLdapCodecService(), controls ) );
    }

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContextThrowOnRefferal( LdapServer ldapServer ) throws Exception
    {
        LOG.debug( "Creating a wired context to local LDAP server on port {}", ldapServer.getPort() );
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        env.put( Context.REFERRAL, "throw" );
        return new InitialLdapContext( env, null );
    }

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContextRefferalIgnore( LdapServer ldapServer ) throws Exception
    {
        LOG.debug( "Creating a wired context to local LDAP server on port {}", ldapServer.getPort() );
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        env.put( Context.REFERRAL, "ignore" );
        return new InitialLdapContext( env, null );
    }

    /**
     * Creates a JNDI LdapContext with a connection over the wire using the
     * SUN LDAP provider.  The connection is made using the administrative
     * user as the principalDN.  The context is to the rootDSE.
     *
     * @param ldapServer the LDAP server to get the connection to
     * @return an LdapContext as the administrative user to the RootDSE
     * @throws Exception if there are problems creating the context
     */
    public static LdapContext getWiredContextFollowOnRefferal( LdapServer ldapServer ) throws Exception
    {
        LOG.debug( "Creating a wired context to local LDAP server on port {}", ldapServer.getPort() );
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        env.put( Context.REFERRAL, "follow" );
        return new InitialLdapContext( env, null );
    }

    public static LdapConnection getWiredConnection( LdapServer ldapServer ) throws Exception
    {
        String testServer = System.getProperty( "ldap.test.server", null );

        if ( testServer == null )
        {
            return getWiredConnection( ldapServer, ServerDNConstants.ADMIN_SYSTEM_DN, "secret" );
        }

        LOG.debug( "ldap.test.server = " + testServer );

        String admin = System.getProperty( testServer + ".admin", DEFAULT_ADMIN );
        LOG.debug( testServer + ".admin = " + admin );

        String password = System.getProperty( testServer + ".password", DEFAULT_PASSWORD );
        LOG.debug( testServer + ".password = " + password );

        String host = System.getProperty( testServer + ".host", DEFAULT_HOST );
        LOG.debug( testServer + ".host = " + host );

        int port = Integer.parseInt( System.getProperty( testServer + ".port", Integer.toString( DEFAULT_PORT ) ) );
        LOG.debug( testServer + ".port = " + port );

        LdapConnection conn = new LdapNetworkConnection( host, port );
        conn.bind( admin, password );

        return conn;
    }

    public static LDAPConnection getNsdkWiredConnection( LdapServer ldapServer ) throws Exception
    {
        String testServer = System.getProperty( "ldap.test.server", null );

        if ( testServer == null )
        {
            return getNsdkWiredConnection( ldapServer, ServerDNConstants.ADMIN_SYSTEM_DN, "secret" );
        }

        LOG.debug( "ldap.test.server = " + testServer );

        String admin = System.getProperty( testServer + ".admin", DEFAULT_ADMIN );
        LOG.debug( testServer + ".admin = " + admin );

        String password = System.getProperty( testServer + ".password", DEFAULT_PASSWORD );
        LOG.debug( testServer + ".password = " + password );

        String host = System.getProperty( testServer + ".host", DEFAULT_HOST );
        LOG.debug( testServer + ".host = " + host );

        int port = Integer.parseInt( System.getProperty( testServer + ".port", Integer.toString( DEFAULT_PORT ) ) );
        LOG.debug( testServer + ".port = " + port );

        LDAPConnection conn = new LDAPConnection();
        conn.connect( 3, host, port, admin, password );

        return conn;
    }

    /**
     * Gets a LDAP connection instance on a server, authenticating a user.
     *
     * @param ldapServer The server we want to connect to
     * @param principalDn The user's DN
     * @param password The user's password
     * @return A LdapConnection instance if we got one
     * @throws Exception If the connection cannot be created
     */
    public static LdapConnection getWiredConnection( LdapServer ldapServer, String principalDn, String password )
        throws Exception
    {
        LdapConnection connection = new LdapNetworkConnection( "localhost", ldapServer.getPort() );
        connection.bind( principalDn, password );

        return connection;
    }

    /**
     * Gets a LDAP connection instance on a server. We won't bind on the server.
     *
     * @param ldapServer The server we want to connect to
     * @return A LdapConnection instance if we got one
     * @throws Exception If the connection cannot be created
     */
    public static LdapConnection getLdapConnection( LdapServer ldapServer ) throws Exception
    {
        LdapConnection connection = new LdapNetworkConnection( "localhost", ldapServer.getPort() );

        return connection;
    }

    /**
     * Gets a LDAP connection instance on a server, authenticating a user.
     *
     * @param ldapServer The server we want to connect to
     * @param principalDn The user's DN
     * @param password The user's password
     * @return A LdapConnection instance if we got one
     * @throws Exception If the connection cannot be created
     */
    public static LDAPConnection getNsdkWiredConnection( LdapServer ldapServer, String principalDn, String password )
        throws Exception
    {
        LDAPConnection connection = new LDAPConnection();
        connection.connect( 3, "localhost", ldapServer.getPort(), principalDn, password );

        return connection;
    }

    /**
     * Gets a LDAP connection instance on a server. We will bind as Admin
     *
     * @param ldapServer The server we want to connect to
     * @return A LdapConnection instance if we got one
     * @throws Exception If the connection cannot be created
     */
    public static LdapConnection getAdminConnection( LdapServer ldapServer ) throws Exception
    {
        LdapConnection connection = new LdapNetworkConnection( "localhost", ldapServer.getPort() );
        connection.bind( ServerDNConstants.ADMIN_SYSTEM_DN, "secret" );

        return connection;
    }
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution.build;

import com.intellij.execution.Executor;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.ParametersList;
import com.intellij.execution.configurations.RunConfigurationModule;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactProperties;
import com.intellij.packaging.artifacts.ArtifactPropertiesProvider;
import com.intellij.task.*;
import com.intellij.task.impl.JpsProjectTaskRunner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenRunConfigurationType;
import org.jetbrains.idea.maven.execution.MavenRunner;
import org.jetbrains.idea.maven.execution.MavenRunnerParameters;
import org.jetbrains.idea.maven.model.MavenExplicitProfiles;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;

import java.util.*;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static org.jetbrains.idea.maven.utils.MavenUtil.isMavenModule;

/**
 * @author ibessonov
 */
public class MavenProjectTaskRunner extends ProjectTaskRunner {

  @Override
  public void run(@NotNull Project project,
                  @NotNull ProjectTaskContext context,
                  @Nullable ProjectTaskNotification callback,
                  @NotNull Collection<? extends ProjectTask> tasks) {
    Map<Class<? extends ProjectTask>, List<ProjectTask>> taskMap = JpsProjectTaskRunner.groupBy(tasks);

    buildModuleFiles(project, context, callback, getFromGroupedMap(taskMap, ModuleFilesBuildTask.class, emptyList()));
    buildModules(project, context, callback, getFromGroupedMap(taskMap, ModuleResourcesBuildTask.class, emptyList()));
    buildModules(project, context, callback, getFromGroupedMap(taskMap, ModuleBuildTask.class, emptyList()));

    buildArtifacts(project, context, callback, getFromGroupedMap(taskMap, ProjectModelBuildTask.class, emptyList()));
  }

  @Override
  public boolean canRun(@NotNull ProjectTask projectTask) {
    throw new UnsupportedOperationException("MavenProjectTaskRunner#canRun(ProjectTask)");
  }

  @Override
  public boolean canRun(@NotNull Project project, @NotNull ProjectTask projectTask) {
    if (!MavenRunner.getInstance(project).getSettings().isDelegateBuildToMaven()) {
      return false;
    }

    if (projectTask instanceof ModuleBuildTask) {
      Module module = ((ModuleBuildTask)projectTask).getModule();
      return isMavenModule(module);
    }

    if (projectTask instanceof ProjectModelBuildTask) {
      ProjectModelBuildTask buildTask = (ProjectModelBuildTask)projectTask;
      if (buildTask.getBuildableElement() instanceof Artifact) {
        Artifact artifact = (Artifact)buildTask.getBuildableElement();
        MavenArtifactProperties properties = null;
        for (ArtifactPropertiesProvider provider : artifact.getPropertiesProviders()) {
          if (provider instanceof MavenArtifactPropertiesProvider) {
            ArtifactProperties<?> artifactProperties = artifact.getProperties(provider);
            if (artifactProperties instanceof MavenArtifactProperties) {
              properties = (MavenArtifactProperties)artifactProperties;
              break;
            }
          }
        }
        if (properties == null || properties.getModuleName() == null) {
          return false;
        }

        Module module = ModuleManager.getInstance(project).findModuleByName(properties.getModuleName());
        if (!isMavenModule(module)) {
          return false;
        }

        for (MavenArtifactBuilder artifactBuilder : MavenArtifactBuilder.EP_NAME.getExtensions()) {
          if (artifactBuilder.isApplicable(buildTask)) {
            return true;
          }
        }
      }
    }

    if (projectTask instanceof ExecuteRunConfigurationTask) {
      ExecuteRunConfigurationTask task = (ExecuteRunConfigurationTask)projectTask;
      RunProfile runProfile = task.getRunProfile();
      if (runProfile instanceof ModuleBasedConfiguration) {
        RunConfigurationModule module = ((ModuleBasedConfiguration)runProfile).getConfigurationModule();
        if (!isMavenModule(module.getModule())) {
          return false;
        }
        for (MavenExecutionEnvironmentProvider environmentProvider : MavenExecutionEnvironmentProvider.EP_NAME.getExtensions()) {
          if (environmentProvider.isApplicable(task)) {
            return true;
          }
        }
      }
    }

    return false;
  }

  @Nullable
  @Override
  public ExecutionEnvironment createExecutionEnvironment(@NotNull Project project,
                                                         @NotNull ExecuteRunConfigurationTask task,
                                                         @Nullable Executor executor) {
    for (MavenExecutionEnvironmentProvider environmentProvider : MavenExecutionEnvironmentProvider.EP_NAME.getExtensions()) {
      if (environmentProvider.isApplicable(task)) {
        return environmentProvider.createExecutionEnvironment(project, task, executor);
      }
    }
    return null;
  }

  private static <T extends ProjectTask> List<? extends T>
  getFromGroupedMap(Map<Class<? extends ProjectTask>, List<ProjectTask>> map, Class<T> key, List<? extends T> defaultValue) {
    List<?> result = map.get(key);
    if (result == null) return defaultValue;
    //noinspection unchecked
    return (List<? extends T>)result;
  }

  private static void buildModules(@NotNull Project project,
                                   @NotNull ProjectTaskContext context,
                                   @Nullable ProjectTaskNotification callback,
                                   @NotNull Collection<? extends ModuleBuildTask> moduleBuildTasks) {
    if (moduleBuildTasks.isEmpty()) return;

    MavenRunner mavenRunner = MavenRunner.getInstance(project);
    MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);

    MavenExplicitProfiles explicitProfiles = mavenProjectsManager.getExplicitProfiles();
    Map<MavenProject, List<MavenProject>> rootProjectsToModules = new HashMap<>();

    boolean buildOnlyResources = false;
    for (ModuleBuildTask moduleBuildTask : moduleBuildTasks) {
      MavenProject mavenProject = mavenProjectsManager.findProject(moduleBuildTask.getModule());
      if (mavenProject == null) continue;

      buildOnlyResources = buildOnlyResources || moduleBuildTask instanceof ModuleResourcesBuildTask;
      MavenProject rootProject = mavenProjectsManager.findRootProject(mavenProject);
      rootProjectsToModules.computeIfAbsent(rootProject, p -> new ArrayList<>()).add(mavenProject);
    }

    boolean clean = moduleBuildTasks.stream().anyMatch(task -> !(task instanceof ModuleFilesBuildTask) && !task.isIncrementalBuild());
    boolean compileOnly = moduleBuildTasks.stream().allMatch(task -> task instanceof ModuleFilesBuildTask);
    boolean includeDependentModules = moduleBuildTasks.stream().anyMatch(ModuleBuildTask::isIncludeDependentModules);
    String goal = getGoal(buildOnlyResources, compileOnly);
    List<MavenRunnerParameters> commands = new ArrayList<>();
    for (Map.Entry<MavenProject, List<MavenProject>> entry : rootProjectsToModules.entrySet()) {
      ParametersList parameters = new ParametersList();
      if (clean) {
        parameters.add("clean");
      }
      parameters.add(goal);

      List<MavenProject> mavenProjects = entry.getValue();
      if (!includeDependentModules) {
        if (mavenProjects.size() > 1) {
          parameters.add("--projects");
          parameters.add(mavenProjects.stream()
                           .map(MavenProject::getMavenId)
                           .map(mavenId -> mavenId.getGroupId() + ":" + mavenId.getArtifactId())
                           .collect(joining(",")));
        }
        else {
          parameters.add("--non-recursive");
        }
      }

      VirtualFile pomFile = (mavenProjects.size() > 1 ? entry.getKey() : mavenProjects.get(0)).getFile();
      commands.add(new MavenRunnerParameters(true,
                                             pomFile.getParent().getPath(),
                                             pomFile.getName(),
                                             parameters.getList(),
                                             explicitProfiles.getEnabledProfiles(),
                                             explicitProfiles.getDisabledProfiles()));
    }

    runBatch(project, mavenRunner, "Maven Build", commands, context, callback);
  }

  @NotNull
  private static String getGoal(boolean buildOnlyResources, boolean compileOnly) {
    if (buildOnlyResources) {
      return "resources:resources";
    }
    return compileOnly ? "compile" : "install";
  }

  public static void runBatch(@NotNull Project project,
                              @NotNull MavenRunner mavenRunner,
                              @NotNull String title,
                              @NotNull List<MavenRunnerParameters> commands,
                              @NotNull ProjectTaskContext context,
                              @Nullable ProjectTaskNotification callback) {

    ApplicationManager.getApplication().invokeAndWait(() -> {

      FileDocumentManager.getInstance().saveAllDocuments();
      for (MavenRunnerParameters command : commands) {
        MavenRunConfigurationType.runConfiguration(project, command, null, null, descriptor -> {
          if(callback == null){
            return;
          }
          ProcessHandler handler = descriptor.getProcessHandler();
          if (handler != null) {
            handler.addProcessListener(new ProcessAdapter() {
              @Override
              public void processTerminated(@NotNull ProcessEvent event) {
                if (event.getExitCode() == 0) {
                  callback.finished(new ProjectTaskResult(false, 0, 0));
                }
                else {
                  callback.finished(new ProjectTaskResult(true, 0, 0));
                }
              }
            });
          }
        }, true);
      }
    });
  }

  private static void buildModuleFiles(@NotNull Project project,
                                       @NotNull ProjectTaskContext context,
                                       @Nullable ProjectTaskNotification callback,
                                       @NotNull Collection<? extends ModuleFilesBuildTask> moduleFilesBuildTasks) {
    buildModules(project, context, callback, moduleFilesBuildTasks);
  }

  private static void buildArtifacts(@NotNull Project project,
                                     @NotNull ProjectTaskContext context,
                                     @Nullable ProjectTaskNotification callback,
                                     List<? extends ProjectModelBuildTask> tasks) {
    for (ProjectModelBuildTask buildTask : tasks) {
      if (buildTask.getBuildableElement() instanceof Artifact) {
        for (MavenArtifactBuilder artifactBuilder : MavenArtifactBuilder.EP_NAME.getExtensions()) {
          if (artifactBuilder.isApplicable(buildTask)) {
            artifactBuilder.build(project, buildTask, context, callback);
          }
        }
      }
    }
  }
}


text:
package org.jetbrains.plugins.scala.lang.completion.postfix.templates

import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.lang.completion.postfix.templates.selector.AncestorSelector._

final class ScalaPrintlnPostfixTemplate(alias: String = "sout") extends ScalaStringBasedPostfixTemplate(
  alias,
  "println(expr)",
  SelectTopmostAncestors(AnyExpression)
) {
  override def getTemplateString(element: PsiElement): String = "println($expr$)"
}


text:
package com.thundersquadron.thundercab.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.google.android.gms.location.places.AutocompletePrediction;

public class PlacesSearchSuggestion implements SearchSuggestion {
    private String prediction;

    public PlacesSearchSuggestion(AutocompletePrediction pred) {
        prediction = pred.getFullText(null).toString();
    }

    public PlacesSearchSuggestion(Parcel in) {
        prediction = in.readString();
    }

    @Override
    public String getBody() {
        return prediction;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(prediction);
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public PlacesSearchSuggestion createFromParcel(Parcel in) {
            return new PlacesSearchSuggestion(in);
        }

        public PlacesSearchSuggestion[] newArray(int size) {
            return new PlacesSearchSuggestion[size];
        }
    };
}


text:
package test.portable;

import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import java.io.IOException;

public class Pet
        extends Animal {
    protected String name;
    protected int age;

    public Pet() {}

    public Pet(String species, String name, int age) {
        super(species);
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void readExternal(PofReader in) throws IOException {
        super.readExternal(in.createNestedPofReader(0));
        name = in.readString(1);
        age = in.readInt(2);
    }

    public void writeExternal(PofWriter out) throws IOException {
        super.writeExternal(out.createNestedPofWriter(0));
        out.writeString(1, name);
        out.writeInt(2, age);
    }

    @Override
    public boolean matches(Object o) {
        if (o instanceof Pet) {
            Pet pet = (Pet) o;
            return super.matches(pet) && age == pet.age && name.equals(pet.name);
        }
        return false;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", species=" + species +
                '}';
    }
}


text:
<?php

// ----------------------------------------------------------------------
// Original Author of file:
// Purpose of file:
// ----------------------------------------------------------------------

define('GLPI_ROOT', '..');
include (GLPI_ROOT . "/inc/includes.php");

$dropdown = new TicketSolutionType();
include (GLPI_ROOT . "/ajax/dropdown.common.tabs.php");

?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;

namespace Microsoft.Research.CodeAnalysis
{
  public class SimpleSatisfyProcedure<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>
  {
    private readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder;

    public BoxedExpression True
    {
      get
      {
        Contract.Ensures(Contract.Result<BoxedExpression>() != null);

        return BoxedExpression.ConstBool(true, this.MetaDataDecoder);
      }
    }

    public BoxedExpression False
    {
      get
      {
        Contract.Ensures(Contract.Result<BoxedExpression>() != null);

        return BoxedExpression.ConstBool(false, this.MetaDataDecoder);
      }
    }

    public SimpleSatisfyProcedure(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
    {
      Contract.Requires(mdDecoder != null);

      this.MetaDataDecoder = mdDecoder;
    }

    public bool TryMostGeneralSatisfaction(BoxedExpression input, BoxedExpression var, out BoxedExpression result)
    {
      BinaryOperator bop;
      BoxedExpression left, right;
      if (input.IsBinaryExpression(out bop, out left, out right) && bop.IsComparisonBinaryOperator())
      {
        var leftVars = left.Variables();
        var rightVars = right.Variables();

        var vIsLeft = (leftVars.Count == 1 && rightVars.Count == 0);
        var vIsRight = (leftVars.Count == 0 && rightVars.Count == 1);
        if (vIsLeft || vIsRight)
        {
          // do the swap
          if (vIsLeft && bop.TryInvert(out bop))
          {
            var tmp = right;
            right = left;
            left = tmp;
          }

          // Invariant:
          //    + left has no variables
          //    + right has exactly one variable

          // Build a new expression
          var newLeft = left.Sub(ConstantsInBoxedExpression.ConstantsIfLinearExpression(right)).EvaluateConstants(this.MetaDataDecoder);
          if (newLeft != null)
          {
            var newRight = rightVars.PickAnElement();
          }

          switch (bop)
          {
            case BinaryOperator.Ceq:
            case BinaryOperator.Cge:
            case BinaryOperator.Cge_Un:
            case BinaryOperator.Cle:
            case BinaryOperator.Cle_Un:
              {
                result = newLeft.EvaluateConstants(this.MetaDataDecoder);
                return true;
              }

            case BinaryOperator.Cgt:
            case BinaryOperator.Cgt_Un:
              {
                // k > x ==> x == k -1
                result = MinusOne(newLeft);
                return true;
              }

            case BinaryOperator.Clt:
            case BinaryOperator.Clt_Un:
              { // k < x ==> x == k+1
                result = PlusOne(newLeft);
                return true;
              }
          }
        }
        if (leftVars.Count == 1 && rightVars.Count == 1)
        {
          left = leftVars.PickAnElement();
          right = rightVars.PickAnElement();

          if (left.Equals(var) && bop.TryInvert(out bop))
          {
            left = right;
            right = var;
          }

          // invariant the invariant is on the right
          if (right.Equals(var))
          {
            // TODO: merge with the switch above
            switch (bop)
            {
              case BinaryOperator.Ceq:
              case BinaryOperator.Cge:
              case BinaryOperator.Cge_Un:
              case BinaryOperator.Cle:
              case BinaryOperator.Cle_Un:
                {
                  result = left;
                  return true;
                }

              case BinaryOperator.Cgt:
              case BinaryOperator.Cgt_Un:
                {
                  // k > x ==> x == k -1
                  result = MinusOne(left);
                  return true;
                }

              case BinaryOperator.Clt:
              case BinaryOperator.Clt_Un:
                { // k < x ==> x == k+1
                  result = PlusOne(right);
                  return true;
                }
            }
          }
        }
      }

      result = null;
      return false;
    }

    public BoxedExpression ApplySimpleArithmeticRules(BoxedExpression exp)
    {
      Contract.Requires(exp != null);
      Contract.Ensures(Contract.Result<BoxedExpression>() != null);

      BinaryOperator bop;
      BoxedExpression left, right;
      if (exp.IsBinaryExpression(out bop, out left, out right))
      {
        BinaryOperator bopRight;
        BoxedExpression right1, right2;
        if (right.IsBinaryExpression(out bopRight, out right1, out right2))
        {
          // (a  bop  k * a) or (a bop a * k) ==> (0 bop (k-1) * a)
          if (bopRight == BinaryOperator.Mul)
          {
            int k;
            BoxedExpression other;
            if (right1.IsConstantInt(out k))
            {
              other = right2;
            }
            else if (right2.IsConstantInt(out k))
            {
              other = right1;
            }
            else
            {
              goto done;
            }

            right1 = right2 = null; // kill them, to avoid errors

            // other appears on the left and the right
            if (other.Equals(left))
            {
              var newRight = k - 1 != 1 ? BoxedExpression.Binary(BinaryOperator.Mul, BoxedExpression.Const(k - 1, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder), other) : other;

              return BoxedExpression.Binary(bop,
                BoxedExpression.Const(0, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder), newRight);
            }
          }
        }
        BinaryOperator bopLeft;
        BoxedExpression left1, left2;
        if (left.IsBinaryExpression(out bopLeft, out left1, out left2))
        {
          // (a / k bop  a)  ==> (0 bop (k-1) * a)
          if (bopLeft == BinaryOperator.Div)
          {
            int k;
            if (!left2.IsConstantInt(out k))
            {
              goto done;
            }

            if (left1.Equals(right))
            {
              var newRight = k - 1 != 1 ? BoxedExpression.Binary(BinaryOperator.Mul, BoxedExpression.Const(k - 1, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder), right) : right;

              return BoxedExpression.Binary(bop,
                BoxedExpression.Const(0, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder), newRight);
            }
          }
        }
      }

        // TODO: add new cases as needed

    done:
      ;
      return exp;

    }

    private BoxedExpression MinusOne(BoxedExpression exp)
    {
      Contract.Requires(exp != null);

      return BoxedExpression.Binary(BinaryOperator.Sub, exp, BoxedExpression.Const(1, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder)).EvaluateConstants(this.MetaDataDecoder);
    }

    private BoxedExpression PlusOne(BoxedExpression exp)
    {
      Contract.Requires(exp != null);

      return BoxedExpression.Binary(BinaryOperator.Add, exp, BoxedExpression.Const(1, this.MetaDataDecoder.System_Int32, this.MetaDataDecoder)).EvaluateConstants(this.MetaDataDecoder);
    }

#pragma warning disable 0693

    class ConstantsInBoxedExpression : IBoxedExpressionVisitor
    {

      public static Set<BoxedExpression> ConstantsIfLinearExpression(BoxedExpression exp)
      {
        Contract.Requires(exp != null);
        var visitor = new ConstantsInBoxedExpression();

        exp.Dispatch(visitor);

        Set<BoxedExpression> result;

        if (!visitor.TryGetConstants(out result))
        {
          result = null;
        }

        return result;
      }

      [ContractInvariantMethod]
      private void ObjectInvariant()
      {
        Contract.Invariant(this.Constants != null);
      }

      public bool TryGetConstants(out Set<BoxedExpression> constants)
      {
        constants = this.Constants;
        return !this.fail;
      }

      readonly private Set<BoxedExpression> Constants;
      private bool fail;
      private bool isPositive;

      public ConstantsInBoxedExpression()
      {
        this.Constants = new Set<BoxedExpression>();
        this.fail = false;
        this.isPositive = true;
      }

      #region IBoxedExpressionVisitor Members

      public void Variable(object var, PathElement[] path, BoxedExpression parent)
      {
      }

      public void Constant<Type>(Type type, object value, BoxedExpression parent)
      {
        if (this.isPositive)
        {
          this.Constants.Add(parent);
        }
        else
        {
          this.Constants.Add(BoxedExpression.Unary(UnaryOperator.Neg, parent));
        }
      }

      public void Binary(BinaryOperator binaryOperator, BoxedExpression left, BoxedExpression right, BoxedExpression parent)
      {
        switch (binaryOperator)
        {
          case BinaryOperator.Add:
            {
              left.Dispatch(this);
              right.Dispatch(this);
            }
            break;
          case BinaryOperator.Sub:
            {
              left.Dispatch(this);

              this.isPositive = !this.isPositive;
              right.Dispatch(this);
              this.isPositive = !this.isPositive;
            }
            break;

          default:
            {
              this.fail = true;
              return;
            }
        }
      }

      public void Unary(UnaryOperator unaryOperator, BoxedExpression argument, BoxedExpression parent)
      {
        argument.Dispatch(this);
      }

      public void SizeOf<Type>(Type type, int sizeAsConstant, BoxedExpression parent)
      {
      }

      public void IsInst<Type>(Type type, BoxedExpression argument, BoxedExpression parent)
      {
        argument.Dispatch(this);
      }

      public void ArrayIndex<Type>(Type type, BoxedExpression array, BoxedExpression index, BoxedExpression parent)
      {
        array.Dispatch(this);
        index.Dispatch(this);
      }

      public void Result<Type>(Type type, BoxedExpression parent)
      {
      }

      public void Old<Type>(Type type, BoxedExpression expression, BoxedExpression parent)
      {
        expression.Dispatch(this);
      }

      public void ValueAtReturn<Type>(Type type, BoxedExpression expression, BoxedExpression parent)
      {
        expression.Dispatch(this);
      }

      public void Assert(BoxedExpression condition, BoxedExpression parent)
      {
        condition.Dispatch(this);
      }

      public void Assume(BoxedExpression condition, BoxedExpression parent)
      {
        condition.Dispatch(this);
      }

      public void StatementSequence(IIndexable<BoxedExpression> statements, BoxedExpression parent)
      {
        foreach (var statement in statements.Enumerate())
        {
          statement.Dispatch(this);
        }
      }

      public void ForAll(BoxedExpression boundVariable, BoxedExpression lower, BoxedExpression upper, BoxedExpression body, BoxedExpression parent)
      {
        boundVariable.Dispatch(this);
        lower.Dispatch(this);
        upper.Dispatch(this);
        body.Dispatch(this);
      }

      #endregion
    }

#pragma warning restore 0693

  }
}


text:
Sample query modal

Return employee from database with name equal to test.

<?php
	print_pre( $employee );
?>


text:
package platform::Cygwin;

use strict;
use warnings;
use Carp;

use vars qw(@ISA);

require platform::mingw;
@ISA = qw(platform::mingw);

# Assume someone set @INC right before loading this module
use configdata;

sub sharedname {
    my $class = shift;
    my $lib = platform::mingw->sharedname(@_);
    $lib =~ s|^lib|cyg| if defined $lib;
    return $lib;
}

1;


text:
<?php

defined('_JEXEC') or die;

/**
 * Controller class to install the sample data for the Joomla Installer.
 *
 * @since  3.1
 */
class InstallationControllerInstallSample extends JControllerBase
{
	/**
	 * Execute the controller.
	 *
	 * @return  void
	 *
	 * @since   3.1
	 */
	public function execute()
	{
		// Get the application
		/* @var InstallationApplicationWeb $app */
		$app = $this->getApplication();

		// Check for request forgeries.
		JSession::checkToken() or $app->sendJsonResponse(new Exception(JText::_('JINVALID_TOKEN'), 403));

		// Get the setup model.
		$model = new InstallationModelSetup;

		// Get the options from the session
		$options = $model->getOptions();

		// Get the database model.
		$db = new InstallationModelDatabase;

		// Attempt to create the database tables.
		$return = $db->installSampleData($options);

		$r = new stdClass;
		$r->view = 'install';

		// Check if the database was initialised
		if (!$return)
		{
			$r->view = 'database';
		}

		$app->sendJsonResponse($r);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Hosting;
using OpenIddict.Server.FunctionalTests;

namespace OpenIddict.Server.AspNetCore.FunctionalTests
{
    /// <summary>
    /// Represents a test host used by the server integration tests.
    /// </summary>
    public class OpenIddictServerAspNetCoreIntegrationTestServer : OpenIddictServerIntegrationTestServer
    {
        public OpenIddictServerAspNetCoreIntegrationTestServer(TestServer server)
            => Server = server;

#if SUPPORTS_GENERIC_HOST
        public OpenIddictServerAspNetCoreIntegrationTestServer(IHost host)
        {
            Host = host;
            Server = host.GetTestServer();
        }
#endif

        /// <summary>
        /// Gets the ASP.NET Core test server used by this instance.
        /// </summary>
        public TestServer Server { get; }

#if SUPPORTS_GENERIC_HOST
        /// <summary>
        /// Gets the generic host used by this instance.
        /// </summary>
        public IHost Host { get; }
#endif

        [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
            Justification = "The caller is responsible of disposing the test client.")]
        public override ValueTask<OpenIddictServerIntegrationTestClient> CreateClientAsync()
            => new ValueTask<OpenIddictServerIntegrationTestClient>(
                new OpenIddictServerIntegrationTestClient(Server.CreateClient()));

        public override
#if SUPPORTS_GENERIC_HOST
            async
#endif
            ValueTask DisposeAsync()
        {
            // Dispose of the underlying test server.
            Server.Dispose();

#if SUPPORTS_GENERIC_HOST
            // Stop and dispose of the underlying generic host.
            await Host.StopAsync();
            Host.Dispose();
#else
            return default;
#endif
        }
    }
}