text:
""" interactive debugging with PDB, the Python Debugger. """
import argparse
import functools
import sys

from _pytest import outcomes
from _pytest.config import hookimpl
from _pytest.config.exceptions import UsageError

def _validate_usepdb_cls(value):
    """Validate syntax of --pdbcls option."""
    try:
        modname, classname = value.split(":")
    except ValueError:
        raise argparse.ArgumentTypeError(
            "{!r} is not in the format 'modname:classname'".format(value)
        )
    return (modname, classname)

def pytest_addoption(parser):
    group = parser.getgroup("general")
    group._addoption(
        "--pdb",
        dest="usepdb",
        action="store_true",
        help="start the interactive Python debugger on errors or KeyboardInterrupt.",
    )
    group._addoption(
        "--pdbcls",
        dest="usepdb_cls",
        metavar="modulename:classname",
        type=_validate_usepdb_cls,
        help="start a custom interactive Python debugger on errors. "
        "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
    )
    group._addoption(
        "--trace",
        dest="trace",
        action="store_true",
        help="Immediately break when running each test.",
    )

def pytest_configure(config):
    import pdb

    if config.getvalue("trace"):
        config.pluginmanager.register(PdbTrace(), "pdbtrace")
    if config.getvalue("usepdb"):
        config.pluginmanager.register(PdbInvoke(), "pdbinvoke")

    pytestPDB._saved.append(
        (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
    )
    pdb.set_trace = pytestPDB.set_trace
    pytestPDB._pluginmanager = config.pluginmanager
    pytestPDB._config = config

    # NOTE: not using pytest_unconfigure, since it might get called although
    #       pytest_configure was not (if another plugin raises UsageError).
    def fin():
        (
            pdb.set_trace,
            pytestPDB._pluginmanager,
            pytestPDB._config,
        ) = pytestPDB._saved.pop()

    config._cleanup.append(fin)

class pytestPDB:
    """ Pseudo PDB that defers to the real pdb. """

    _pluginmanager = None
    _config = None
    _saved = []  # type: list
    _recursive_debug = 0
    _wrapped_pdb_cls = None

    @classmethod
    def _is_capturing(cls, capman):
        if capman:
            return capman.is_capturing()
        return False

    @classmethod
    def _import_pdb_cls(cls, capman):
        if not cls._config:
            import pdb

            # Happens when using pytest.set_trace outside of a test.
            return pdb.Pdb

        usepdb_cls = cls._config.getvalue("usepdb_cls")

        if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
            return cls._wrapped_pdb_cls[1]

        if usepdb_cls:
            modname, classname = usepdb_cls

            try:
                __import__(modname)
                mod = sys.modules[modname]

                # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
                parts = classname.split(".")
                pdb_cls = getattr(mod, parts[0])
                for part in parts[1:]:
                    pdb_cls = getattr(pdb_cls, part)
            except Exception as exc:
                value = ":".join((modname, classname))
                raise UsageError(
                    "--pdbcls: could not import {!r}: {}".format(value, exc)
                )
        else:
            import pdb

            pdb_cls = pdb.Pdb

        wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
        cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)
        return wrapped_cls

    @classmethod
    def _get_pdb_wrapper_class(cls, pdb_cls, capman):
        import _pytest.config

        class PytestPdbWrapper(pdb_cls):
            _pytest_capman = capman
            _continued = False

            def do_debug(self, arg):
                cls._recursive_debug += 1
                ret = super().do_debug(arg)
                cls._recursive_debug -= 1
                return ret

            def do_continue(self, arg):
                ret = super().do_continue(arg)
                if cls._recursive_debug == 0:
                    tw = _pytest.config.create_terminal_writer(cls._config)
                    tw.line()

                    capman = self._pytest_capman
                    capturing = pytestPDB._is_capturing(capman)
                    if capturing:
                        if capturing == "global":
                            tw.sep(">", "PDB continue (IO-capturing resumed)")
                        else:
                            tw.sep(
                                ">",
                                "PDB continue (IO-capturing resumed for %s)"
                                % capturing,
                            )
                        capman.resume()
                    else:
                        tw.sep(">", "PDB continue")
                cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
                self._continued = True
                return ret

            do_c = do_cont = do_continue

            def do_quit(self, arg):
                """Raise Exit outcome when quit command is used in pdb.

                This is a bit of a hack - it would be better if BdbQuit
                could be handled, but this would require to wrap the
                whole pytest run, and adjust the report etc.
                """
                ret = super().do_quit(arg)

                if cls._recursive_debug == 0:
                    outcomes.exit("Quitting debugger")

                return ret

            do_q = do_quit
            do_exit = do_quit

            def setup(self, f, tb):
                """Suspend on setup().

                Needed after do_continue resumed, and entering another
                breakpoint again.
                """
                ret = super().setup(f, tb)
                if not ret and self._continued:
                    # pdb.setup() returns True if the command wants to exit
                    # from the interaction: do not suspend capturing then.
                    if self._pytest_capman:
                        self._pytest_capman.suspend_global_capture(in_=True)
                return ret

            def get_stack(self, f, t):
                stack, i = super().get_stack(f, t)
                if f is None:
                    # Find last non-hidden frame.
                    i = max(0, len(stack) - 1)
                    while i and stack[i][0].f_locals.get("__tracebackhide__", False):
                        i -= 1
                return stack, i

        return PytestPdbWrapper

    @classmethod
    def _init_pdb(cls, method, *args, **kwargs):
        """ Initialize PDB debugging, dropping any IO capturing. """
        import _pytest.config

        if cls._pluginmanager is not None:
            capman = cls._pluginmanager.getplugin("capturemanager")
        else:
            capman = None
        if capman:
            capman.suspend(in_=True)

        if cls._config:
            tw = _pytest.config.create_terminal_writer(cls._config)
            tw.line()

            if cls._recursive_debug == 0:
                # Handle header similar to pdb.set_trace in py37+.
                header = kwargs.pop("header", None)
                if header is not None:
                    tw.sep(">", header)
                else:
                    capturing = cls._is_capturing(capman)
                    if capturing == "global":
                        tw.sep(">", "PDB {} (IO-capturing turned off)".format(method))
                    elif capturing:
                        tw.sep(
                            ">",
                            "PDB %s (IO-capturing turned off for %s)"
                            % (method, capturing),
                        )
                    else:
                        tw.sep(">", "PDB {}".format(method))

        _pdb = cls._import_pdb_cls(capman)(**kwargs)

        if cls._pluginmanager:
            cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)
        return _pdb

    @classmethod
    def set_trace(cls, *args, **kwargs):
        """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing."""
        frame = sys._getframe().f_back
        _pdb = cls._init_pdb("set_trace", *args, **kwargs)
        _pdb.set_trace(frame)

class PdbInvoke:
    def pytest_exception_interact(self, node, call, report):
        capman = node.config.pluginmanager.getplugin("capturemanager")
        if capman:
            capman.suspend_global_capture(in_=True)
            out, err = capman.read_global_capture()
            sys.stdout.write(out)
            sys.stdout.write(err)
        _enter_pdb(node, call.excinfo, report)

    def pytest_internalerror(self, excrepr, excinfo):
        tb = _postmortem_traceback(excinfo)
        post_mortem(tb)

class PdbTrace:
    @hookimpl(hookwrapper=True)
    def pytest_pyfunc_call(self, pyfuncitem):
        _test_pytest_function(pyfuncitem)
        yield

def _test_pytest_function(pyfuncitem):
    _pdb = pytestPDB._init_pdb("runcall")
    testfunction = pyfuncitem.obj

    # we can't just return `partial(pdb.runcall, testfunction)` because (on
    # python < 3.7.4) runcall's first param is `func`, which means we'd get
    # an exception if one of the kwargs to testfunction was called `func`
    @functools.wraps(testfunction)
    def wrapper(*args, **kwargs):
        func = functools.partial(testfunction, *args, **kwargs)
        _pdb.runcall(func)

    pyfuncitem.obj = wrapper

def _enter_pdb(node, excinfo, rep):
    # XXX we re-use the TerminalReporter's terminalwriter
    # because this seems to avoid some encoding related troubles
    # for not completely clear reasons.
    tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
    tw.line()

    showcapture = node.config.option.showcapture

    for sectionname, content in (
        ("stdout", rep.capstdout),
        ("stderr", rep.capstderr),
        ("log", rep.caplog),
    ):
        if showcapture in (sectionname, "all") and content:
            tw.sep(">", "captured " + sectionname)
            if content[-1:] == "\n":
                content = content[:-1]
            tw.line(content)

    tw.sep(">", "traceback")
    rep.toterminal(tw)
    tw.sep(">", "entering PDB")
    tb = _postmortem_traceback(excinfo)
    rep._pdbshown = True
    post_mortem(tb)
    return rep

def _postmortem_traceback(excinfo):
    from doctest import UnexpectedException

    if isinstance(excinfo.value, UnexpectedException):
        # A doctest.UnexpectedException is not useful for post_mortem.
        # Use the underlying exception instead:
        return excinfo.value.exc_info[2]
    else:
        return excinfo._excinfo[2]

def post_mortem(t):
    p = pytestPDB._init_pdb("post_mortem")
    p.reset()
    p.interaction(None, t)
    if p.quitting:
        outcomes.exit("Quitting debugger")


text:
import { Component, OnInit } from '@angular/core';
import { Crisis, CrisisService } from './crisis.service';

@Component({
    selector: 'crisis-list',
    templateUrl: './crisis-list.component.html',
    styleUrls: ['./crisis-list.component.css'],
})
export class CrisisListComponent implements OnInit {
    crises: Promise<Crisis[]>;

    constructor(private crisisService: CrisisService){}

    ngOnInit():void  {
        this.crises = this.crisisService.getCrises();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.skysail.core.model

/**
 * Describes types of associations between resources.
 *
 * For example, a SkysailApplication can define a resource to be used when there is a request to the
 * root context by setting "addAssociatedResourceClasses(List((APPLICATION_CONTEXT_RESOURCE, classOf[ConfigsResource])))".
 */
sealed trait ResourceAssociationType

/**
 * An {@link ApplicationModel} can define the resource which should be used to serve the
 * root context.
 */
case object APPLICATION_CONTEXT_RESOURCE extends ResourceAssociationType

case object RESOURCE_SELF extends ResourceAssociationType
case object ENTITY_RESOURCE_FOR_LIST_RESOURCE extends ResourceAssociationType
case object LINKED_RESOURCE extends ResourceAssociationType
case object FORM_TARGET_RESOURCE extends ResourceAssociationType


text:
package images

import (
	"github.com/chrislusf/seaweedfs/weed/util"
	"os"
	"testing"
)

func TestXYZ(t *testing.T) {
	fname := "sample1.jpg"

	dat, _ := os.ReadFile(fname)

	fixed_data := FixJpgOrientation(dat)

	util.WriteFile("fixed1.jpg", fixed_data, 0644)

	os.Remove("fixed1.jpg")

}


text:
    width: 400px;
    height: 100%;
    margin: auto;
    margin-top: 2%;
    margin-left: 35%;
    background-color: ;
}
input[type=text]{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}
input[type=password]{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}
input[type=submit]{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}
input[type=reset]{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}
textarea{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}
#block{
    width: 200px;
    height: 300px;
    background: red;
    float: left;
    margin-top: 5%;
    margin-left: 10%;
}
#login{
    width: 400px;
    height: 300px;
    background: red;
    float: left;
    font-size: 28px ;
    margin-left: 10%;
    margin-top: 5%;

}
#botaolog{
    background: lightgray;
    text-align: center;
    width: 100px;
    border-radius: 5px;
    float: left;
    margin-left: 20%;
    font-family: tahoma;
    font-size: 18px;
}
#blockcad{
    width: 400px;
    height: 200px;
    //background: ;
    float: left;
    text-align: center;
    margin-top: 10%;
    font-size: 24px;
}
#blockcontato{
    width: 500px;
    height: 100%;
    //background: ;
    margin: auto;
    //margin-top: %;
    font-family: tahoma;
    font-size: 26px;

}
#blockpainelvendedor{
    width: 500px;
    height: 150px;
    background:red ;
    margin: auto;
    margin-top: 10%;
    font-family: tahoma;
    font-size: 24px;
}
#botaopainel{
    width: 35%;
    background: darkblue;
    color: white;
    border-radius: 5px;
    float: left;
    text-align: center;
    margin-left: 50px;
    margin-top: 5%;
}
#blockcliven{
    width: 500px;
    height: 200px;
    //background:;
    margin: auto;
    text-align: left;
    font-family: tahoma;
    font-size: 20px;
    margin-top: 5%;
}
.botaoform{
    background: lightgray;
    text-align: center;
    width: 100px;
    border-radius: 5px;
    float: right;
    margin-top: 2%;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;;
    font-size: 18px;
    box-shadow: 5px 5px 5px gray;
}
#tablelog{
    font-size: 30px;
}
#tablelog input[type=text]{
    background-color: white;
    border:1px solid navy;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}


text:
// import * as XmlCore from "xml-core";
import { XmlAttribute, XmlChildElement, XmlContent, XmlElement } from "xml-core";

import { XmlXades } from "./xml";
import { XadesCollection, XadesObject } from "./xml_base";

/**
 *
 * <!-- Start ObjectIdentifierType-->
 * <xsd:element name="ObjectIdentifier" type="ObjectIdentifierType"/>
 * <xsd:complexType name="ObjectIdentifierType">
 *   <xsd:sequence>
 *     <xsd:element name="Identifier" type="IdentifierType"/>
 *     <xsd:element name="Description" type="xsd:string" minOccurs="0"/>
 *     <xsd:element name="DocumentationReferences" type="DocumentationReferencesType" minOccurs="0"/>
 *   </xsd:sequence>
 * </xsd:complexType>
 * <xsd:complexType name="IdentifierType">
 *   <xsd:simpleContent>
 *     <xsd:extension base="xsd:anyURI">
 *       <xsd:attribute name="Qualifier" type="QualifierType" use="optional"/>
 *     </xsd:extension>
 *   </xsd:simpleContent>
 * </xsd:complexType>
 * <xsd:simpleType name="QualifierType">
 *   <xsd:restriction base="xsd:string">
 *     <xsd:enumeration value="OIDAsURI"/>
 *     <xsd:enumeration value="OIDAsURN"/>
 *   </xsd:restriction>
 * </xsd:simpleType>
 * <xsd:complexType name="DocumentationReferencesType">
 *   <xsd:sequence maxOccurs="unbounded">
 *      <xsd:element name="DocumentationReference" type="xsd:anyURI"/>
 *   </xsd:sequence>
 * </xsd:complexType>
 * <!-- End ObjectIdentifierType-->
 *
 */

export type IdentifierQualifier = "OIDAsURI" | "OIDAsURN";

@XmlElement({
    localName: XmlXades.ElementNames.Identifier,
})
export class Identifier extends XadesObject {

    @XmlAttribute({
        localName: XmlXades.AttributeNames.Qualifier,
    })
    public Qualifier: IdentifierQualifier;

    @XmlContent({
        defaultValue: "",
        required: true,
    })
    public Value: string;

}

@XmlElement({
    localName: XmlXades.ElementNames.DocumentationReference,
})
export class DocumentationReference extends XadesObject {

    @XmlContent({
        defaultValue: "",
        required: true,
    })
    public Uri: string;

    protected OnLoadXml(e: Element) {
        if (e.textContent) {
            this.Uri = e.textContent;
        }
    }

    protected OnGetXml(e: Element) {
        if (this.Uri) {
            e.textContent = this.Uri;
        }
    }

}

@XmlElement({
    localName: XmlXades.ElementNames.DocumentationReferences,
    parser: DocumentationReference,
})
export class DocumentationReferences extends XadesCollection<DocumentationReference> { }

@XmlElement({
    localName: XmlXades.ElementNames.ObjectIdentifier,
})
export class ObjectIdentifier extends XadesObject {

    @XmlChildElement({
        parser: Identifier,
        required: true,
    })
    public Identifier: Identifier;

    @XmlChildElement({
        localName: XmlXades.ElementNames.Description,
        namespaceURI: XmlXades.NamespaceURI,
        prefix: XmlXades.DefaultPrefix,
        defaultValue: "",
    })
    public Description: string;

    @XmlChildElement({
        parser: DocumentationReferences,
    })
    public DocumentationReferences: DocumentationReferences;

}


text:
class ThreadSweeper < ActionController::Caching::Sweeper
  observe Discussion::ThreadRead

  def after_save(thread_read)
    expire_cache_for(thread_read) if thread_read.read_changed?
  end

  def after_create(thread_read)
    expire_cache_for(thread_read)
  end

  def after_destroy(thread_read)
    expire_cache_for(thread_read)
  end

  private
  def expire_cache_for(thread_read)
    Rails.logger.debug "deleting cache for :: #{thread_read.user_id}"
    Rails.logger.debug "================================================================="
    Rails.cache.delete("total_unread_thread_by_#{thread_read.user_id}")
  end

end


text:
package ru.pavkin.todoist.api.core.dto

import ru.pavkin.todoist.api.core.IsResourceId

case class MultipleIdCommand[T: IsResourceId](ids: List[T])


text:
layout: page
title: Twin Tech Trade Fair
date: 2016-05-24
author: James Mcneil
tags: weekly links, java
status: published
summary: Sed mattis, enim quis suscipit ultricies, justo arcu fermentum nunc.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 08/07/2017
  endDate: 08/11/2017
  ctyhocn: CAELXHX
  groupCode: TTTF
published: true
---
Quisque vestibulum tortor nulla, vel mollis ex interdum sed. Nulla nec erat sit amet lectus auctor volutpat ut eu nisi. Suspendisse eget magna eget tortor dignissim viverra in et mi. Pellentesque quis orci egestas odio elementum aliquam ac et ligula. Curabitur convallis ornare lectus, ac dapibus risus. Proin accumsan massa lorem, id efficitur ex convallis id. Nam maximus sem quis finibus ornare. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

1 Nullam ullamcorper neque vitae eros tristique placerat
1 Curabitur consequat purus non accumsan vehicula
1 Etiam sagittis felis eu libero aliquet efficitur.

Nunc sed venenatis neque. Aliquam finibus ultrices metus ut dapibus. Curabitur tristique tempus posuere. Proin pretium, metus non consectetur pellentesque, odio nisl pretium felis, quis hendrerit nulla felis nec est. Vestibulum in justo id mi gravida mollis eget eu turpis. Phasellus dapibus neque quis auctor cursus. Maecenas vitae dapibus ex. Nam sed sodales elit. Nulla cursus odio ut magna gravida blandit. Aliquam lectus nibh, tempus at bibendum et, condimentum faucibus ante. Maecenas gravida risus eu libero vehicula, rutrum posuere purus suscipit. Curabitur ultrices imperdiet elementum. Praesent sagittis consequat faucibus. Cras vulputate enim tortor, id sodales enim lobortis sit amet. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla eu nibh vitae elit pharetra cursus. Nulla blandit purus non lectus maximus venenatis. Fusce feugiat est elit, at volutpat odio gravida in. Vestibulum sed dolor magna. Aenean facilisis accumsan ex, sed egestas turpis congue mattis. Maecenas aliquam enim a tortor sollicitudin, suscipit tincidunt magna aliquet. Suspendisse dolor diam, laoreet et justo in, molestie finibus mi. Phasellus vitae lacinia eros. Nulla facilisi. Maecenas dictum dolor at efficitur volutpat. In finibus mauris metus, id commodo tellus sollicitudin a.


text:
package com.eboji.center.bootstrap;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;

import com.eboji.center.util.ConfigUtil;

/**
 * 中心服务启动的入口类
 * @author zhoucl 2016-02-19
 */
public class CenterServerBootstrap {
	private static final Logger logger = LoggerFactory.getLogger(CenterServerBootstrap.class);

	private static final Daemon daemon = Daemon.getInstance();

	private static Boolean DEBUG = true;

	static {
		try {
			ShutdownHook.doShutdownHook();

			/**
			 * 读取conf文件夹中的logback.xml配置文件
			 */
			if(!DEBUG) {
				String jarPath = CenterServerBootstrap.class.getProtectionDomain().getCodeSource().getLocation().getFile();
				jarPath = jarPath.substring(0, jarPath.lastIndexOf('/'));
				jarPath = jarPath.substring(0, jarPath.lastIndexOf('/') + 1) + "conf";
				File logbackFile = new File(jarPath + "/logback.xml");

				if (logbackFile.exists()) {
		            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		            JoranConfigurator configurator = new JoranConfigurator();
		            configurator.setContext(lc);
		            lc.reset();
		            try {
		                configurator.doConfigure(logbackFile);
		            }
		            catch (JoranException e) {
		                e.printStackTrace(System.err);
		                System.exit(-1);
		            }
		        }
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	public static void main(String[] args) {
		logger.info("CenterServer is starting.");
		DEBUG = Boolean.valueOf(System.getProperty("debug", "true"));

		try {
			if(DEBUG) {
				loadProps(DEBUG);

				daemon.init();
				daemon.start();
			} else {
				checkArgs(args);
				String command = "start";
				if(args.length > 0) {
					command = args[args.length - 1];
				}

				if(command.equals("start")) {
					daemon.init();
					daemon.start();
				} else if(command.equals("stop")) {
					daemon.stop();
				} else {
					logger.warn("CenterServer Bootstrap: command \"" + command + "\" does not exist.");
				}
			}
		} catch (Exception e) {
			logger.error("CenterServer started fail!", e);
			System.exit(-1);
		}
	}

	private static void checkArgs(String[] args) {
		logger.info("check args is starting.");
		try {
			for (int i = 0; i < args.length; ++i) {
				if (args[i].startsWith("--port")) {
					daemon.setPort(Integer.valueOf(args[i].split("=")[1]));
				} else if (args[i].equals("--timeout")) {

				} else if (args[i].equals("--ssl")) {

				} else if (args[i].equals("--help")) {
					System.out.println("Allowed options:");
					System.out.println("  --help\t\t\tProduce help message");
					System.out.println("  --port=arg (=" + daemon.getPort() + ")\t\tPort number to connect");
					System.exit(0);
				}
			}
		} catch (Exception x) {
			logger.error("Can not parse arguments! See --help");
			System.exit(-1);
		}
		logger.info("check args finished.");
	}

	private static void loadProps(Boolean isDebug) {
		String filePath = "";
		FileInputStream fis = null;

		try {
			if(DEBUG) {
				filePath = CenterServerBootstrap.class.getClass().getResource("/").getPath() + "config.properties";
			} else {
				String jarPath = CenterServerBootstrap.class.getProtectionDomain().getCodeSource().getLocation().getFile();
				jarPath = jarPath.substring(0, jarPath.lastIndexOf('/'));
				jarPath = jarPath.substring(0, jarPath.lastIndexOf('/') + 1) + "conf";
				filePath = jarPath + "/config.properties";
			}

			fis = new FileInputStream(new File(filePath));
			Properties p = new Properties();
			p.load(fis);

			logger.info("loading config file: "  + filePath + " success!");

			ConfigUtil.setProps(p);
		} catch (Exception e) {
			logger.error("loading config file: " + filePath + " exception:\n" + e.getMessage());
		}
	}
}


text:
namespace boost {

    template <typename T>
    class reference_wrapper;
} // namespace boost

#include <boost/parameter/aux_/yesno.hpp>

namespace boost { namespace parameter { namespace aux {

    //
    // reference_wrapper support -- if perfect forwarding is unsupported,
    // then when passing arguments positionally by non-const reference,
    // we ask users of named parameter interfaces to use ref(x) to wrap them.
    //

    template <typename U>
    ::boost::parameter::aux::yes_tag
        is_cv_reference_wrapper_check(
            ::boost::reference_wrapper<U> const volatile*
        );

    ::boost::parameter::aux::no_tag is_cv_reference_wrapper_check(...);
}}} // namespace boost::parameter::aux

#include <boost/parameter/config.hpp>

#if !defined(BOOST_NO_CXX11_HDR_FUNCTIONAL)
#include <functional>

namespace boost { namespace parameter { namespace aux {

    // Support for std::ref(x) -- Cromwell D. Enage
    template <typename U>
    ::boost::parameter::aux::yes_tag
        is_cv_reference_wrapper_check(
            ::std::reference_wrapper<U> const volatile*
        );
}}} // namespace boost::parameter::aux
#endif

#include <boost/parameter/aux_/preprocessor/nullptr.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11) && !( \
        BOOST_WORKAROUND(BOOST_MSVC, >= 1900) && \
        BOOST_WORKAROUND(BOOST_MSVC, < 1910) \
    )
#include <boost/mp11/integral.hpp>
#include <boost/mp11/utility.hpp>
#include <type_traits>
#else   // !defined(BOOST_PARAMETER_CAN_USE_MP11) || MSVC-14.0
#include <boost/mpl/bool.hpp>
#include <boost/type_traits/remove_reference.hpp>
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && \
    !BOOST_WORKAROUND(BOOST_GCC, < 40000)
#include <boost/mpl/eval_if.hpp>
#endif
#endif  // BOOST_PARAMETER_CAN_USE_MP11 && not MSVC-14.0

namespace boost { namespace parameter { namespace aux {

#if defined(BOOST_PARAMETER_CAN_USE_MP11) && !( \
        BOOST_WORKAROUND(BOOST_MSVC, >= 1900) && \
        BOOST_WORKAROUND(BOOST_MSVC, < 1910) \
    )
    // This metafunction returns mp11::mp_true if T is of type
    // reference_wrapper<U> cv.
    template <typename T>
    using is_cv_reference_wrapper = ::boost::mp11::mp_bool<
        sizeof(
            ::boost::parameter::aux::is_cv_reference_wrapper_check(
                static_cast<
                    typename ::std::remove_reference<T>::type*
                >(BOOST_PARAMETER_AUX_PP_NULLPTR)
            )
        ) == sizeof(::boost::parameter::aux::yes_tag)
    >;

    // Needed for unwrap_cv_reference below. T might be const, so
    // mp_eval_if<> might fail because of deriving from T const on EDG.
    template <typename T>
    using unwrap_cv_reference_impl = typename ::std::remove_reference<T>::type;

    // Produces the unwrapped type to hold a reference to in
    // tagged_argument<>.  Can't use boost::unwrap_reference<> here
    // because it doesn't handle the case where T = reference_wrapper<U> cv.
    template <typename T>
    using unwrap_cv_reference = ::boost::mp11::mp_eval_if<
        ::boost::parameter::aux::is_cv_reference_wrapper<T>
      , ::boost::parameter::aux::unwrap_cv_reference_impl<T>
      , ::std::remove_reference
      , T
    >;
#else  // !defined(BOOST_PARAMETER_CAN_USE_MP11) || MSVC-14.0
    // This metafunction returns mpl::true_ if T is of type
    // reference_wrapper<U> cv.
    template <typename T>
    struct is_cv_reference_wrapper
    {
        BOOST_STATIC_CONSTANT(
            bool, value = (
                sizeof(
                    ::boost::parameter::aux::is_cv_reference_wrapper_check(
                        static_cast<
                            typename ::boost::remove_reference<T>::type*
                        >(BOOST_PARAMETER_AUX_PP_NULLPTR)
                    )
                ) == sizeof(::boost::parameter::aux::yes_tag)
            )
        );

        typedef boost::mpl::bool_<
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
            is_cv_reference_wrapper::
#endif
        value> type;
    };

#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) || \
    BOOST_WORKAROUND(BOOST_GCC, < 40000)
    template <
        typename T
      , typename = typename ::boost::parameter::aux
        ::is_cv_reference_wrapper<T>::type
    >
    struct unwrap_cv_reference : ::boost::remove_reference<T>
    {
    };

    template <typename T>
    struct unwrap_cv_reference<T const,::boost::mpl::false_>
    {
        typedef T const type;
    };

    template <typename T>
    struct unwrap_cv_reference<T,::boost::mpl::true_> : T
    {
    };
#else   // no Borland or GCC 3- workarounds needed
    // Needed for unwrap_cv_reference below. T might be const, so
    // eval_if<> might fail because of deriving from T const on EDG.
    template <typename T>
    struct unwrap_cv_reference_impl : ::boost::remove_reference<T>::type
    {
    };

    // Produces the unwrapped type to hold a reference to in
    // tagged_argument<>.  Can't use boost::unwrap_reference<> here
    // because it doesn't handle the case where T = reference_wrapper<U> cv.
    template <typename T>
    struct unwrap_cv_reference
      : ::boost::mpl::eval_if<
            ::boost::parameter::aux::is_cv_reference_wrapper<T>
          , ::boost::parameter::aux::unwrap_cv_reference_impl<T>
          , ::boost::remove_reference<T>
        >
    {
    };
#endif  // Borland or GCC 3- workarounds needed
#endif  // BOOST_PARAMETER_CAN_USE_MP11 && not MSVC-14.0
}}} // namespace boost::parameter::aux

#endif  // include guard


text:
namespace constants {
extern const size_t min_capacity;
extern const size_t max_capacity;

extern const size_t alphabetic_characters_count;

extern const char min_character;
extern const char max_character;
}


text:
"""Experimental library that exposes XLA operations directly in TensorFlow.

It is sometimes useful to be able to build HLO programs directly from
TensorFlow. This file provides Tensorflow operators that mirror the semantics of
HLO operators as closely as possible.

Note: There is no promise of backward or forward compatibility for operators
defined in this module. This is primarily because the underlying HLO operators
do not promise backward or forward compatibility.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.compiler.tf2xla.ops import gen_xla_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import bitwise_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops

# TODO(phawkins): provide wrappers for all XLA operators. Currently the missing
# ops include:
# infeed/outfeed (available via tf.contrib.tpu)
# collectives, e.g., cross-replica-sum (available via tf.contrib.tpu)
# conditional
# gather/scatter
# collapse

# This file reuses builtin names (following XLA's names, so we can call things
# like xla.max), so we capture the builtin versions here.
# pylint: disable=redefined-builtin
_max = max
_min = min
_slice = slice  # pylint: disable=invalid-name

constant = constant_op.constant

# Unary operators.

# For most arithmetic operators there is a TensorFlow operator
# that exactly corresponds to each XLA operator. Rather than defining
# XLA-specific variants, we reuse the corresponding TensorFlow operator.
# TODO(phawkins): It would be even better to have TensorFlow operators that 1:1
# wrap every HLO operator, because that would allow us to be confident that the
# semantics match.

def _unary_op(fn):
  """Wrapper that restricts `fn` to have the correct signature."""

  def unary_op_wrapper(x, name=None):
    return fn(x, name=name)

  return unary_op_wrapper

abs = _unary_op(math_ops.abs)
# TODO(phawkins): implement clz.
conj = _unary_op(math_ops.conj)
cos = _unary_op(math_ops.cos)
ceil = _unary_op(math_ops.ceil)
digamma = _unary_op(math_ops.digamma)
erf = _unary_op(math_ops.erf)
erfc = _unary_op(math_ops.erfc)
# TODO(phawkins): implement erfinv
exp = _unary_op(math_ops.exp)
expm1 = _unary_op(math_ops.expm1)
floor = _unary_op(math_ops.floor)
imag = _unary_op(math_ops.imag)
is_finite = _unary_op(math_ops.is_finite)
lgamma = _unary_op(math_ops.lgamma)
log = _unary_op(math_ops.log)
log1p = _unary_op(math_ops.log1p)
logical_not = _unary_op(math_ops.logical_not)
neg = _unary_op(math_ops.neg)
real = _unary_op(math_ops.real)
# TODO(phawkins): unlike xla::Round, this rounds to even instead of zero for
# numbers halfway between two integers.
round = _unary_op(math_ops.round)
sin = _unary_op(math_ops.sin)
sign = _unary_op(math_ops.sign)
tanh = _unary_op(math_ops.tanh)

# Bessel
bessel_i0e = _unary_op(math_ops.bessel_i0e)
bessel_i1e = _unary_op(math_ops.bessel_i1e)

# Binary operators

# The main difference between TensorFlow and XLA binary ops is the broadcasting
# semantics. TensorFlow uses Numpy-style broadcasting semantics, whereas XLA
# requires an explicit specification of which dimensions to broadcast if the
# arguments have different ranks.

def _broadcasting_binary_op(fn):
  """Wraps a binary Tensorflow operator and performs XLA-style broadcasting."""

  def broadcasting_binary_op_wrapper(x, y, broadcast_dims=None, name=None):
    """Inner wrapper function."""
    broadcast_dims = broadcast_dims or []
    broadcast_dims = ops.convert_to_tensor(broadcast_dims, dtypes.int64)
    # Rather than relying on having static shape information in the TensorFlow
    # graph, we use an XlaBroadcastHelper op that can compute the correct shapes
    # at JIT compilation time.
    x, y = gen_xla_ops.xla_broadcast_helper(x, y, broadcast_dims)
    return fn(x, y, name=name)

  return broadcasting_binary_op_wrapper

# Map from TF signed types to TF unsigned types.
_SIGNED_TO_UNSIGNED_TABLE = {
    dtypes.int8: dtypes.uint8,
    dtypes.int16: dtypes.uint16,
    dtypes.int32: dtypes.uint32,
    dtypes.int64: dtypes.uint64,
}

# Map from TF unsigned types to TF signed types.
_UNSIGNED_TO_SIGNED_TABLE = {
    dtypes.uint8: dtypes.int8,
    dtypes.uint16: dtypes.int16,
    dtypes.uint32: dtypes.int32,
    dtypes.uint64: dtypes.int64,
}

def _shift_right_logical_helper(x, y, name=None):
  """Performs an integer right logical shift irrespective of input type."""
  assert y.dtype == x.dtype
  dtype = x.dtype
  signed = dtype in _SIGNED_TO_UNSIGNED_TABLE
  if signed:
    unsigned_dtype = _SIGNED_TO_UNSIGNED_TABLE[dtype]
    x = math_ops.cast(x, unsigned_dtype)
    y = math_ops.cast(y, unsigned_dtype)
  output = bitwise_ops.right_shift(x, y, name=name)
  if signed:
    output = math_ops.cast(output, dtype)
  return output

def _shift_right_arithmetic_helper(x, y, name=None):
  """Performs an integer right arithmetic shift irrespective of input type."""
  assert y.dtype == x.dtype
  dtype = x.dtype
  unsigned = dtype in _UNSIGNED_TO_SIGNED_TABLE
  if unsigned:
    signed_dtype = _UNSIGNED_TO_SIGNED_TABLE[dtype]
    x = math_ops.cast(x, signed_dtype)
    y = math_ops.cast(y, signed_dtype)
  output = bitwise_ops.right_shift(x, y, name=name)
  if unsigned:
    output = math_ops.cast(output, dtype)
  return output

add = _broadcasting_binary_op(math_ops.add)
sub = _broadcasting_binary_op(math_ops.sub)
mul = _broadcasting_binary_op(math_ops.mul)
div = _broadcasting_binary_op(math_ops.div)
rem = _broadcasting_binary_op(gen_math_ops.mod)
max = _broadcasting_binary_op(math_ops.maximum)
min = _broadcasting_binary_op(math_ops.minimum)
atan2 = _broadcasting_binary_op(math_ops.atan2)
complex = _broadcasting_binary_op(math_ops.complex)
logical_and = _broadcasting_binary_op(math_ops.logical_and)
logical_or = _broadcasting_binary_op(math_ops.logical_or)
logical_xor = _broadcasting_binary_op(math_ops.logical_xor)
eq = _broadcasting_binary_op(math_ops.equal)
ne = _broadcasting_binary_op(math_ops.not_equal)
ge = _broadcasting_binary_op(math_ops.greater_equal)
gt = _broadcasting_binary_op(math_ops.greater)
le = _broadcasting_binary_op(math_ops.less_equal)
lt = _broadcasting_binary_op(math_ops.less)
pow = _broadcasting_binary_op(math_ops.pow)
shift_left = _broadcasting_binary_op(bitwise_ops.left_shift)
shift_right_logical = _broadcasting_binary_op(_shift_right_logical_helper)
shift_right_arithmetic = _broadcasting_binary_op(_shift_right_arithmetic_helper)

def _binary_op(fn):
  """Wrapper that restricts `fn` to have the correct signature."""

  def binary_op_wrapper(x, y, name=None):
    return fn(x, y, name=name)

  return binary_op_wrapper

transpose = _binary_op(array_ops.transpose)
rev = _binary_op(array_ops.reverse)

bitcast_convert_type = array_ops.bitcast

def broadcast(x, dims, name=None):
  x = ops.convert_to_tensor(x)
  shape = array_ops.concat([constant_op.constant(dims),
                            array_ops.shape(x)],
                           axis=0)
  return array_ops.broadcast_to(x, shape, name=name)

def clamp(a, x, b, name=None):
  return min(max(a, x, name=name), b, name=name)

concatenate = array_ops.concat

def conv(lhs,
         rhs,
         window_strides,
         padding,
         lhs_dilation,
         rhs_dilation,
         dimension_numbers,
         feature_group_count=1,
         precision_config=None,
         name=None):
  """Wraps the XLA ConvGeneralDilated operator.

  ConvGeneralDilated is the most general form of XLA convolution and is
  documented at
  https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution

  Args:
    lhs: the input tensor
    rhs: the kernel tensor
    window_strides: the inter-window strides
    padding: the padding to apply at the start and end of each input dimensions
    lhs_dilation: dilation to apply between input elements
    rhs_dilation: dilation to apply between kernel elements
    dimension_numbers: a `ConvolutionDimensionNumbers` proto.
    feature_group_count: number of feature groups for grouped convolution.
    precision_config: a `xla.PrecisionConfig` proto.
    name: an optional name for the operator

  Returns:
    A tensor representing the output of the convolution.
  """
  precision_config_proto = ""
  if precision_config:
    precision_config_proto = precision_config.SerializeToString()
  return gen_xla_ops.xla_conv(
      lhs,
      rhs,
      window_strides=window_strides,
      padding=padding,
      lhs_dilation=lhs_dilation,
      rhs_dilation=rhs_dilation,
      feature_group_count=feature_group_count,
      dimension_numbers=dimension_numbers.SerializeToString(),
      precision_config=precision_config_proto,
      name=name)

convert_element_type = math_ops.cast

def dot(lhs, rhs, name=None):
  return math_ops.tensordot(lhs, rhs, axes=1, name=name)

def dot_general(lhs, rhs, dimension_numbers, precision_config=None, name=None):
  precision_config_proto = ""
  if precision_config:
    precision_config_proto = precision_config.SerializeToString()
  return gen_xla_ops.xla_dot(
      lhs,
      rhs,
      dimension_numbers=dimension_numbers.SerializeToString(),
      precision_config=precision_config_proto,
      name=name)

def self_adjoint_eig(a, lower, max_iter, epsilon):
  return gen_xla_ops.xla_self_adjoint_eig(a, lower, max_iter, epsilon)

def svd(a, max_iter, epsilon, precision_config=None):
  precision_config_proto = ""
  if precision_config:
    precision_config_proto = precision_config.SerializeToString()
  return gen_xla_ops.xla_svd(a, max_iter, epsilon, precision_config_proto)

dynamic_slice = gen_xla_ops.xla_dynamic_slice
dynamic_update_slice = gen_xla_ops.xla_dynamic_update_slice
einsum = gen_xla_ops.xla_einsum

# TODO(phawkins): generalize tf.pad to support interior padding, and then remove
# the XLA-specific pad operator.
pad = gen_xla_ops.xla_pad

def random_normal(mu, sigma, dims, name=None):
  mu = ops.convert_to_tensor(mu)
  return random_ops.random_normal(
      dims, mean=mu, stddev=sigma, dtype=mu.dtype, name=name)

def random_uniform(minval, maxval, dims, name=None):
  minval = ops.convert_to_tensor(minval)
  return random_ops.random_uniform(
      dims, minval, maxval, dtype=minval.dtype, name=name)

recv = gen_xla_ops.xla_recv
reduce = gen_xla_ops.xla_reduce

def reduce_window(operand,
                  init,
                  reducer,
                  window_dimensions,
                  window_strides=None,
                  base_dilations=None,
                  window_dilations=None,
                  padding=None,
                  name=None):
  """Wraps the XLA ReduceWindow operator.

  ReduceWindow is documented at
  https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow .

  Args:
    operand: the input tensor
    init: a scalar tensor representing the initial value for the reduction
    reducer: a reduction function that combines a pair of scalars.
    window_dimensions: shape of the window, as a list of integers
    window_strides: inter-window strides, as a list of integers. Optional; if
      omitted, defaults to strides of 1.
    padding: padding to apply to 'operand'. List of (low, high) pairs of
      integers that specify the padding to apply before and after each
      dimension. Optional; if omitted, defaults to no padding.
    name: the operator name, or None.

  Returns:
    A tensor that represents the output of the reduce_window operator.
  """
  window_strides = window_strides or [1] * len(window_dimensions)
  base_dilations = base_dilations or [1] * len(window_dimensions)
  window_dilations = window_dilations or [1] * len(window_dimensions)
  padding = padding or [(0, 0)] * len(window_dimensions)
  return gen_xla_ops.xla_reduce_window(
      input=operand,
      init_value=init,
      window_dimensions=window_dimensions,
      window_strides=window_strides,
      base_dilations=base_dilations,
      window_dilations=window_dilations,
      padding=padding,
      computation=reducer,
      name=name)

replica_id = gen_xla_ops.xla_replica_id

def reshape(x, new_sizes, dimensions=None, name=None):
  if dimensions is not None:
    x = array_ops.transpose(x, dimensions)
  x = array_ops.reshape(x, new_sizes, name=name)
  return x

def select(condition, x, y, name=None):
  return array_ops.where(condition, x, y, name)

select_and_scatter = gen_xla_ops.xla_select_and_scatter
send = gen_xla_ops.xla_send

def slice(x, start_dims, limit_dims, strides):
  spec = [
      _slice(start, limit, stride)
      for (start, limit, stride) in zip(start_dims, limit_dims, strides)
  ]
  return x[tuple(spec)]

sharding = gen_xla_ops.xla_sharding

@ops.RegisterGradient("XlaSharding")
def _sharding_grad(op, grad):
  del op  # Unused
  return [grad]

sort = gen_xla_ops.xla_sort
key_value_sort = gen_xla_ops.xla_key_value_sort
while_loop = gen_xla_ops.xla_while
dequantize = gen_xla_ops.xla_dequantize


text:
/*M*
Copyright (c) 2002-2005, Intel Corporation
All rights reserved.

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

  a.. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
  b.. 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.
  c.. Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *M*/
#include <stdio.h>
#ifdef WIN32
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
#elif defined(DOS)
#include <dos.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
#else
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#if defined(HPUX)
/* getopt is defined in stdio.h */
#elif defined(MACOS)
/* getopt is defined in unistd.h */
#include <unistd.h>
#else
#include <getopt.h>
#endif
#endif
#include <time.h>

#include "ipmicmd.h"

#define  SELprintf  printf
#define  ETYPE_CRITSTOP  0x20
#define  RTYPE_OEM2      0xe0  /* 2nd OEM type (range) */

#pragma pack(1)
typedef struct
{
        ushort             record_id;
        uchar              record_type;
        uint               timestamp;
        ushort             generator_id;    /*slave_addr/channel*/
        uchar              evm_rev;         //event message revision
        uchar              sensor_type;
        uchar              sensor_number;
        uchar              event_trigger;
        uchar              event_data1;
        uchar              event_data2;
        uchar              event_data3;
}       SEL_RECORD;
#pragma pack()

#define MIN_FREE       128    /*=8*16, minimal bytes of free SEL space */
#define REC_SIZE        16    /*SEL Record Size, see IPMI 1.5 Table 26-1 */
#define RECORD_BASE     2     //base value to the SEL record in IMB resp data
#define RID_OFFSET      0     //byte offset to the record id
#define RTYPE_OFFSET    2     //byte offset to the record type
#define RTS_OFFSET      3     //byte offset to the record timestamp
#define RGID_OFFSET     7     //byte offset to the record generator id
#define REREV_OFFSET    9     //byte offset to the record event message rev
#define RSTYPE_OFFSET   10    //byte offset to the record sensor type
#define RSN_OFFSET      11    //byte offset to the record sensor number
#define RET_OFFSET      12    //byte offset to the record event trigger
#define RDATA_OFFSET    13    //byte offset to the record event data

static char *progname  = "isel";
static char *progver   = "2.94";
#ifdef WIN32
#define IDXFILE   "sel.idx"
static char idxfile[80] = IDXFILE;
static char idxfile2[80] = "%ipmiutildir%\\sel.idx";
#else
static char idxfile[80]  = "/var/lib/ipmiutil/sel.idx";
static char idxfile2[80] = "/usr/share/ipmiutil/sel.idx"; /*old location*/
#endif
static char fdebug = 0;
static char fall = 1;
static char futc      = 0;
static char fwritesel = 0;
static char fshowraw = 0;
static char fdecoderaw = 0;
static char fdecodebin = 0;
static char fclearsel = 0;
static char faddsel = 0;
static char fonlyver = 0;
static char flastrecs = 0;
static char fremote = 0;
static char fsensdesc = 0;
static char fcanonical = 0;
static char fset_mc = 0;
static uchar min_sev = 0;  /*only show sev >= this value [0,1,2,3]*/
static char *addstr = NULL;
static char *addhex = NULL;
static uint savtime = 0;
static ushort savid = 0;
static int nlast = 20;
static ushort idinc = REC_SIZE;
static char *rawfile = NULL;
static int  vend_id, prod_id;
static uchar *sdrs = NULL;
static uchar  g_bus  = PUBLIC_BUS;
static uchar  g_sa   = BMC_SA;
static uchar  g_lun  = BMC_LUN;
static uchar  g_addrtype = ADDR_SMI;

/*------------------------------------------------------------------------
 * decode_sel_entry
 * Parse and decode the SEL record into readable format.
 * See ievents.c
 *------------------------------------------------------------------------*/
extern char *evt_hdr;
extern char *evt_hdr2;
extern int  decode_sel_entry( uchar *psel, char *outbuf, int sz);
extern int  decode_raw_sel( char *raw_file, int mode);
extern void set_sel_opts(int sensdsc, int canon, void *sdrs, char fdbg, char u);
extern int get_sdr_cache( uchar **sdrs);
extern void free_sdr_cache( uchar *sdrs);
extern uchar find_msg_sev(char *msgbuf);  /* subs.c*/
extern int OpenSyslog(char *tag);      /*see subs.c*/
extern void CloseSyslog(void);         /*see subs.c*/
extern void WriteSyslog(char *msgbuf); /*see subs.c*/
extern int write_syslog(char *msg);    /*see subs.c*/

/*F*
////////////////////////////////////////////////////////////////////////////////
//  GetSelEntry
////////////////////////////////////////////////////////////////////////////////
//  Name			:	GetSelEntry
//
//  Purpose			:	This routine gets the next SEL record
//
//  Parameters		:
//	pRecordID		:	input/output pointer to next Record ID
//	selRecord		:	output pointer to the sel record
//
//  Returns			:	0 if success
//					-1 if last record.
//					-2 if completion code error.
//					-3 if null buffer on input.
//					-4 if record id mismatch.
//
//	Notes			:	uses ipmi_cmd()
//
*F*/
int GetSelEntry(ushort *pRecordID, SEL_RECORD *selRecord)
{
	uchar responseData[MAX_BUFFER_SIZE];
	int responseLength = MAX_BUFFER_SIZE;
	int status;
	uchar inputData[6];
	uchar completionCode;
	char* cpRecordID;	 //for next record id
	ushort inRecordID;    //save the input record id

	inRecordID = *pRecordID;
	if (!selRecord)
	{
		if (fdebug)
		    SELprintf("GetSelEntry: error, output buffer is NULL\n");
		return -3;
	}

	//set the reservation id to zero
	inputData[0]            = 0;
	inputData[1]            = 0;

	//set the record id to get
	cpRecordID              = (char*) pRecordID;
	inputData[2]            = cpRecordID[0];
	inputData[3]            = cpRecordID[1];

	//set the offset to the record to value zero
	inputData[4]            = 0;

	//set the number of byte to read.  0xFF means read the entire record
	inputData[5]            = (char) 0xFF;

	status = ipmi_cmd(GET_SEL_ENTRY, inputData, 6, responseData,
			&responseLength, &completionCode, fdebug);

	if (status == ACCESS_OK) {
		if( completionCode ) {
			if (completionCode == 0xCB && inRecordID == 0)
			  SELprintf("Firmware Log (SEL) is empty\n");
			else
			  SELprintf("GetSelEntry[%x]: completion code=%x\n",
				inRecordID,completionCode); // responseData[0]);
		} else {
			//successful, done

			//save the next SEL record id
			cpRecordID[0] = responseData[0];
			cpRecordID[1] = responseData[1];

			//save the SEL record content
			//(note that selRecord structure must be pragma_pack'd)
			memcpy(selRecord,&responseData[RECORD_BASE],16);

			if (inRecordID == 0 || inRecordID == selRecord->record_id)
			{
				/* We return success if the input record is
				   begin-of-SEL (value 0), or
                                   input and output record id matches.
				*/
				return 0;
			}
			else
			{
				/* If last record, inRecordID will be -1 from
				   response data, so return -1 as normal EOF.
				   (fix to bug 279)
				*/
				if (inRecordID == 0xFFFF) return(-1);
				/* If not last record, this is an error. */
				if (fdebug)
				SELprintf("GetSelEntry: input id  %d != output id %d \n", inRecordID, selRecord->record_id);
				*pRecordID = inRecordID;  //restore the input record id
				return -4;
			}
		}
	}

	// we are here because after the retry, completionCode is not COMPLETION_CODE_OK

	if (fdebug)
		SELprintf("GetSelEntry: ipmi_cmd error %d completion code, code=%d\n", status,completionCode);
 	return -2;

}  /* end GetSelEntry() */

int AddSelEntry(uchar *selrec, int ilen)
{
	uchar rdata[MAX_BUFFER_SIZE];
	int rlen = MAX_BUFFER_SIZE;
	uchar idata[16];
	uchar ccode;
	int rv;

	/* Do not use AddSelEntry unless there is a legitimate
	   hardware-related event. */
	memset(idata,0,16);
	if (ilen > 16) ilen = 16;
	memcpy(idata,selrec,ilen);
	rv = ipmi_cmdraw(0x44, NETFN_STOR, g_sa, g_bus, g_lun,
			idata, 16, rdata, &rlen, &ccode, fdebug);
 	return (rv);
}

int get_sel_time_utc_offset(short *offset)
{
	uchar rdata[MAX_BUFFER_SIZE];
	int rlen = MAX_BUFFER_SIZE;
	uchar idata[16];
	uchar ccode;
	int rv;

	if (offset == NULL) return(-1);
	*offset = 0;
	rv = ipmi_cmdraw(0x5C, NETFN_STOR, g_sa, g_bus, g_lun,
			idata, 0, rdata, &rlen, &ccode, fdebug);
        if (rv == 0) rv = ccode;
        if (rv == 0) *offset = rdata[0] + (rdata[1] << 8);
 	return (rv);
}

void StartWriting(uint *plasttime, ushort *plastid)
{
	FILE *fd;
	uint lasttime;
	uint lastid;
	int ret = -1;

	lasttime = 0;
	lastid = 0;
	// Open the index file
	fd = fopen(idxfile,"r");
	if (fd == NULL) fd = fopen(idxfile2,"r");
	if (fd != NULL) {
		// Read the file, get savtime & savid
		ret = fscanf(fd,"%x %x",&lasttime,&lastid);
		fclose(fd);
	}
	else printf("StartWriting: cannot open %s\n",idxfile);
	if (fdebug) printf("StartWriting: idx fd=%p, savtime=%x, savid=%x\n",
				fd,lasttime,(ushort)lastid);
	*plasttime = lasttime;
	*plastid = (ushort)lastid;

	ret = OpenSyslog("SEL");
	if (fdebug) printf("StartWriting: ret = %d\n",ret);
	return;
}

void StopWriting(uint lasttime, ushort lastid)
{
	FILE *fd;
	// Rewrite the saved time & record id
	fd = fopen(idxfile,"w");
	if (fd != NULL) {
		fprintf(fd,"%x %x\n",lasttime,lastid);
		fclose(fd);
		}
	else printf("StopWriting: cannot open %s\n",idxfile);
	CloseSyslog();
	return;
}

int ClearSEL(void)
{
	uchar responseData[MAX_BUFFER_SIZE];
	int responseLength = MAX_BUFFER_SIZE;
	int status;
	uchar inputData[6];
	uchar completionCode;
	ushort cmd;

	cmd = RESERVE_SEL;  /*0x0A42*/
	status = ipmi_cmd(cmd, inputData, 0, responseData,
			&responseLength, &completionCode, fdebug);

	if (status == ACCESS_OK && completionCode == 0) {
	    cmd = CLEAR_SEL;  /*0x0A47*/
	    inputData[0] = responseData[0];  /*Reservation ID [0]*/
	    inputData[1] = responseData[1];  /*Reservation ID [1]*/
	    inputData[2] = 'C';
	    inputData[3] = 'L';
	    inputData[4] = 'R';
	    inputData[5] = 0xAA;   /* initiate erase */
	    status = ipmi_cmd(cmd, inputData, 6, responseData,
	  		      &responseLength, &completionCode, fdebug);
	    /* The reservation is cancelled by the CLEAR_SEL cmd */
	    }
	if (status == ACCESS_OK) {
		if( completionCode ) {
		    SELprintf("ClearSEL: cmd = %x, completion code=%x\n",
			      cmd,completionCode);
		    status = completionCode;
		} else {
		    /* Successful, done. */
		    SELprintf("ClearSEL: Log Cleared successfully\n");
		}
	} else {
	    SELprintf("ClearSEL: cmd = %x, error status = %d\n",
		      cmd,status);
	}
	if (fwritesel) {  /* this won't always be enough, but try */
	   StartWriting(&savtime,&savid);
	   savid = 0;
	   StopWriting(savtime,savid);
	}
	return(status);
}  /* ClearSEL()*/

void ReadSEL(uchar mytype, char fwriteit)
{
	ushort RecordID = 0;  /* 0 = first record, 0xFFFF = end */
	SEL_RECORD selRecord;
	SEL_RECORD *pSelRecord = &selRecord;
	char output[160];
	int rc = 0;
        int ilast = 0;
        short recid0;
	uchar *bsel;
	uchar sev;
	char fskipit = 0;

	if (fwriteit) {
		StartWriting(&savtime,&savid);
		RecordID = savid;
	}
	memset(pSelRecord, 0, sizeof(SEL_RECORD));
        if (flastrecs) {
            /* read the first two records to get the record id increment */
            RecordID = 0;
	    rc = GetSelEntry( &RecordID, pSelRecord);
	    recid0 = pSelRecord->record_id;
	    rc = GetSelEntry( &RecordID, pSelRecord);
	    if (rc == 0) idinc = pSelRecord->record_id - recid0;
	    else { idinc = recid0; rc = 0; }
            RecordID = 0xFFFF;  /* -1=0xFFFF; * get last record */
            if (fdebug) printf("recid inc = 0x%02x (%x - %x)\n",idinc,
				pSelRecord->record_id,recid0);
        }
        set_sel_opts(fsensdesc, fcanonical, sdrs, fdebug,futc);
	if (futc) {  /*Try to get the UTC offset*/
	   short utc_off;
	   printf("Showing SEL Time as UTC\n");
	   rc = get_sel_time_utc_offset(&utc_off);
	   if (rc == 0) {
	      printf("SEL Time UTC Offset = %d\n",utc_off);
	   } else rc = 0; /*may fail if not supported, but ok*/
	}
	/* show header for the SEL records */
	if (fcanonical)
             printf("%s",evt_hdr2);  /*RecId | Date/Time */
	else printf("%s",evt_hdr);   /*RecId Date/Time_______ */
	while( rc == 0 ) {
		rc = GetSelEntry( &RecordID, pSelRecord);
		if (fwriteit && (rc != 0) && (RecordID == savid)) {
		    /* If here, log was probably cleared, so try
		     * again from the log start. */
		    RecordID = 0;
		    rc = GetSelEntry( &RecordID, pSelRecord);
		}
                if (fdebug) printf("rc = %d, recid = %04x, next = %04x\n",
                                   rc, pSelRecord->record_id, RecordID);
                if (flastrecs && (ilast == 0) && (rc == -1)) rc = 0;
		if (rc != 0) { /* EOF or error */ break; }

		if (fshowraw) {
		   bsel = (uchar *)&selRecord;
		   sprintf(output,"%02x %02x %02x %02x %02x %02x %02x %02x "
		                "%02x %02x %02x %02x %02x %02x %02x %02x\n",
				bsel[0], bsel[1], bsel[2], bsel[3],
				bsel[4], bsel[5], bsel[6], bsel[7],
				bsel[8], bsel[9], bsel[10], bsel[11],
				bsel[12], bsel[13], bsel[14], bsel[15]);
		   printf("%s", output);
		} else {
		 if (mytype == 0xff || pSelRecord->sensor_type == mytype) {
		   /* show all records, or type matches */
		   decode_sel_entry((uchar *)pSelRecord,output, sizeof(output));
		   fskipit = 0;
		   if (min_sev > 0) {
		      sev = find_msg_sev(output);
		      if (fdebug) printf("min_sev=%d, sev=%d\n",min_sev,sev);
		      if (sev < min_sev) fskipit = 1;
		   }
		   if (!fskipit) printf("%s", output);
		 } else if ((mytype == ETYPE_CRITSTOP) &&
                           (pSelRecord->record_type >= RTYPE_OEM2)) {
                   /* if showing panics only, also show its oem records */
		   decode_sel_entry((uchar *)pSelRecord,output,sizeof(output));
		   printf("%s", output);
		 } else {
		   if (fdebug) printf("decoding error, mytype = %d\n",mytype);
		   output[0] = 0;
		 }
		}

		if (fwriteit) {
		   /* Only write newer records  to syslog */
		   if (pSelRecord->record_type == 0x02) {
			if ((pSelRecord->timestamp > savtime) ||
			    (pSelRecord->record_id > savid)) {
			   WriteSyslog(output);
			   savid = pSelRecord->record_id;
			   savtime = pSelRecord->timestamp;
			}
		   } else {   /* no timestamp */
			if (pSelRecord->record_id > savid) {
			   WriteSyslog(output);
			   savid = pSelRecord->record_id;
			}
		   }
		}  /*endif writeit*/
		if( pSelRecord->record_id == 0xFFFF )
			break;
		if( RecordID == pSelRecord->record_id )
			break;
                if (flastrecs) {
                    ++ilast;
		    if (fdebug) printf("ilast = %d, next = %x, id = %x\n",
					ilast,RecordID,pSelRecord->record_id);
                    if (ilast >= nlast) break;
                    RecordID = pSelRecord->record_id - idinc;
                    if (RecordID > pSelRecord->record_id) break;
                    if (RecordID == 0) break;
                }
		memset(pSelRecord, 0, sizeof(SEL_RECORD));
	}  /*endwhile*/
	if (fwriteit) StopWriting(savtime,savid);
}  /* end ReadSEL()*/

static uint vfree = 0;
static uint vused = 0;
static uint vtotal = 0;
static uint vsize = REC_SIZE;

static int ReadSELinfo()
{
	uchar responseData[MAX_BUFFER_SIZE];
	int responseLength = MAX_BUFFER_SIZE;
	int status;
	uchar completionCode;
	uchar inputData[6];
	uchar b;
	char *strb;

	status = ipmi_cmd(GET_SEL_INFO, inputData, 0, responseData,
			&responseLength, &completionCode, fdebug);
	if (fdebug) printf("GetSelInfo status = %x, cc = %x\n",
			status,completionCode);

	if ((status == ACCESS_OK) && (completionCode == 0)) {
		vfree = responseData[3] + (responseData[4] << 8); // in Bytes
		vused = responseData[1] + (responseData[2] << 8); // in Entries/Allocation Units
		vtotal = vused + (vfree/vsize); // vsize from AllocationInfo
		b = responseData[13];
		if (b & 0x80) strb = " overflow"; /*SEL overflow occurred*/
		else strb = "";
                if (b & 0x1) {         // Get SEL Allocation Info supported
                   status = ipmi_cmd(GET_SEL_ALLOCATION_INFO, inputData, 0,
					responseData, &responseLength,
					&completionCode, fdebug);
		   if (fdebug) printf("GetSelInfo status = %x, cc = %x\n",
					status,completionCode);
		   if ((status == ACCESS_OK) && (completionCode == 0)) {
                      vsize  = responseData[2] + (responseData[3] << 8);
		      if (vsize == 0) vsize = REC_SIZE;
                      vtotal = responseData[0] + (responseData[1] << 8);
                   }
                }

		if (fcanonical)
		   SELprintf("SEL %s Size = %d records (Used=%d, Free=%d)\n",
		          strb, vtotal, vused, vfree/vsize );
		else
		   SELprintf("SEL Ver %x Support %02x%s, Size = %d records (Used=%d, Free=%d)\n",
		          responseData[0],
		          b, strb,
			  vtotal,
			  vused,
			  vfree/vsize );
		//successful, done
		return(0);
	} else {
		vfree = MIN_FREE * 2; /*sane values to avoid SEL full warning*/
		vused = 0;
		vtotal = vused + (vfree/vsize);
		return(1);
	}

}  /*end ReadSELinfo()*/

#ifdef ALONE
#ifdef WIN32
int __cdecl
#else
int
#endif
main(int  argc, char **argv)
#else
/* METACOMMAND */
int i_sel(int argc, char **argv)
#endif
{
   int ret = -1;
   char DevRecord[16];
   int c;
   char *s1;

   printf("%s: version %s\n",progname,progver);
   while ((c = getopt(argc,argv,"a:b:cdef:h:l:m:nprs:uwvx:T:V:J:EYF:P:N:U:R:Z:?")) != EOF)
      switch(c) {
          case 'a': faddsel = 1; /*undocumented option, to prevent misuse*/
		addstr = optarg; /*text string, max 13 bytes*/
		break;
          case 'h': faddsel = 1; /*undocumented option, to prevent misuse*/
		addhex = optarg; /*string of 16 hex characters, no spaces*/
		break;
          case 'b': fdecodebin = 1;
		rawfile = optarg;
		break;
          case 'd': fclearsel = 1;   break;  /*delete/clear SEL*/
          case 'e': fsensdesc = 1;   break; /*extended sensor descriptions*/
          case 'f': fdecoderaw = 1;
		rawfile = optarg;
		break;
          case 'l': flastrecs = 1;
                nlast = atoi(optarg);
                break;
          case 'm': /* specific MC, 3-byte address, e.g. "409600" */
                    g_bus = htoi(&optarg[0]);  /*bus/channel*/
                    g_sa  = htoi(&optarg[2]);  /*device slave address*/
                    g_lun = htoi(&optarg[4]);  /*LUN*/
		    if (optarg[6] == 's') {
		             g_addrtype = ADDR_SMI;  s1 = "SMI";
		    } else { g_addrtype = ADDR_IPMB; s1 = "IPMB"; }
		    fset_mc = 1;
		    printf("set MC at %s bus=%x sa=%x lun=%x\n",
		            s1,g_bus,g_sa,g_lun);
                    break;
          case 'c':
          case 'n': fcanonical = 1;         /*parse easier, canonical*/
                    fsensdesc = 1;          /*extended sensor descriptions*/
		    /* Note that this option does not show event data bytes */
		    break;
          case 'p': fall = 0;        break; /*crit stop (panic) only*/
          case 'r': fshowraw = 1;    break;
          case 's': min_sev = atob(optarg); break; /*show sev >= value*/
          case 'u': futc = 1;    break;
          case 'v': fonlyver = 1;    break;
          case 'w': fwritesel = 1;   break;
          case 'x': fdebug = 1;      break;
          case 'N':    /* nodename */
          case 'U':    /* remote username */
          case 'P':    /* remote password */
          case 'R':    /* remote password */
          case 'E':    /* get password from IPMI_PASSWORD environment var */
          case 'F':    /* force driver type */
          case 'T':    /* auth type */
          case 'J':    /* cipher suite */
          case 'V':    /* priv level */
          case 'Y':    /* prompt for remote password */
          case 'Z':    /* set local MC address */
                parse_lan_options(c,optarg,fdebug);
                break;
          default:
                printf("Usage: %s [-bcdefmnprsuvwx] [-l 5] [-NUPREFTVY]\n",
                       progname);
		printf("   -b  interpret Binary file with raw SEL data\n");
		printf("   -c  Show canonical output with delimiters\n");
		printf("   -d  Delete, Clears all SEL records\n");
		printf("   -e  shows Extended sensor description if run locally\n");
		printf("   -f  interpret File with ascii hex SEL data\n");
		printf("   -l5 Show last 5 SEL records (reverse order)\n");
		printf("   -r  Show uninterpreted raw SEL records in ascii hex\n");
		printf("   -n  Show nominal/canonical output (same as -c)\n");
		printf("   -p  Show only Panic/Critical Stop records\n");
		printf("   -s1 Show only Severity >= value (0,1,2,3)\n");
                printf("   -u  use raw UTC time\n");
		printf("   -v  Only show version information\n");
		printf("   -w  Writes new SEL records to syslog\n");
		printf("   -x  Display extra debug messages\n");
		print_lan_opt_usage();
		ret = ERR_USAGE;
		goto do_exit;
      }
   if (fwritesel && flastrecs) {
       printf("Error: Options -l and -w are incompatible\n");
       ret = ERR_BAD_PARAM;
       goto do_exit;
   }

   /* Handle simple decoding options -f, -b */
   if (fdecoderaw) {  /* -f */
	ret = decode_raw_sel(rawfile,1);
        goto do_exit;
   } else if (fdecodebin) {  /* -b */
	ret = decode_raw_sel(rawfile,2);
	goto do_exit;
   }

   // if (fwrite) fall = 1;   // would we ever set fwrite without fall??
#ifdef WIN32
   fremote = is_remote();
   if (fwritesel) {  /*resolve path of idxfile*/
      char *ipath;
      ipath = getenv("ipmiutildir");  /*ipmiutil directory path*/
      if (ipath != NULL) {
	  if (strlen(ipath)+8 < sizeof(idxfile)) {
	     sprintf(idxfile,"%s\\%s",ipath,"\\",IDXFILE);
	  }
      }
   }
#elif defined(DOS)
   fremote = 0;
#else
   /* Linux, BSD, Solaris */
   fremote = is_remote();
   if (fremote == 0) {
	//uchar guid[16];
	//char gstr[36];
        /* only run this as superuser */
        ret = geteuid();
        if (ret > 1) {
            printf("Not superuser (%d)\n", ret);
            ret = ERR_NOT_ALLOWED;
	    goto do_exit;
        }
   }
#endif
   if (fremote) {  /*remote, ipmi lan, any OS*/
        char *node;
        node = get_nodename();
        strcat(idxfile,"-");
        strcat(idxfile,node);
        strcat(idxfile2,"-");
        strcat(idxfile2,node);
   }
#ifdef REMOVABLE
   else {
	// if removable media, may need to add uniqueness to local file.
	ret = get_SystemGuid(guid);
	if (ret == 0) {
	   sprintf(gstr,"%02X%02X%02X%02X%02X%02X%02X%02X",
		   guid[8], guid[9], guid[10], guid[11],
		   guid[12], guid[13], guid[14], guid[15]);
           strcat(idxfile,"-");
           strcat(idxfile,gstr);
           strcat(idxfile2,"-");
           strcat(idxfile2,gstr);
	}
   }
#endif
   if (fremote) {
      if (faddsel || fclearsel)
         parse_lan_options('V',"4",0); /*admin priv to clear*/
   }

   if (faddsel) {  /* -a, Add a custom SEL record */
	/* use this sparingly, only for hardware-related events. */
	char buf[16];
	int i, len = 0;
	buf[0] = 0;
	buf[1] = 0;
	if (addstr != NULL) {  /*ASCII text string*/
	   buf[2] = 0xf1;  /*use SEL type OEM 0xF1*/
	   len = strlen_(addstr);
	   if (len > 13) len = 13;
	   if (len <= 0) ret = LAN_ERR_TOO_SHORT;
	   else memcpy(&buf[3],addstr,len);
	   len += 3;
	}
	if (addhex != NULL) {  /*string of hex characters, no spaces*/
	   len = strlen_(addhex);
	   if (len < 32) ret = LAN_ERR_TOO_SHORT;
	   else {
	      for (i=2; i<16; i++)
	         buf[i] = htoi(&addhex[i*2]);
	   }
	   len = 16;
	}
        if (fdebug) {
           printf("Ready to AddSelEntry: ");
           for (i=0; i<16; i++) printf("%02x ",buf[i]);
           printf("\n");
        }
	if (ret == 0)
	   ret = AddSelEntry(buf, len);
	printf("AddSelEntry ret = %d\n",ret);
        goto do_exit;
   }

   ret = ipmi_getdeviceid( DevRecord, sizeof(DevRecord),fdebug);
   if (ret == 0) {
      uchar ipmi_maj, ipmi_min;
      ipmi_maj = DevRecord[4] & 0x0f;
      ipmi_min = DevRecord[4] >> 4;
      show_devid( DevRecord[2],  DevRecord[3], ipmi_maj, ipmi_min);
      prod_id = DevRecord[9] + (DevRecord[10] << 8);
      vend_id = DevRecord[6] + (DevRecord[7] << 8) + (DevRecord[8] << 16);
      if (vend_id == VENDOR_INTEL) {
	 if (prod_id == 0x003E)   /*Urbanna NSN2U or CG2100*/
	           set_max_kcs_loops(URNLOOPS); /*longer KCS timeout*/
      }
   } else {
      goto do_exit;
   }

   ret = ReadSELinfo();
   if (ret == 0 && !fonlyver) {
      if (fclearsel) {
	 ret = ClearSEL();
      } else {
         if (fsensdesc) {
	     if (fdebug) printf("%s: fetching SDRs ...\n",progname);
             ret = get_sdr_cache(&sdrs);
	     if (fdebug) printf("%s: get_sdr_cache ret = %d\n",progname,ret);
	     ret = 0; /*if error, keep going anyway*/
	 }
	 if (fdebug) printf("%s: starting ReadSEL ...\n",progname);
         if (fall) ReadSEL(0xff,fwritesel); /* show all SEL records */
         else ReadSEL(ETYPE_CRITSTOP,fwritesel);  /* only show OS Crit Stops*/
	 /* PEF alerts and other log messages fail if low free space,
	    so show a warning. */
	 if (vfree < MIN_FREE) {
             printf("WARNING: free space is very low (=%d), need to clear with -c\n",
		    vfree);
	 } else if ((vfree/vsize) < ((vtotal * 20)/100)) {
             printf("WARNING: free space is low (=%d), need to clear with -c\n",
		    vfree);
	 }
      }
   }
do_exit:
   free_sdr_cache(sdrs);
   ipmi_close_();
   // show_outcome(progname,ret);
   return(ret);
}

/* end isel.c */


text:
/**
 * SQLite
 */

DROP TABLE IF EXISTS "tree";

CREATE TABLE "tree" (
  "id" INTEGER NOT NULL PRIMARY KEY,
  "lft" INTEGER NOT NULL,
  "rgt" INTEGER NOT NULL,
  "depth" INTEGER NOT NULL,
  "name" TEXT NOT NULL
);

DROP TABLE IF EXISTS "multiple_roots_tree";

CREATE TABLE "multiple_roots_tree" (
  "id" INTEGER NOT NULL PRIMARY KEY,
  "tree" INTEGER,
  "lft" INTEGER NOT NULL,
  "rgt" INTEGER NOT NULL,
  "depth" INTEGER NOT NULL,
  "name" TEXT NOT NULL
);


text:
{% extends "admin/change_form.html" %}
{% load i18n %}
{% load url from future %}

{% block object-tools %}
    {% if change %}{% if not is_popup %}

{% trans "History" %}

            {% if original.switch %}

{% trans "Switch" %}

            {% endif %}

{% trans "Results" %}

            {% if has_absolute_url %}

                    {% trans "View on site" %}

            {% endif %}

    {% endif %}{% endif %}
{% endblock %}


text:
<!DOCTYPE html>

    <title></title>

Doge Social Network

Home

Profile

Friends

Welcome to the Doge Social Network

Here you can find friends or talk strangers

The Doge Social Network does not take any responsibility for the information found


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/services/device_sync/remote_device_loader.h"

#include <algorithm>
#include <utility>

#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/components/multidevice/remote_device.h"
#include "chromeos/components/multidevice/remote_device_ref.h"
#include "chromeos/components/multidevice/secure_message_delegate.h"
#include "chromeos/components/multidevice/software_feature.h"
#include "chromeos/services/device_sync/proto/enum_util.h"

namespace chromeos {

namespace device_sync {

namespace {

std::map<multidevice::SoftwareFeature, multidevice::SoftwareFeatureState>
GetSoftwareFeatureToStateMap(const cryptauth::ExternalDeviceInfo& device) {
  std::map<multidevice::SoftwareFeature, multidevice::SoftwareFeatureState>
      software_feature_to_state_map;

  for (int i = 0; i < device.supported_software_features_size(); ++i) {
    cryptauth::SoftwareFeature feature =
        SoftwareFeatureStringToEnum(device.supported_software_features(i));
    if (feature == cryptauth::UNKNOWN_FEATURE)
      continue;

    software_feature_to_state_map[multidevice::FromCryptAuthFeature(feature)] =
        multidevice::SoftwareFeatureState::kSupported;
  }

  for (int i = 0; i < device.enabled_software_features_size(); ++i) {
    cryptauth::SoftwareFeature feature =
        SoftwareFeatureStringToEnum(device.enabled_software_features(i));
    if (feature == cryptauth::UNKNOWN_FEATURE)
      continue;

    software_feature_to_state_map[multidevice::FromCryptAuthFeature(feature)] =
        multidevice::SoftwareFeatureState::kEnabled;
  }

  return software_feature_to_state_map;
}

}  // namespace

// static
RemoteDeviceLoader::Factory* RemoteDeviceLoader::Factory::factory_instance_ =
    nullptr;

// static
std::unique_ptr<RemoteDeviceLoader> RemoteDeviceLoader::Factory::Create(
    const std::vector<cryptauth::ExternalDeviceInfo>& device_info_list,
    const std::string& user_email,
    const std::string& user_private_key,
    std::unique_ptr<multidevice::SecureMessageDelegate>
        secure_message_delegate) {
  if (factory_instance_) {
    return factory_instance_->CreateInstance(
        device_info_list, user_email, user_private_key,
        std::move(secure_message_delegate));
  }

  return base::WrapUnique(
      new RemoteDeviceLoader(device_info_list, user_email, user_private_key,
                             std::move(secure_message_delegate)));
}

// static
void RemoteDeviceLoader::Factory::SetFactoryForTesting(Factory* factory) {
  factory_instance_ = factory;
}

RemoteDeviceLoader::RemoteDeviceLoader(
    const std::vector<cryptauth::ExternalDeviceInfo>& device_info_list,
    const std::string& user_email,
    const std::string& user_private_key,
    std::unique_ptr<multidevice::SecureMessageDelegate> secure_message_delegate)
    : remaining_devices_(device_info_list),
      user_email_(user_email),
      user_private_key_(user_private_key),
      secure_message_delegate_(std::move(secure_message_delegate)) {}

RemoteDeviceLoader::~RemoteDeviceLoader() {}

void RemoteDeviceLoader::Load(RemoteDeviceCallback callback) {
  DCHECK(callback_.is_null());
  callback_ = std::move(callback);
  PA_LOG(VERBOSE) << "Loading " << remaining_devices_.size()
                  << " remote devices";

  if (remaining_devices_.empty()) {
    std::move(callback_).Run(remote_devices_);
    return;
  }

  std::vector<cryptauth::ExternalDeviceInfo> all_devices_to_convert =
      remaining_devices_;

  for (const auto& device : all_devices_to_convert) {
    secure_message_delegate_->DeriveKey(
        user_private_key_, device.public_key(),
        base::BindOnce(&RemoteDeviceLoader::OnPSKDerived,
                       weak_ptr_factory_.GetWeakPtr(), device));
  }
}

void RemoteDeviceLoader::OnPSKDerived(
    const cryptauth::ExternalDeviceInfo& device,
    const std::string& psk) {
  std::string public_key = device.public_key();
  auto iterator =
      std::find_if(remaining_devices_.begin(), remaining_devices_.end(),
                   [&public_key](const cryptauth::ExternalDeviceInfo& device) {
                     return device.public_key() == public_key;
                   });

  DCHECK(iterator != remaining_devices_.end());
  remaining_devices_.erase(iterator);

  std::vector<multidevice::BeaconSeed> multidevice_beacon_seeds;
  for (const auto& cryptauth_beacon_seed : device.beacon_seeds()) {
    multidevice_beacon_seeds.push_back(
        multidevice::FromCryptAuthSeed(cryptauth_beacon_seed));
  }

  // Because RemoteDeviceLoader does not handle devices using v2 DeviceSync, no
  // Instance ID is present.
  multidevice::RemoteDevice remote_device(
      user_email_, std::string() /* instance_id */,
      device.friendly_device_name(), device.no_pii_device_name(),
      device.public_key(), psk, device.last_update_time_millis(),
      GetSoftwareFeatureToStateMap(device), multidevice_beacon_seeds,
      device.bluetooth_address());

  remote_devices_.push_back(remote_device);

  if (remaining_devices_.empty()) {
    PA_LOG(VERBOSE) << "Derived keys for " << remote_devices_.size()
                    << " devices.";
    std::move(callback_).Run(remote_devices_);
  }
}

}  // namespace device_sync

}  // namespace chromeos


text:
package io.skysail.server.model.test;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

import org.junit.*;
import org.mockito.Mockito;

import io.skysail.api.responses.*;
import io.skysail.server.model.ResourceModel;

@Ignore
public class ResourceModelTest extends ModelTests {

    @Before
    public void setUp() throws Exception {
        super.setUp();
        testEntity = new TestEntity();
        testEntity.setFieldWithoutAnnotation("fwa");
        testEntity.setStringField("sf");
        testEntity.setStringField_Textarea("sf_t");
    }

    @Test
    public void finds_formField_from_listResource() {
//        ListServerResponse<TestEntity> listResponse = new ListServerResponse<>(Arrays.asList(testEntity));
//        ResourceModel<TestListResource, List<TestEntity>> resourceModel = new ResourceModel<>(testListResource, listResponse);
//        assertThat(resourceModel.getTitle(), is(equalTo("Skysail")));
//        assertThat(resourceModel.getParameterizedType(), is(equalTo(TestEntity.class)));
//        assertThat(resourceModel.getFormfields().size(), is(2));
//        assertThat(resourceModel.getFormfields().get(0).getName(), is(equalTo("stringField")));
    }

    @Test
    public void constructor_works_for_putResource() {
        Mockito.when(request.toString()).thenReturn("/parent:22/");

        FormResponse<TestEntity> formResponse = new FormResponse<>(null, testEntity, ".");
        ResourceModel<TestPutResource, TestEntity> resourceModel = new ResourceModel<>(testPutResource, formResponse);
        assertThat(resourceModel.getParameterizedType(),is(equalTo(TestEntity.class)));
        //assertThat(resourceModel.getFields().keySet(), hasItem("stringField"));
    }

    @Test
    public void constructor_works_for_postResource() {
        FormResponse<TestEntity> formResponse = new FormResponse<>(null, testEntity, ".");
        ResourceModel<TestPostResource, TestEntity> resourceModel = new ResourceModel<>(testPostResource, formResponse);
        assertThat(resourceModel.getParameterizedType(),is(equalTo(TestEntity.class)));
        assertThat(resourceModel.getFields().keySet(), hasItem("stringField"));
    }

    @Test
    public void constructor_works_for_entityResource() {
        EntityServerResponse<TestEntity> entityResponse = new EntityServerResponse<>(null, testEntity);
        ResourceModel<TestEntityResource, TestEntity> resourceModel = new ResourceModel<>(testEntityResource, entityResponse);
        assertThat(resourceModel.getParameterizedType(),is(equalTo(TestEntity.class)));
        assertThat(resourceModel.getFields().keySet(), hasItem("stringField"));
    }

//    @Test
//    public void constructor_works_for_listResource() {
//        ResourceModel<TestListResource, List<TestEntity>> resourceModel = new ResourceModel<>(testListResource, Arrays.asList(testEntity));
//        assertThat(resourceModel.getParameterizedType(),is(equalTo(TestEntity.class)));
//        assertThat(resourceModel.getFormfields().size(), is(2));
//        assertThat(resourceModel.getModelType(),is(equalTo(ModelType.LIST)));
//    }
//
//    @SuppressWarnings("unchecked")
//    @Test
//    public void converter_works_for_listResource() {
//        ResourceModel<TestListResource, List<TestEntity>> resourceModel = new ResourceModel<>(testListResource, Arrays.asList(testEntity));
//        //resourceModel.convert();
//        assertThat(resourceModel.getConvertedSource(), is(instanceOf(List.class)));
//        List<?> list = (List<?>)resourceModel.getConvertedSource();
//        assertThat(list.size(), is(1));
//        assertThat(list.get(0), is(instanceOf(Map.class)));
//        Map<String,Object> map = (Map<String, Object>) list.get(0);
//        assertThat(map.get("stringField"), is(equalTo("sf")));
//    }
}


text:
export * from './module';
export * from './checkbox';


text:
<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\base\Security;
use yii\web\IdentityInterface;
/**
 * This is the model class for table "tbl_user".
 *
 * @property string $userid
 * @property string $username
 * @property string $password
 * @property string $password2
 * @property string $dateCreate
 * @property Profile $profile
 */
class User extends ActiveRecord  implements IdentityInterface
{
    public $password2;
    public $crib;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required','on'=>'create'],
            ['username','email'],
            ['username','unique'],
            [['username', 'password'], 'string', 'max' => 100],
            [['username','password','password2'],'required','on'=>'client.create'],
            ['password2','compare','compareAttribute'=>'password','on'=>'client.create'],
            [['role'],'default','value'=>'client'],
            [['role','password','password2','dateCreate'],'safe'],
            ['crib','safe','on'=>'user.crib'],
            ['crib','checkBalance','on'=>'user.crib'],
        ];
    }

    public function checkBalance($attr)
    {
        $value = $this->{$attr};
        $balance = $this->profile->balance;
        if($value>$balance)
            $this->addError ($attr,'Вы пытаетесь списать сумму больше вашего баланса!');
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'userid' => 'Userid',
            'username' => 'Email',
            'password' => 'Пароль',
            'password2' => 'Повторить пароль',
            'role' => 'Полномочия',
            'dateCreate' => 'Дата регистрации',
            'crib' => 'Сумма вывода',
        ];
    }
    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
    /* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /* removed
        public static function findIdentityByAccessToken($token)
        {
            throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
        }
    */
    /**
     * Finds user by username
     *
     * @param  string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int)end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        $security = new Security();
        return $security->validatePassword($password,$this->password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $security = new Security();
        $this->password = $security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $security = new Security();
        $this->auth_key = $security->generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /** EXTENSION MOVIE **/

    public static function getRolesDropdown()
    {
        return ArrayHelper::map(Yii::$app->authManager->getRoles(),'name','description');
    }

    public function beforeSave($insert=true)
    {
        if(!$this->isNewRecord && $this->role)
        {
            Yii::$app->authManager->revokeAll($this->id);
        }

        if(!empty($this->password))
            $this->setPassword($this->password);
        else
            $this->password = $this->oldAttributes['password'];

        $this->generateAuthKey();
        return parent::beforeSave($insert);
    }

    public function afterSave($insert=true,$changedAttributes)
    {
        if($this->role)
        {
            $auth = Yii::$app->authManager;
            $role = $auth->getRole($this->role);
            $auth->assign($role,$this->id);
        }

        return parent::afterSave($insert,$changedAttributes);
    }

    public static function getDropDown()
    {
        $data = self::find()->orderBy('username')->all();
        return ArrayHelper::map($data,'id','username');
    }

    public function getProfile()
    {
        return $this->hasOne(Profile::className(),['userId'=>'id']);
    }

    protected $_role;

    public function getRole()
    {
        if(!empty($this->_role))
            return $this->_role;

        $roles = Yii::$app->authManager->getRolesByUser($this->id);
        if(empty($roles))
            return '';

        $roles = array_keys($roles);
        return array_shift($roles);
    }

    public function setRole($value)
    {
        $this->_role = $value;
    }

    public function crib()
    {
        $balanceModel = new BalanceHistory;
        $balanceModel->id = md5($this->id.''.time());
        $balanceModel->type = BalanceHistory::TYPE_REMOVE;
        $balanceModel->userId = $this->id;
        $balanceModel->sum = $this->crib;
        $balanceModel->date = date(DATE_FORMAT_DB);
        $balanceModel->save();

        $balance = $balanceModel->getBalanceById($this->id);
        $this->profile->updateBalance();
    }

}


text:
package var.rmi.chat;

public class Conf {
	public static final String CHATSERVICE = "//localhost:1099/chat";
}


text:
package org.onosproject.odtn.utils.openconfig;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.yang.model.ResourceId;
import org.onosproject.yang.runtime.AnnotatedNodeInfo;

import org.onosproject.yang.gen.v1.openconfigterminaldevice.rev20170708.openconfigterminaldevice.terminallogicalchanassignmenttop.logicalchannelassignments.assignment.DefaultConfig;
import org.onosproject.yang.gen.v1.openconfigterminaldevice.rev20170708.openconfigterminaldevice.terminallogicalchanassignmenttop.logicalchannelassignments.DefaultAssignment;

import static org.junit.Assert.assertEquals;

/**
 * UnitTest class for OpenConfigAssignmentHandler.
 */
public class OpenConfigAssignmentHandlerTest {
    // parent Handler
    OpenConfigLogicalChannelAssignmentsHandler parent;

    // expected ResourceId
    ResourceId rid;

    /**
     * Set up method for UnitTest.
     */
    @Before
    public void setUp() {
        // parent Handler set up
        // create <terminal-device xmlns="http://openconfig.net/yang/terminal-device">
        //        </terminal-device>
        OpenConfigTerminalDeviceHandler terminalDevice = new OpenConfigTerminalDeviceHandler();

        // add <logical-channels></logical-channels>
        OpenConfigLogicalChannelsHandler logicalChannels =
            new OpenConfigLogicalChannelsHandler(terminalDevice);

        // add <channel><index>1</index></channel>
        OpenConfigChannelHandler channel =
            new OpenConfigChannelHandler(1, logicalChannels);

        // add <logical-channel-assignments></logical-channel-assignments>
        parent = new OpenConfigLogicalChannelAssignmentsHandler(channel);

        // expected ResourceId set up
        rid = ResourceId.builder()
        .addBranchPointSchema("terminal-device", "http://openconfig.net/yang/terminal-device")
        .addBranchPointSchema("logical-channels", "http://openconfig.net/yang/terminal-device")
        .addBranchPointSchema("channel", "http://openconfig.net/yang/terminal-device")
        .addKeyLeaf("index", "http://openconfig.net/yang/terminal-device", 1)
        .addBranchPointSchema("logical-channel-assignments", "http://openconfig.net/yang/terminal-device")
        .addBranchPointSchema("assignment", "http://openconfig.net/yang/terminal-device")
        .addKeyLeaf("index", "http://openconfig.net/yang/terminal-device", 2)
        .build();
    }

    /**
     * UnitTest method for getModelObject.
     */
    @Test
    public void testGetModelObject() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        // expected ModelObject
        DefaultAssignment modelObject = new DefaultAssignment();
        modelObject.index(2);

        assertEquals("[NG]getModelObject:Return is not an expected ModelObject.\n",
                     modelObject, assignment.getModelObject());
    }

    /**
     * UnitTest method for setResourceId.
     */
    @Test
    public void testSetResourceId() {
        // call setResourceId
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        // get resourceId
        ResourceId resourceId = null;
        try {
            Field field = OpenConfigObjectHandler.class.getDeclaredField("resourceId");
            field.setAccessible(true);
            resourceId = (ResourceId) field.get(assignment);
        } catch (NoSuchFieldException e) {
            Assert.fail("[NG]setResourceId:ResourceId does not exist.\n" + e);
        } catch (IllegalAccessException e) {
            Assert.fail("[NG]setResourceId:Access to ResourceId is illegal.\n" + e);
        }

        assertEquals("[NG]setResourceId:Set ResourceId is not an expected one.\n",
                     rid, resourceId);
    }

    /**
     * UnitTest method for getResourceId.
     */
    @Test
    public void testGetResourceId() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        assertEquals("[NG]getResourceId:Return is not an expected ResourceId.\n",
                     rid, assignment.getResourceId());
    }

    /**
     * UnitTest method for getResourceIdBuilder.
     */
    @Test
    public void testGetResourceIdBuilder() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        assertEquals("[NG]getResourceIdBuilder:Return is not an expected ResourceIdBuilder.\n",
                     rid, assignment.getResourceIdBuilder().build());
    }

    /**
     * UnitTest method for addAnnotation.
     */
    @Test
    public void testAddAnnotation() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        // call addAnnotation
        assignment.addAnnotation("name", "value");

        // get annotatedNodeInfos
        List<AnnotatedNodeInfo> annotatedNodeInfos = new ArrayList<AnnotatedNodeInfo>();
        try {
            Field field = OpenConfigObjectHandler.class.getDeclaredField("annotatedNodeInfos");
            field.setAccessible(true);
            annotatedNodeInfos = (List<AnnotatedNodeInfo>) field.get(assignment);
        } catch (NoSuchFieldException e) {
            Assert.fail("[NG]addAnnotation:List of AnnotatedNodeInfo does not exist.\n" + e);
        } catch (IllegalAccessException e) {
            Assert.fail("[NG]addAnnotation:Access to list of AnnotatedNodeInfo is illegal.\n" + e);
        }

        assertEquals("[NG]addAnnotation:List size of AnnotatedNodeInfo is invalid.\n",
                     1, annotatedNodeInfos.size());
        assertEquals("[NG]addAnnotation:ResourceId of AnnotatedNodeInfo is not an expected one.\n",
                     rid, annotatedNodeInfos.get(0).resourceId());
        assertEquals("[NG]addAnnotation:List size of Annotation is invalid.\n",
                     1, annotatedNodeInfos.get(0).annotations().size());
        assertEquals("[NG]addAnnotation:Name of Annotation is not an expected one.\n",
                     "name", annotatedNodeInfos.get(0).annotations().get(0).name());
        assertEquals("[NG]addAnnotation:Value of Annotation is not an expected one.\n",
                     "value", annotatedNodeInfos.get(0).annotations().get(0).value());
    }

    /**
     * UnitTest method for getAnnotatedNodeInfoList.
     */
    @Test
    public void testGetAnnotatedNodeInfoList() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        // set list of AnnotatedNodeInfo
        assignment.addAnnotation("name", "value");

        assertEquals("[NG]getAnnotatedNodeInfoList:List size of AnnotatedNodeInfo is invalid.\n",
                     1, assignment.getAnnotatedNodeInfoList().size());
        assertEquals("[NG]getAnnotatedNodeInfoList:ResourceId of AnnotatedNodeInfo is not an expected one.\n",
                     rid, assignment.getAnnotatedNodeInfoList().get(0).resourceId());
        assertEquals("[NG]getAnnotatedNodeInfoList:List size of Annotation is invalid.\n",
                     1, assignment.getAnnotatedNodeInfoList().get(0).annotations().size());
        assertEquals("[NG]getAnnotatedNodeInfoList:Name of Annotation is not an expected one.\n",
                     "name", assignment.getAnnotatedNodeInfoList().get(0).annotations().get(0).name());
        assertEquals("[NG]getAnnotatedNodeInfoList:Value of Annotation is not an expected one.\n",
                     "value", assignment.getAnnotatedNodeInfoList().get(0).annotations().get(0).value());
    }

    /**
     * UnitTest method for addConfig.
     */
    @Test
    public void testAddConfig() {
        // test Handler
        OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent);

        // call addConfig
        OpenConfigConfigOfAssignmentHandler configOfAssignment =
            new OpenConfigConfigOfAssignmentHandler(assignment);

        // expected ModelObject
        DefaultAssignment modelObject = new DefaultAssignment();
        modelObject.index(2);
        DefaultConfig config = new DefaultConfig();
        modelObject.config(config);

        assertEquals("[NG]addConfig:ModelObject(Config added) is not an expected one.\n",
                     modelObject, assignment.getModelObject());
    }
}


text:
package com.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.app.http.HttpCallBack;
import com.app.http.MAsyncTask;

public class MainActivity extends AppCompatActivity {

    MAsyncTask mAsyncTask ;

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

        //请求地址
        String url = "http://www.baidu.com" ;

        mAsyncTask = new MAsyncTask( url  , new HttpCallBack() {
            @Override
            protected void start() {
                super.start();
                Toast.makeText( MainActivity.this , "开始了" , Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void finished(String result) {
                super.finished(result);
                Toast.makeText( MainActivity.this , "完成了" + result , Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void cancle() {
                super.cancle();
                Toast.makeText( MainActivity.this , "取消了" , Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void progressUpdate(Integer progress) {
                super.progressUpdate(progress);
                Toast.makeText( MainActivity.this , "进度" + progress , Toast.LENGTH_SHORT).show();
            }
        }) ;

    }

}


text:
package com.lenzhao.framework.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

public class HessianSerializer implements ISerializer{
	private static final HessianSerializer INSTANCE = new HessianSerializer();

	private HessianSerializer()
	{

	}

	public static ISerializer getInstance() {
		return INSTANCE;
	}

	@Override
	public RpcRequest decodeRequest(InputStream inputStream) throws IOException {
		Hessian2Input in = new Hessian2Input(inputStream);
		RpcRequest obj = (RpcRequest)in.readObject();
		return obj;
	}

	@Override
	public void encodeResponse(OutputStream outputStream, RpcResponse result)
			throws IOException {
         Hessian2Output out = new Hessian2Output(outputStream);
         out.writeObject(result);
         out.flush();
	}

	@Override
	public RpcResponse decodeResponse(InputStream inputStream)
			throws IOException {
		  Hessian2Input in = new Hessian2Input(inputStream);
		  RpcResponse obj = (RpcResponse)in.readObject();
		  return obj;
	}

	@Override
	public void encodeRequest(OutputStream outputStream, RpcRequest request)
			throws IOException {
        Hessian2Output out = new Hessian2Output(outputStream);
        out.writeObject(request);
        out.flush();
	}

}