##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##

import sigrokdecode as srd
from common.plugtrx import (MODULE_ID, ALARM_THRESHOLDS, AD_READOUTS, GCS_BITS,
        CONNECTOR, TRANSCEIVER, SERIAL_ENCODING, XMIT_TECH, CDR, DEVICE_TECH,
        ENHANCED_OPTS, AUX_TYPES)

class Decoder(srd.Decoder):
    api_version = 3
    id = 'xfp'
    name = 'XFP'
    longname = '10 Gigabit Small Form Factor Pluggable Module (XFP)'
    desc = 'XFP I²C management interface structures/protocol'
    license = 'gplv3+'
    inputs = ['i2c']
    outputs = []
    tags = ['Networking']
    annotations = (
        ('fieldnames-and-values', 'XFP structure field names and values'),
        ('fields', 'XFP structure fields'),
    )

    def __init__(self):
        self.reset()

    def reset(self):
        # Received data items, used as an index into samplenum/data
        self.cnt = -1
        # Start/end sample numbers per data item
        self.sn = []
        # Multi-byte structure buffer
        self.buf = []
        # Filled in by address 0x7f in low memory
        self.cur_highmem_page = 0
        # Filled in by extended ID value in table 2
        self.have_clei = False
        # Handlers for each field in the structure, keyed by the end
        # index of that field. Each handler is fed all unhandled bytes
        # up until that point, so mark unused space with the dummy
        # handler self.ignore().
        self.MAP_LOWER_MEMORY = {
            0:  self.module_id,
            1:  self.signal_cc,
            57: self.alarm_warnings,
            59: self.vps,
            69: self.ignore,
            71: self.ber,
            75: self.wavelength_cr,
            79: self.fec_cr,
            95: self.int_ctrl,
            109: self.ad_readout,
            111: self.gcs,
            117: self.ignore,
            118: self.ignore,
            122: self.ignore,
            126: self.ignore,
            127: self.page_select,
        }
        self.MAP_HIGH_TABLE_1 = {
            128: self.module_id,
            129: self.ext_module_id,
            130: self.connector,
            138: self.transceiver,
            139: self.serial_encoding,
            140: self.br_min,
            141: self.br_max,
            142: self.link_length_smf,
            143: self.link_length_e50,
            144: self.link_length_50um,
            145: self.link_length_625um,
            146: self.link_length_copper,
            147: self.device_tech,
            163: self.vendor,
            164: self.cdr,
            167: self.vendor_oui,
            183: self.vendor_pn,
            185: self.vendor_rev,
            187: self.wavelength,
            189: self.wavelength_tolerance,
            190: self.max_case_temp,
            191: self.ignore,
            195: self.power_supply,
            211: self.vendor_sn,
            219: self.manuf_date,
            220: self.diag_mon,
            221: self.enhanced_opts,
            222: self.aux_mon,
            223: self.ignore,
            255: self.maybe_ascii,
        }

    def start(self):
        self.out_ann = self.register(srd.OUTPUT_ANN)

    def decode(self, ss, es, data):
        cmd, data = data

        # We only care about actual data bytes that are read (for now).
        if cmd != 'DATA READ':
            return

        self.cnt += 1
        self.sn.append([ss, es])

        self.buf.append(data)
        if self.cnt < 0x80:
            if self.cnt in self.MAP_LOWER_MEMORY:
                self.MAP_LOWER_MEMORY[self.cnt](self.buf)
                self.buf.clear()
        elif self.cnt < 0x0100 and self.cur_highmem_page == 0x01:
            # Serial ID memory map
            if self.cnt in self.MAP_HIGH_TABLE_1:
                self.MAP_HIGH_TABLE_1[self.cnt](self.buf)
                self.buf.clear()

    # Annotation helper
    def annotate(self, key, value, start_cnt=None, end_cnt=None):
        if start_cnt is None:
            start_cnt = self.cnt - len(self.buf) + 1
        if end_cnt is None:
            end_cnt = self.cnt
        self.put(self.sn[start_cnt][0], self.sn[end_cnt][1],
                self.out_ann, [0, [key + ": " + value]])
        self.put(self.sn[start_cnt][0], self.sn[end_cnt][1],
                 self.out_ann, [1, [value]])

    # Placeholder handler, needed to advance the buffer past unused or
    # reserved space in the structures.
    def ignore(self, data):
        pass

    # Show as ASCII if possible
    def maybe_ascii(self, data):
        for i in range(len(data)):
            if data[i] >= 0x20 and data[i] < 0x7f:
                cnt = self.cnt - len(data) + 1
                self.annotate("Vendor ID", chr(data[i]), cnt, cnt)

    # Convert 16-bit two's complement values, with each increment
    # representing 1/256C, to degrees Celsius.
    def to_temp(self, value):
        if value & 0x8000:
            value = -((value ^ 0xffff) + 1)
        temp = value / 256.0
        return "%.1f C" % temp

    # TX bias current in uA. Each increment represents 0.2uA
    def to_current(self, value):
        current = value / 500000.0
        return "%.1f mA" % current

    # Power in mW, with each increment representing 0.1uW
    def to_power(self, value):
        power = value / 10000.0
        return "%.2f mW" % power

    # Wavelength in increments of 0.05nm
    def to_wavelength(self, value):
        wl = value / 20
        return "%d nm" % wl

    # Wavelength in increments of 0.005nm
    def to_wavelength_tolerance(self, value):
        wl = value / 200.0
        return "%.1f nm" % wl

    def module_id(self, data):
        self.annotate("Module identifier", MODULE_ID.get(data[0], "Unknown"))

    def signal_cc(self, data):
        # No good data available.
        if (data[0] != 0x00):
            self.annotate("Signal Conditioner Control", "%.2x" % data[0])

    def alarm_warnings(self, data):
        cnt_idx = self.cnt - len(data)
        idx = 0
        while idx < 56:
            if idx == 8:
                # Skip over reserved A/D flag thresholds
                idx += 8
            value = (data[idx] << 8) | data[idx + 1]
            if value != 0:
                name = ALARM_THRESHOLDS.get(idx, "...")
                if idx in (0, 2, 4, 6):
                    self.annotate(name, self.to_temp(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                elif idx in (16, 18, 20, 22):
                    self.annotate(name, self.to_current(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                elif idx in (24, 26, 28, 30, 32, 34, 36, 38):
                    self.annotate(name, self.to_power(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                else:
                    self.annotate(name, "%d" % name, value, cnt_idx + idx,
                            cnt_idx + idx + 1)
            idx += 2

    def vps(self, data):
        # No good data available.
        if (data != [0, 0]):
            self.annotate("VPS", "%.2x%.2x" % (data[0], data[1]))

    def ber(self, data):
        # No good data available.
        if (data != [0, 0]):
            self.annotate("BER", str(data))

    def wavelength_cr(self, data):
        # No good data available.
        if (data != [0, 0, 0, 0]):
            self.annotate("WCR", str(data))

    def fec_cr(self, data):
        if (data != [0, 0, 0, 0]):
            self.annotate("FEC", str(data))

    def int_ctrl(self, data):
        # No good data available. Also boring.
        out = []
        for d in data:
            out.append("%.2x" % d)
        self.annotate("Interrupt bits", ' '.join(out))

    def ad_readout(self, data):
        cnt_idx = self.cnt - len(data) + 1
        idx = 0
        while idx < 14:
            if idx == 2:
                # Skip over reserved field
                idx += 2
            value = (data[idx] << 8) | data[idx + 1]
            name = AD_READOUTS.get(idx, "...")
            if value != 0:
                if idx == 0:
                    self.annotate(name, self.to_temp(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                elif idx == 4:
                    self.annotate(name, self.to_current(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                elif idx in (6, 8):
                    self.annotate(name, self.to_power(value),
                            cnt_idx + idx, cnt_idx + idx + 1)
                else:
                    self.annotate(name, str(value), cnt_idx + idx,
                            cnt_idx + idx + 1)
            idx += 2

    def gcs(self, data):
        allbits = (data[0] << 8) | data[1]
        out = []
        for b in range(13):
            if allbits & 0x8000:
                out.append(GCS_BITS[b])
            allbits <<= 1
        self.annotate("General Control/Status", ', '.join(out))

    def page_select(self, data):
        self.cur_highmem_page = data[0]

    def ext_module_id(self, data):
        out = ["Power level %d module" % ((data[0] >> 6) + 1)]
        if data[0] & 0x20 == 0:
            out.append("CDR")
        if data[0] & 0x10 == 0:
            out.append("TX ref clock input required")
        if data[0] & 0x08 == 0:
            self.have_clei = True
        self.annotate("Extended id", ', '.join(out))

    def connector(self, data):
        if data[0] in CONNECTOR:
            self.annotate("Connector", CONNECTOR[data[0]])

    def transceiver(self, data):
        out = []
        for t in range(8):
            if data[t] == 0:
                continue
            value = data[t]
            for b in range(8):
                if value & 0x80:
                    if len(TRANSCEIVER[t]) < b + 1:
                        out.append("(unknown)")
                    else:
                        out.append(TRANSCEIVER[t][b])
                value <<= 1
        self.annotate("Transceiver compliance", ', '.join(out))

    def serial_encoding(self, data):
        out = []
        value = data[0]
        for b in range(8):
            if value & 0x80:
                if len(SERIAL_ENCODING) < b + 1:
                    out.append("(unknown)")
                else:
                    out.append(SERIAL_ENCODING[b])
                value <<= 1
        self.annotate("Serial encoding support", ', '.join(out))

    def br_min(self, data):
        # Increments represent 100Mb/s
        rate = data[0] / 10.0
        self.annotate("Minimum bit rate", "%.3f GB/s" % rate)

    def br_max(self, data):
        # Increments represent 100Mb/s
        rate = data[0] / 10.0
        self.annotate("Maximum bit rate", "%.3f GB/s" % rate)

    def link_length_smf(self, data):
        if data[0] == 0:
            length = "(standard)"
        elif data[0] == 255:
            length = "> 254 km"
        else:
            length = "%d km" % data[0]
        self.annotate("Link length (SMF)", length)

    def link_length_e50(self, data):
        if data[0] == 0:
            length = "(standard)"
        elif data[0] == 255:
            length = "> 508 m"
        else:
            length = "%d m" % (data[0] * 2)
        self.annotate("Link length (extended, 50μm MMF)", length)

    def link_length_50um(self, data):
        if data[0] == 0:
            length = "(standard)"
        elif data[0] == 255:
            length = "> 254 m"
        else:
            length = "%d m" % data[0]
        self.annotate("Link length (50μm MMF)", length)

    def link_length_625um(self, data):
        if data[0] == 0:
            length = "(standard)"
        elif data[0] == 255:
            length = "> 254 m"
        else:
            length = "%d m" % (data[0])
        self.annotate("Link length (62.5μm MMF)", length)

    def link_length_copper(self, data):
        if data[0] == 0:
            length = "(unknown)"
        elif data[0] == 255:
            length = "> 254 m"
        else:
            length = "%d m" % (data[0] * 2)
        self.annotate("Link length (copper)", length)

    def device_tech(self, data):
        out = []
        xmit = data[0] >> 4
        if xmit <= len(XMIT_TECH) - 1:
            out.append("%s transmitter" % XMIT_TECH[xmit])
        dev = data[0] & 0x0f
        for b in range(4):
            out.append(DEVICE_TECH[b][(dev >> (3 - b)) & 0x01])
        self.annotate("Device technology", ', '.join(out))

    def vendor(self, data):
        name = bytes(data).strip().decode('ascii').strip('\x00')
        if name:
            self.annotate("Vendor", name)

    def cdr(self, data):
        out = []
        value = data[0]
        for b in range(8):
            if value & 0x80:
                out.append(CDR[b])
            value <<= 1
        self.annotate("CDR support", ', '.join(out))

    def vendor_oui(self, data):
        if data != [0, 0, 0]:
            self.annotate("Vendor OUI", "%.2X-%.2X-%.2X" % tuple(data))

    def vendor_pn(self, data):
        name = bytes(data).strip().decode('ascii').strip('\x00')
        if name:
            self.annotate("Vendor part number", name)

    def vendor_rev(self, data):
        name = bytes(data).strip().decode('ascii').strip('\x00')
        if name:
            self.annotate("Vendor revision", name)

    def wavelength(self, data):
        value = (data[0] << 8) | data[1]
        self.annotate("Wavelength", self.to_wavelength(value))

    def wavelength_tolerance(self, data):
        value = (data[0] << 8) | data[1]
        self.annotate("Wavelength tolerance", self.to_wavelength_tolerance(value))

    def max_case_temp(self, data):
        self.annotate("Maximum case temperature", "%d C" % data[0])

    def power_supply(self, data):
        out = []
        self.annotate("Max power dissipation",
                "%.3f W" % (data[0] * 0.02), self.cnt - 3, self.cnt - 3)
        self.annotate("Max power dissipation (powered down)",
                "%.3f W" % (data[1] * 0.01), self.cnt - 2, self.cnt - 2)
        value = (data[2] >> 4) * 0.050
        self.annotate("Max current required (5V supply)",
                "%.3f A" % value, self.cnt - 1, self.cnt - 1)
        value = (data[2] & 0x0f) * 0.100
        self.annotate("Max current required (3.3V supply)",
                "%.3f A" % value, self.cnt - 1, self.cnt - 1)
        value = (data[3] >> 4) * 0.100
        self.annotate("Max current required (1.8V supply)",
                "%.3f A" % value, self.cnt, self.cnt)
        value = (data[3] & 0x0f) * 0.050
        self.annotate("Max current required (-5.2V supply)",
                "%.3f A" % value, self.cnt, self.cnt)

    def vendor_sn(self, data):
        name = bytes(data).strip().decode('ascii').strip('\x00')
        if name:
            self.annotate("Vendor serial number", name)

    def manuf_date(self, data):
        y = int(bytes(data[0:2])) + 2000
        m = int(bytes(data[2:4]))
        d = int(bytes(data[4:6]))
        mnf = "%.4d-%.2d-%.2d" % (y, m, d)
        lot = bytes(data[6:]).strip().decode('ascii').strip('\x00')
        if lot:
            mnf += " lot " + lot
        self.annotate("Manufacturing date", mnf)

    def diag_mon(self, data):
        out = []
        if data[0] & 0x10:
            out.append("BER support")
        else:
            out.append("no BER support")
        if data[0] & 0x08:
            out.append("average power measurement")
        else:
            out.append("OMA power measurement")
        self.annotate("Diagnostic monitoring", ', '.join(out))

    def enhanced_opts(self, data):
        out = []
        value = data[0]
        for b in range(8):
            if value & 0x80:
                out.append(ENHANCED_OPTS[b])
            value <<= 1
        self.annotate("Enhanced option support", ', '.join(out))

    def aux_mon(self, data):
        aux = AUX_TYPES[data[0] >> 4]
        self.annotate("AUX1 monitoring", aux)
        aux = AUX_TYPES[data[0] & 0x0f]
        self.annotate("AUX2 monitoring", aux)

{'repo_name': 'DreamSourceLab/DSView', 'stars': '498', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': 1347748837759515899, 'source_dataset': 'data'}


// A table of symbols, where each symbol can be a variable, procedure, or
// function. A table is for a lexical scope only, but has a link to the
// lexical scope it's nested in.

'use strict';

define(["PascalError", "Symbol", "Node", "Token", "modules",
       "inst", "Native", "NativeProcedure", "SymbolLookup", "underscore"],
       function (PascalError, Symbol, Node, Token, modules,
                 inst, Native, NativeProcedure, SymbolLookup, _) {

    // The parent symbol table must be lexical, not dynamic.
    var SymbolTable = function (parentSymbolTable) {
        // Map from symbol name (all lowercase, since Pascal is case-insensitive) to
        // a Symbol object. This stores variables, constants, procedure, and functions.
        // Basically any symbol that can be references in an expression.
        this.symbols = {};

        // Map from type name (all lowercase, since Pascal is case-insensitive) to
        // a Symbol object. This stores user-defined types.
        this.types = {};

        // Parent of this table. Symbols not found in this table are looked up in the
        // parent one if it's not null.
        this.parentSymbolTable = parentSymbolTable;

        // Registry of native functions. We only have one of these, so if we have a parent,
        // use its object.
        this.native = parentSymbolTable ? parentSymbolTable.native : new Native();

        // Size (in words) of all variables in this frame.
        this.totalVariableSize = 0;

        // Size (in words) of all parameters in this frame.
        this.totalParameterSize = 0;

        // Size (in words) of all typed constants in this frame.
        this.totalTypedConstantsSize = 0;
    };

    // Adds a symbol to the table. Returns the Symbol object.
    SymbolTable.prototype.addSymbol = function (name, nodeType, type, byReference) {
        var address = -1; // Indicates error.

        // Default to false.
        byReference = byReference || false;

        if (nodeType === Node.VAR) {
            // For this to work, all parameters must be added to the symbol table
            // before any variable is added.
            address = inst.MARK_SIZE + this.totalParameterSize + this.totalVariableSize;
            this.totalVariableSize += type.getTypeSize();
        } else if (nodeType === Node.CONST) {
            // Nothing. We may later treat constant arrays like read-only
            // variables, in the sense that they end up on the stack. I don't
            // know how we'd populate them. I think in the real p-machine they
            // end up above the heap and are loaded declaratively from the
            // bytecode object.
        } else if (nodeType === Node.TYPED_CONST) {
            // They end up being copied to the stack at the start of
            // a function call, like a regular variable.
            address = inst.MARK_SIZE + this.totalParameterSize + this.totalVariableSize;
            this.totalVariableSize += type.getTypeSize();
        } else if (nodeType === Node.PARAMETER) {
            address = inst.MARK_SIZE + this.totalParameterSize;
            this.totalParameterSize += byReference ? 1 : type.getTypeSize();
        }

        var symbol = new Symbol(name, type, address, byReference);
        this.symbols[name.toLowerCase()] = symbol;

        return symbol;
    };

    // Add a user-defined type, returning the Symbol object.
    SymbolTable.prototype.addType = function (name, type) {
        var symbol = new Symbol(name, type, 0, false);
        this.types[name.toLowerCase()] = symbol;

        return symbol;
    };

    // Returns the SymbolLookup object for the name. If the name is not found
    // in this table, the parent table is consulted if it's set. Throws if not
    // found. The nodeType is optional. If set, only nodes of that type will
    // be returned. The "level" parameter is for internal use and should be left out.
    SymbolTable.prototype.getSymbol = function (token, nodeType, level) {
        var name = token.value.toLowerCase();

        // Default to zero.
        level = level || 0;

        if (this.symbols.hasOwnProperty(name)) {
            var symbol = this.symbols[name];

            // Match optional nodeType.
            if (!nodeType || symbol.type.nodeType === nodeType) {
                return new SymbolLookup(symbol, level);
            }
        }

        if (this.parentSymbolTable !== null) {
            return this.parentSymbolTable.getSymbol(token, nodeType, level + 1);
        }

        throw new PascalError(token, "can't find symbol");
    };

    // Returns a SymbolLookup object for the type name. If the name is not
    // found in this table, the parent table is consulted if it's set. Throws
    // if not found. The "level" parameter is for internal use and should be left out.
    SymbolTable.prototype.getType = function (token, level) {
        var name = token.value.toLowerCase();

        // Default to zero.
        level = level || 0;

        if (this.types.hasOwnProperty(name)) {
            var symbol = this.types[name];
            return new SymbolLookup(symbol, level);
        }

        if (this.parentSymbolTable !== null) {
            return this.parentSymbolTable.getType(token, level + 1);
        }

        throw new PascalError(token, "unknown type");
    };

    // Add a native constant to the symbol table.
    SymbolTable.prototype.addNativeConstant = function (name, value, type) {
        var valueNode;
        switch (type.getSimpleTypeCode()) {
            case inst.A:
                valueNode = Node.makePointerNode(value);
                break;
            case inst.B:
                valueNode = Node.makeBooleanNode(value);
                break;
            default:
                valueNode = Node.makeNumberNode(value);
                break;
        }
        valueNode.expressionType = type;

        var symbol = this.addSymbol(name, Node.CONST, type);
        symbol.value = valueNode;
    };

    // Add a native function to the symbol table.
    SymbolTable.prototype.addNativeFunction = function (name, returnType, parameterTypes, fn) {
        // Add to table of builtins first (for CSP call).
        var nativeProcedure = new NativeProcedure(name, returnType, parameterTypes, fn);
        var index = this.native.add(nativeProcedure);

        // Function that takes a type and an index and returns a PARAMETER for it.
        var makeParameter = function (type, index) {
            var name = Node.makeIdentifierNode(String.fromCharCode(97 + index)); // "a", "b", ...
            return new Node(Node.PARAMETER, null, {
                name: name,
                type: type
            });
        };

        // Make function type.
        var type = new Node(Node.SUBPROGRAM_TYPE, null, {
            parameters: _.map(parameterTypes, makeParameter),
            returnType: returnType
        });

        // Add to this symbol table.
        var symbol = this.addSymbol(name, Node.SUBPROGRAM_TYPE, type);

        // Remember the native index.
        symbol.address = index;

        // Mark it as native.
        symbol.isNative = true;

        return symbol;
    };

    // Add a native type (such as "integer") to the symbol table.
    SymbolTable.prototype.addNativeType = function (name, type) {
        // Nothing special here, it's just like a user-defined type.
        this.addType(name, type);
    };

    // Create a default symbol table with all built-in symbols.
    SymbolTable.makeBuiltinSymbolTable = function () {
        var symbolTable = new SymbolTable(null);

        modules.importModule("__builtin__", symbolTable);

        return symbolTable;
    };

    return SymbolTable;
});

{'repo_name': 'lkesteloot/turbopascal', 'stars': '279', 'repo_language': 'JavaScript', 'file_name': 'require.js', 'mime_type': 'text/plain', 'hash': 5305670573904628361, 'source_dataset': 'data'}


Please enter valid database column names for each row (a-Z and underscore characters). Please fix the following rows:

Please enter a valid database table name (a-Z and underscores only).

Enclose table and field names with backquotes

Add default auto-increment primary key column

Number of rows to insert per query (1 - 300)

{'repo_name': 'benkeen/generatedata', 'stars': '1646', 'repo_language': 'TypeScript', 'file_name': 'build.js', 'mime_type': 'text/plain', 'hash': 7668983837534197866, 'source_dataset': 'data'}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">

	<title>Editor NormalizeIndentOutdent Test</title>

Editor + NormalizeIndentOutdent Plugin

This is an example editor with NormalizeIndentOutdent enabled.

	The NormalizeIndentOutdent plugin tries to improve the behavior of indent and outdent, and make it generate
	sane HTML output.  The default browser behaviors usually do not generate valid HTML when indenting and
	outdenting lists.  This tries to correct for that, as well as improve general handling of text indents.

		This instance is created from a div with an extra plugin, 'NormalizeIndentOutdent' loaded.

List Item One

List Item Two

List Item Three

List Item Four

		The Dojo Toolkit

One

Two

					Three

Malformed list #1

List Item One

List Item Two

List Item Three

List Item Four

List Item Five

Malformed list #2

List Item one

List Item two

List Item three

List Item four

List Item five

A bunch of Lorum Ipsum Text:

			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eget turpis nunc.
			Praesent ut metus ac mi gravida lobortis vel quis nulla. Sed elementum elit eget
			ante viverra consectetur. Praesent pulvinar faucibus risus in pulvinar. Sed auctor,
			dui sed suscipit semper, metus sapien feugiat urna, et auctor nisi est quis purus.
			Aliquam eu tortor eu ante venenatis pellentesque nec sed massa. Nulla feugiat, nunc
			ac aliquet elementum, lacus odio dictum nisl, vel molestie neque tellus eget nibh.
			Curabitur et eros quam, non consectetur erat. Class aptent taciti sociosqu ad litora
			torquent per conubia nostra, per inceptos himenaeos. Quisque luctus imperdiet felis,
			a mollis sapien scelerisque ut. Quisque dui neque, vulputate eu consectetur et, fermentum
			id est. Nulla euismod lorem at massa aliquam at cursus mi fermentum. Quisque rhoncus
			ornare pharetra. Cras vestibulum convallis nisl, eget ultrices sem porta eget. Duis
			in dolor id nibh volutpat sodales. Nullam eleifend, sapien accumsan convallis tincidunt,
			justo mi pellentesque dolor, in suscipit dolor quam ac ligula.

			Ut molestie facilisis nisi sed consequat. Nunc in turpis quam, vel elementum lectus.
			Suspendisse vel consequat augue. Praesent id orci orci. Praesent est tortor, consequat
			eu posuere nec, volutpat ac diam. Cras pretium quam non diam dictum tincidunt. Mauris
			aliquet lacinia odio vitae elementum. Nam rutrum semper metus, in consectetur lectus
			aliquam a. Maecenas pharetra nibh nec leo consequat vitae rhoncus nibh volutpat.
			Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
			mus. Sed at odio turpis, sit amet molestie nisl. Curabitur in ligula id tortor feugiat
			semper. Vestibulum id nunc magna, eu lacinia nibh. Ut congue adipiscing dictum.

			Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia
			nostra, per inceptos himenaeos. Phasellus in orci purus, sed aliquet quam. Aenean
			ultrices tincidunt augue, in feugiat massa dignissim in. Nunc a dolor eu mi fringilla
			laoreet. Praesent lacinia mi eu sapien imperdiet dignissim. Praesent a pellentesque
			est. Sed augue eros, porttitor nec consequat bibendum, mattis lobortis diam. Sed
			at massa ante. In volutpat ultrices mattis. Vestibulum tempus pretium risus quis
			aliquet. Donec non ante vitae orci euismod eleifend. Aliquam at metus quis turpis
			pharetra porta. Sed dignissim risus in erat aliquam et posuere nulla molestie. Nunc
			iaculis lectus eget augue sollicitudin gravida ac non nisl. Vivamus bibendum gravida
			vehicula. Aliquam vitae mi ligula. Nulla at augue velit, vitae ultricies libero.
			Proin at lorem turpis.

		Centered Text

{'repo_name': 'jrossi227/ApacheGUI', 'stars': '115', 'repo_language': 'HTML', 'file_name': 'context.xml', 'mime_type': 'text/xml', 'hash': 4797627293590365014, 'source_dataset': 'data'}


package org.csanchez.jenkins.plugins.kubernetes;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.slaves.Cloud;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;

public class NonConfigurableKubernetesCloud extends KubernetesCloud {
    public NonConfigurableKubernetesCloud(@NonNull String name, @NonNull KubernetesCloud source) {
        super(name, source);
    }

    @Extension
    public static class FilterImpl extends DescriptorVisibilityFilter {
        @Override
        public boolean filter(Object context, Descriptor descriptor) {
            return !(descriptor instanceof DescriptorImpl);
        }
    }

    @Extension
    public static class DescriptorImpl extends KubernetesCloud.DescriptorImpl {
        @Override
        public String getDisplayName() {
            return Messages.NonConfigurableKubernetesCloud_displayName();
        }

        @Override
        public boolean configure(StaplerRequest request, JSONObject object) throws Descriptor.FormException {
            return true;
        }

        @Override
        public Cloud newInstance(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
            if (req != null) {
                // We prevent the cloud reconfiguration from the web UI
                String cloudName = req.getParameter("cloudName");
                return Jenkins.getInstance().getCloud(cloudName);
            } else {
                throw new IllegalStateException("Expecting req to be non-null");
            }
        }
    }
}

{'repo_name': 'jenkinsci/kubernetes-plugin', 'stars': '1664', 'repo_language': 'Java', 'file_name': 'maven.config', 'mime_type': 'text/plain', 'hash': -4446348133999051994, 'source_dataset': 'data'}


/*
Copyright 2014 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bearertoken

import (
	"errors"
	"net/http"
	"strings"

	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/user"
)

type Authenticator struct {
	auth authenticator.Token
}

func New(auth authenticator.Token) *Authenticator {
	return &Authenticator{auth}
}

var invalidToken = errors.New("invalid bearer token")

func (a *Authenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
	auth := strings.TrimSpace(req.Header.Get("Authorization"))
	if auth == "" {
		return nil, false, nil
	}
	parts := strings.Split(auth, " ")
	if len(parts) < 2 || strings.ToLower(parts[0]) != "bearer" {
		return nil, false, nil
	}

	token := parts[1]

	// Empty bearer tokens aren't valid
	if len(token) == 0 {
		return nil, false, nil
	}

	user, ok, err := a.auth.AuthenticateToken(token)
	// if we authenticated successfully, go ahead and remove the bearer token so that no one
	// is ever tempted to use it inside of the API server
	if ok {
		req.Header.Del("Authorization")
	}

	// If the token authenticator didn't error, provide a default error
	if !ok && err == nil {
		err = invalidToken
	}

	return user, ok, err
}

{'repo_name': 'sapcc/kubernetes-operators', 'stars': '116', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -8434297640964459786, 'source_dataset': 'data'}


//
// detail/impl/reactive_serial_port_service.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP
#define ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "asio/detail/config.hpp"

#if defined(ASIO_HAS_SERIAL_PORT)
#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__)

#include <cstring>
#include "asio/detail/reactive_serial_port_service.hpp"

#include "asio/detail/push_options.hpp"

namespace asio {
namespace detail {

reactive_serial_port_service::reactive_serial_port_service(
    execution_context& context)
  : execution_context_service_base<reactive_serial_port_service>(context),
    descriptor_service_(context)
{
}

void reactive_serial_port_service::shutdown()
{
  descriptor_service_.shutdown();
}

asio::error_code reactive_serial_port_service::open(
    reactive_serial_port_service::implementation_type& impl,
    const std::string& device, asio::error_code& ec)
{
  if (is_open(impl))
  {
    ec = asio::error::already_open;
    return ec;
  }

  descriptor_ops::state_type state = 0;
  int fd = descriptor_ops::open(device.c_str(),
      O_RDWR | O_NONBLOCK | O_NOCTTY, ec);
  if (fd < 0)
    return ec;

  int s = descriptor_ops::fcntl(fd, F_GETFL, ec);
  if (s >= 0)
    s = descriptor_ops::fcntl(fd, F_SETFL, s | O_NONBLOCK, ec);
  if (s < 0)
  {
    asio::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
    return ec;
  }

  // Set up default serial port options.
  termios ios;
  errno = 0;
  s = descriptor_ops::error_wrapper(::tcgetattr(fd, &ios), ec);
  if (s >= 0)
  {
#if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
    ::cfmakeraw(&ios);
#else
    ios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK
        | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    ios.c_oflag &= ~OPOST;
    ios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    ios.c_cflag &= ~(CSIZE | PARENB);
    ios.c_cflag |= CS8;
#endif
    ios.c_iflag |= IGNPAR;
    ios.c_cflag |= CREAD | CLOCAL;
    errno = 0;
    s = descriptor_ops::error_wrapper(::tcsetattr(fd, TCSANOW, &ios), ec);
  }
  if (s < 0)
  {
    asio::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
    return ec;
  }

  // We're done. Take ownership of the serial port descriptor.
  if (descriptor_service_.assign(impl, fd, ec))
  {
    asio::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
  }

  return ec;
}

asio::error_code reactive_serial_port_service::do_set_option(
    reactive_serial_port_service::implementation_type& impl,
    reactive_serial_port_service::store_function_type store,
    const void* option, asio::error_code& ec)
{
  termios ios;
  errno = 0;
  descriptor_ops::error_wrapper(::tcgetattr(
        descriptor_service_.native_handle(impl), &ios), ec);
  if (ec)
    return ec;

  if (store(option, ios, ec))
    return ec;

  errno = 0;
  descriptor_ops::error_wrapper(::tcsetattr(
        descriptor_service_.native_handle(impl), TCSANOW, &ios), ec);
  return ec;
}

asio::error_code reactive_serial_port_service::do_get_option(
    const reactive_serial_port_service::implementation_type& impl,
    reactive_serial_port_service::load_function_type load,
    void* option, asio::error_code& ec) const
{
  termios ios;
  errno = 0;
  descriptor_ops::error_wrapper(::tcgetattr(
        descriptor_service_.native_handle(impl), &ios), ec);
  if (ec)
    return ec;

  return load(option, ios, ec);
}

} // namespace detail
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__)
#endif // defined(ASIO_HAS_SERIAL_PORT)

#endif // ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP

{'repo_name': 'zhllxt/asio2', 'stars': '121', 'repo_language': 'C++', 'file_name': 'CA.pl', 'mime_type': 'text/x-perl', 'hash': -2924552380939682503, 'source_dataset': 'data'}


package com.scwang.refreshlayout.activity.style;

import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;

import com.scwang.refreshlayout.R;
import com.scwang.refreshlayout.adapter.BaseRecyclerAdapter;
import com.scwang.refreshlayout.adapter.SmartViewHolder;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.R.layout.simple_list_item_2;
import static android.support.v7.widget.DividerItemDecoration.VERTICAL;

public class PhoenixStyleActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private enum Item {
        折叠(R.string.item_style_app_bar_collapse),
        展开(R.string.item_style_app_bar_expand),
        橙色主题(R.string.item_style_theme_orange_abstract),
        红色主题(R.string.item_style_theme_red_abstract),
        绿色主题(R.string.item_style_theme_green_abstract),
        蓝色主题(R.string.item_style_theme_blue_abstract),
        ;
        public int nameId;
        Item(@StringRes int nameId) {
            this.nameId = nameId;
        }
    }

    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private AppBarLayout mAppBarLayout;
    private RefreshLayout mRefreshLayout;
    private FloatingActionButton mActionButton;
    private CollapsingToolbarLayout mToolbarLayout;
    private static boolean isFirstEnter = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_style_phoenix);

        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRefreshLayout = findViewById(R.id.refreshLayout);
        if (isFirstEnter) {
            isFirstEnter = false;
            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }

        mAppBarLayout = findViewById(R.id.appbar);
        mToolbarLayout = findViewById(R.id.toolbarLayout);

        View view = findViewById(R.id.recyclerView);
        if (view instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            List<Item> items = new ArrayList<>();
            items.addAll(Arrays.asList(Item.values()));
            items.addAll(Arrays.asList(Item.values()));
            recyclerView.setAdapter(new BaseRecyclerAdapter<Item>(items, simple_list_item_2,this) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, Item model, int position) {
                    holder.text(android.R.id.text1, model.name());
                    holder.text(android.R.id.text2, model.nameId);
                    holder.textColorId(android.R.id.text2, R.color.colorTextAssistant);
                }
            });
            mRecyclerView = recyclerView;
        }

        /*
         * 监听 AppBarLayout 的关闭和开启 ActionButton 设置关闭隐藏动画
         */
        mActionButton = findViewById(R.id.fab);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean misAppbarExpand = true;
            View fab = findViewById(R.id.fab);
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int scrollRange = appBarLayout.getTotalScrollRange();
                float fraction = 1f * (scrollRange + verticalOffset) / scrollRange;
                if (fraction < 0.1 && misAppbarExpand) {
                    misAppbarExpand = false;
                    fab.animate().scaleX(0).scaleY(0);
                }
                if (fraction > 0.8 && !misAppbarExpand) {
                    misAppbarExpand = true;
                    fab.animate().scaleX(1).scaleY(1);
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (Item.values()[position % Item.values().length]) {
            case 折叠:
                mAppBarLayout.setExpanded(false, true);
                mAppBarLayout.setEnabled(false);
                mRecyclerView.setNestedScrollingEnabled(false);
                break;
            case 展开:
                mAppBarLayout.setEnabled(true);
                mAppBarLayout.setExpanded(true, true);
                mRecyclerView.setNestedScrollingEnabled(true);
                break;
            case 蓝色主题:
                setThemeColor(R.color.colorPrimary, R.color.colorPrimaryDark);
                break;
            case 绿色主题:
                setThemeColor(android.R.color.holo_green_light, android.R.color.holo_green_dark);
                break;
            case 红色主题:
                setThemeColor(android.R.color.holo_red_light, android.R.color.holo_red_dark);
                break;
            case 橙色主题:
                setThemeColor(android.R.color.holo_orange_light, android.R.color.holo_orange_dark);
                break;
        }
        mRefreshLayout.autoRefresh();
    }

    private void setThemeColor(int colorPrimary, int colorPrimaryDark) {
        mToolbar.setBackgroundResource(colorPrimary);
        mAppBarLayout.setBackgroundResource(colorPrimary);
        mToolbarLayout.setContentScrimResource(colorPrimary);
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.white);
        mActionButton.setBackgroundColor(ContextCompat.getColor(this, colorPrimaryDark));
        mActionButton.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, colorPrimaryDark)));
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, colorPrimaryDark));
        }
    }

}

{'repo_name': 'scwang90/SmartRefreshLayout', 'stars': '21103', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/html', 'hash': -6834849571395312451, 'source_dataset': 'data'}


/**********************************************************************
*These solidity codes have been obtained from Etherscan for extracting
*the smartcontract related info.
*The data will be used by MATRIX AI team as the reference basis for
*MATRIX model analysis,extraction of contract semantics,
*as well as AI based data analysis, etc.
**********************************************************************/
pragma solidity ^0.4.16;

interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }

contract ChenXiangToken {
    // Public variables of the token
    string public name;
    string public symbol;
    uint8 public decimals = 18;
    // 18 decimals is the strongly suggested default, avoid changing it
    uint256 public totalSupply;

    // This creates an array with all balances
    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    // This generates a public event on the blockchain that will notify clients
    event Transfer(address indexed from, address indexed to, uint256 value);

    // This notifies clients about the amount burnt
    event Burn(address indexed from, uint256 value);

    /**
     * Constrctor function
     *
     * Initializes contract with initial supply tokens to the creator of the contract
     */
    function ChenXiangToken(
        uint256 initialSupply,
        string tokenName,
        string tokenSymbol
    ) public {
        totalSupply = initialSupply * 10 ** uint256(decimals);  // Update total supply with the decimal amount
        balanceOf[msg.sender] = totalSupply;                // Give the creator all initial tokens
        name = tokenName;                                   // Set the name for display purposes
        symbol = tokenSymbol;                               // Set the symbol for display purposes
    }

    /**
     * Internal transfer, only can be called by this contract
     */
    function _transfer(address _from, address _to, uint _value) internal {
        // Prevent transfer to 0x0 address. Use burn() instead
        require(_to != 0x0);
        // Check if the sender has enough
        require(balanceOf[_from] >= _value);
        // Check for overflows
        require(balanceOf[_to] + _value > balanceOf[_to]);
        // Save this for an assertion in the future
        uint previousBalances = balanceOf[_from] + balanceOf[_to];
        // Subtract from the sender
        balanceOf[_from] -= _value;
        // Add the same to the recipient
        balanceOf[_to] += _value;
        Transfer(_from, _to, _value);
        // Asserts are used to use static analysis to find bugs in your code. They should never fail
        assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }

    /**
     * Transfer tokens
     *
     * Send `_value` tokens to `_to` from your account
     *
     * @param _to The address of the recipient
     * @param _value the amount to send
     */
    function transfer(address _to, uint256 _value) public {
        _transfer(msg.sender, _to, _value);
    }

    /**
     * Transfer tokens from other address
     *
     * Send `_value` tokens to `_to` in behalf of `_from`
     *
     * @param _from The address of the sender
     * @param _to The address of the recipient
     * @param _value the amount to send
     */
    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_value <= allowance[_from][msg.sender]);     // Check allowance
        allowance[_from][msg.sender] -= _value;
        _transfer(_from, _to, _value);
        return true;
    }

    /**
     * Set allowance for other address
     *
     * Allows `_spender` to spend no more than `_value` tokens in your behalf
     *
     * @param _spender The address authorized to spend
     * @param _value the max amount they can spend
     */
    function approve(address _spender, uint256 _value) public
        returns (bool success) {
        allowance[msg.sender][_spender] = _value;
        return true;
    }

    /**
     * Set allowance for other address and notify
     *
     * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
     *
     * @param _spender The address authorized to spend
     * @param _value the max amount they can spend
     * @param _extraData some extra information to send to the approved contract
     */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData)
        public
        returns (bool success) {
        tokenRecipient spender = tokenRecipient(_spender);
        if (approve(_spender, _value)) {
            spender.receiveApproval(msg.sender, _value, this, _extraData);
            return true;
        }
    }

    /**
     * Destroy tokens
     *
     * Remove `_value` tokens from the system irreversibly
     *
     * @param _value the amount of money to burn
     */
    function burn(uint256 _value) public returns (bool success) {
        require(balanceOf[msg.sender] >= _value);   // Check if the sender has enough
        balanceOf[msg.sender] -= _value;            // Subtract from the sender
        totalSupply -= _value;                      // Updates totalSupply
        Burn(msg.sender, _value);
        return true;
    }

    /**
     * Destroy tokens from other account
     *
     * Remove `_value` tokens from the system irreversibly on behalf of `_from`.
     *
     * @param _from the address of the sender
     * @param _value the amount of money to burn
     */
    function burnFrom(address _from, uint256 _value) public returns (bool success) {
        require(balanceOf[_from] >= _value);                // Check if the targeted balance is enough
        require(_value <= allowance[_from][msg.sender]);    // Check allowance
        balanceOf[_from] -= _value;                         // Subtract from the targeted balance
        allowance[_from][msg.sender] -= _value;             // Subtract from the sender's allowance
        totalSupply -= _value;                              // Update totalSupply
        Burn(_from, _value);
        return true;
    }
}

{'repo_name': 'MatrixAINetwork/SMARTCONTRACT', 'stars': '195', 'repo_language': 'None', 'file_name': 'sc_ContractCatalog_0xa46aaf1b1f69e78d67fcb6c343e1701f835292e4.sol', 'mime_type': 'text/plain', 'hash': 5646029536858155309, 'source_dataset': 'data'}


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

package grpc

import (
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// PreparedMsg is responsible for creating a Marshalled and Compressed object.
//
// This API is EXPERIMENTAL.
type PreparedMsg struct {
	// Struct for preparing msg before sending them
	encodedData []byte
	hdr         []byte
	payload     []byte
}

// Encode marshalls and compresses the message using the codec and compressor for the stream.
func (p *PreparedMsg) Encode(s Stream, msg interface{}) error {
	ctx := s.Context()
	rpcInfo, ok := rpcInfoFromContext(ctx)
	if !ok {
		return status.Errorf(codes.Internal, "grpc: unable to get rpcInfo")
	}

	// check if the context has the relevant information to prepareMsg
	if rpcInfo.preloaderInfo == nil {
		return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo is nil")
	}
	if rpcInfo.preloaderInfo.codec == nil {
		return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo.codec is nil")
	}

	// prepare the msg
	data, err := encode(rpcInfo.preloaderInfo.codec, msg)
	if err != nil {
		return err
	}
	p.encodedData = data
	compData, err := compress(data, rpcInfo.preloaderInfo.cp, rpcInfo.preloaderInfo.comp)
	if err != nil {
		return err
	}
	p.hdr, p.payload = msgHeader(data, compData)
	return nil
}

{'repo_name': 'runatlantis/atlantis', 'stars': '2858', 'repo_language': 'Go', 'file_name': 'recovery_test.go', 'mime_type': 'text/plain', 'hash': -3668180806097844635, 'source_dataset': 'data'}


/*
 * LIBOIL - Library of Optimized Inner Loops
 * Copyright (c) 2003,2004 David A. Schleef <ds@schleef.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <liboil/liboilfunction.h>
#include <liboil/simdpack/simdpack.h>

#define ABS(x) ((x)>0 ? (x) : -(x))

static void
abs_u16_s16_unroll2 (uint16_t * dest, int dstr, int16_t * src, int sstr, int n)
{
  while (n & 1) {
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    n--;
  }
  while (n > 0) {
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    n -= 2;
  }
}
OIL_DEFINE_IMPL (abs_u16_s16_unroll2, abs_u16_s16);

static void
abs_u16_s16_unroll4 (uint16_t * dest, int dstr, int16_t * src, int sstr, int n)
{
  while (n & 3) {
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    n--;
  }
  while (n > 0) {
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    *dest = ABS (*src);
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
    n -= 4;
  }
}
OIL_DEFINE_IMPL (abs_u16_s16_unroll4, abs_u16_s16);

static void
abs_u16_s16_fast (uint16_t * dest, int dstr, int16_t * src, int sstr, int n)
{
  int i;
  int16_t x, y;

  for (i = 0; i < n; i++) {
    x = *src;
    y = ((x >> 15) & x);
    *dest = x - y - y;
    OIL_INCREMENT (dest, dstr);
    OIL_INCREMENT (src, sstr);
  }
}

OIL_DEFINE_IMPL (abs_u16_s16_fast, abs_u16_s16);

/* Similar algorithm as clipping, but for absolute value.  Note the stunt
 * pulled to get around 2*y rolling over.  */

static void
abs_u32_s32_fast (uint32_t * dest, int dstr, int32_t * src, int sstr, int n)
{
  int i;
  int32_t x, y;

  for (i = 0; i < n; i++) {
    x = OIL_GET(src, i * sstr, int32_t);
    y = ((x >> 31) & x);
    OIL_GET(dest, i * dstr, uint32_t) = x - y - y;
  }
}

OIL_DEFINE_IMPL (abs_u32_s32_fast, abs_u32_s32);

{'repo_name': 'artclarke/xuggle-xuggler', 'stars': '328', 'repo_language': 'C', 'file_name': 'org.eclipse.cdt.ui.prefs', 'mime_type': 'text/plain', 'hash': 7224218925930317223, 'source_dataset': 'data'}