text:
#ifndef TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED

#include "catch_reporter_bases.hpp"

#include "../internal/catch_reporter_registrars.hpp"
#include "../internal/catch_console_colour.hpp"

namespace Catch {

    struct CompactReporter : StreamingReporterBase {

        CompactReporter( ReporterConfig const& _config )
        : StreamingReporterBase( _config )
        {}

        virtual ~CompactReporter();

        static std::string getDescription() {
            return "Reports test results on a single line, suitable for IDEs";
        }

        virtual ReporterPreferences getPreferences() const {
            ReporterPreferences prefs;
            prefs.shouldRedirectStdOut = false;
            return prefs;
        }

        virtual void noMatchingTestCases( std::string const& spec ) {
            stream << "No test cases matched '" << spec << '\'' << std::endl;
        }

        virtual void assertionStarting( AssertionInfo const& ) {}

        virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
            AssertionResult const& result = _assertionStats.assertionResult;

            bool printInfoMessages = true;

            // Drop out if result was successful and we're not printing those
            if( !m_config->includeSuccessfulResults() && result.isOk() ) {
                if( result.getResultType() != ResultWas::Warning )
                    return false;
                printInfoMessages = false;
            }

            AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
            printer.print();

            stream << std::endl;
            return true;
        }

        virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE {
            if (m_config->showDurations() == ShowDurations::Always) {
                stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
            }
        }

        virtual void testRunEnded( TestRunStats const& _testRunStats ) {
            printTotals( _testRunStats.totals );
            stream << '\n' << std::endl;
            StreamingReporterBase::testRunEnded( _testRunStats );
        }

    private:
        class AssertionPrinter {
            void operator= ( AssertionPrinter const& );
        public:
            AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
            : stream( _stream )
            , stats( _stats )
            , result( _stats.assertionResult )
            , messages( _stats.infoMessages )
            , itMessage( _stats.infoMessages.begin() )
            , printInfoMessages( _printInfoMessages )
            {}

            void print() {
                printSourceInfo();

                itMessage = messages.begin();

                switch( result.getResultType() ) {
                    case ResultWas::Ok:
                        printResultType( Colour::ResultSuccess, passedString() );
                        printOriginalExpression();
                        printReconstructedExpression();
                        if ( ! result.hasExpression() )
                            printRemainingMessages( Colour::None );
                        else
                            printRemainingMessages();
                        break;
                    case ResultWas::ExpressionFailed:
                        if( result.isOk() )
                            printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
                        else
                            printResultType( Colour::Error, failedString() );
                        printOriginalExpression();
                        printReconstructedExpression();
                        printRemainingMessages();
                        break;
                    case ResultWas::ThrewException:
                        printResultType( Colour::Error, failedString() );
                        printIssue( "unexpected exception with message:" );
                        printMessage();
                        printExpressionWas();
                        printRemainingMessages();
                        break;
                    case ResultWas::FatalErrorCondition:
                        printResultType( Colour::Error, failedString() );
                        printIssue( "fatal error condition with message:" );
                        printMessage();
                        printExpressionWas();
                        printRemainingMessages();
                        break;
                    case ResultWas::DidntThrowException:
                        printResultType( Colour::Error, failedString() );
                        printIssue( "expected exception, got none" );
                        printExpressionWas();
                        printRemainingMessages();
                        break;
                    case ResultWas::Info:
                        printResultType( Colour::None, "info" );
                        printMessage();
                        printRemainingMessages();
                        break;
                    case ResultWas::Warning:
                        printResultType( Colour::None, "warning" );
                        printMessage();
                        printRemainingMessages();
                        break;
                    case ResultWas::ExplicitFailure:
                        printResultType( Colour::Error, failedString() );
                        printIssue( "explicitly" );
                        printRemainingMessages( Colour::None );
                        break;
                    // These cases are here to prevent compiler warnings
                    case ResultWas::Unknown:
                    case ResultWas::FailureBit:
                    case ResultWas::Exception:
                        printResultType( Colour::Error, "** internal error **" );
                        break;
                }
            }

        private:
            // Colour::LightGrey

            static Colour::Code dimColour() { return Colour::FileName; }

#ifdef CATCH_PLATFORM_MAC
            static const char* failedString() { return "FAILED"; }
            static const char* passedString() { return "PASSED"; }
#else
            static const char* failedString() { return "failed"; }
            static const char* passedString() { return "passed"; }
#endif

            void printSourceInfo() const {
                Colour colourGuard( Colour::FileName );
                stream << result.getSourceInfo() << ':';
            }

            void printResultType( Colour::Code colour, std::string const& passOrFail ) const {
                if( !passOrFail.empty() ) {
                    {
                        Colour colourGuard( colour );
                        stream << ' ' << passOrFail;
                    }
                    stream << ':';
                }
            }

            void printIssue( std::string const& issue ) const {
                stream << ' ' << issue;
            }

            void printExpressionWas() {
                if( result.hasExpression() ) {
                    stream << ';';
                    {
                        Colour colour( dimColour() );
                        stream << " expression was:";
                    }
                    printOriginalExpression();
                }
            }

            void printOriginalExpression() const {
                if( result.hasExpression() ) {
                    stream << ' ' << result.getExpression();
                }
            }

            void printReconstructedExpression() const {
                if( result.hasExpandedExpression() ) {
                    {
                        Colour colour( dimColour() );
                        stream << " for: ";
                    }
                    stream << result.getExpandedExpression();
                }
            }

            void printMessage() {
                if ( itMessage != messages.end() ) {
                    stream << " '" << itMessage->message << '\'';
                    ++itMessage;
                }
            }

            void printRemainingMessages( Colour::Code colour = dimColour() ) {
                if ( itMessage == messages.end() )
                    return;

                // using messages.end() directly yields compilation error:
                std::vector<MessageInfo>::const_iterator itEnd = messages.end();
                const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );

                {
                    Colour colourGuard( colour );
                    stream << " with " << pluralise( N, "message" ) << ':';
                }

                for(; itMessage != itEnd; ) {
                    // If this assertion is a warning ignore any INFO messages
                    if( printInfoMessages || itMessage->type != ResultWas::Info ) {
                        stream << " '" << itMessage->message << '\'';
                        if ( ++itMessage != itEnd ) {
                            Colour colourGuard( dimColour() );
                            stream << " and";
                        }
                    }
                }
            }

        private:
            std::ostream& stream;
            AssertionStats const& stats;
            AssertionResult const& result;
            std::vector<MessageInfo> messages;
            std::vector<MessageInfo>::const_iterator itMessage;
            bool printInfoMessages;
        };

        // Colour, message variants:
        // - white: No tests ran.
        // -   red: Failed [both/all] N test cases, failed [both/all] M assertions.
        // - white: Passed [both/all] N test cases (no assertions).
        // -   red: Failed N tests cases, failed M assertions.
        // - green: Passed [both/all] N tests cases with M assertions.

        std::string bothOrAll( std::size_t count ) const {
            return count == 1 ? std::string() : count == 2 ? "both " : "all " ;
        }

        void printTotals( const Totals& totals ) const {
            if( totals.testCases.total() == 0 ) {
                stream << "No tests ran.";
            }
            else if( totals.testCases.failed == totals.testCases.total() ) {
                Colour colour( Colour::ResultError );
                const std::string qualify_assertions_failed =
                    totals.assertions.failed == totals.assertions.total() ?
                        bothOrAll( totals.assertions.failed ) : std::string();
                stream <<
                    "Failed " << bothOrAll( totals.testCases.failed )
                              << pluralise( totals.testCases.failed, "test case"  ) << ", "
                    "failed " << qualify_assertions_failed <<
                                 pluralise( totals.assertions.failed, "assertion" ) << '.';
            }
            else if( totals.assertions.total() == 0 ) {
                stream <<
                    "Passed " << bothOrAll( totals.testCases.total() )
                              << pluralise( totals.testCases.total(), "test case" )
                              << " (no assertions).";
            }
            else if( totals.assertions.failed ) {
                Colour colour( Colour::ResultError );
                stream <<
                    "Failed " << pluralise( totals.testCases.failed, "test case"  ) << ", "
                    "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
            }
            else {
                Colour colour( Colour::ResultSuccess );
                stream <<
                    "Passed " << bothOrAll( totals.testCases.passed )
                              << pluralise( totals.testCases.passed, "test case"  ) <<
                    " with "  << pluralise( totals.assertions.passed, "assertion" ) << '.';
            }
        }
    };

    INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter )

} // end namespace Catch

#endif // TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED


text:
set -e

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

export GO111MODULE=on

cd ${DIR}
go mod tidy -compat=1.17
bazel run //:gazelle -- update-repos -from_file=${DIR}/go.mod -to_macro=third_party/go_repositories.bzl%go_repositories -prune
bazel run //:gazelle

echo "updates done"

redpajama_set_name: RedPajamaGithub


text:
New Occurrence

        <form class="form-horizontal" data-ng-submit="create()" novalidate>
            <fieldset>

                    Name

                        <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>

                    actions

                        <input type="text" data-ng-model="actions" id="actions" class="form-control" placeholder="actions" required>

                    <input type="submit" class="btn btn-default">

            </fieldset>
        </form>


text:
"""
serializers.py - (C) Copyright - 2017
This software is copyrighted to contributors listed in CONTRIBUTIONS.md.

SPDX-License-Identifier: MIT

Author(s) of this file:
  J. Harding

Serializers for pull requests.
"""

import datetime
from django.db import models as m
from rest_framework import serializers as s
from repo_health.gh_users.models import GhUser
from ..models import GhPullRequestHistory
from repo_health.index.mixins import CountForPastYearMixin
from repo_health.metrics.serializers import MetricField, ChartField

class GhPullRequestStatsSerializer(s.Serializer, CountForPastYearMixin):
    _most_recent_history = None
    _opened_histories = None
    _contrib_most_prs = None
    _maintainers = None
    _maintainers_count = None
    _charts = None

    card_title = s.SerializerMethodField()
    pr_count = s.SerializerMethodField()
    prs_last_year = s.SerializerMethodField()
    latest_pr_created_at = s.SerializerMethodField()
    contrib_most_prs = s.SerializerMethodField()
    prs_no_maintainer_comments = s.SerializerMethodField()
    maintainers_count = s.SerializerMethodField()
    prs_no_comments = s.SerializerMethodField()
    avg_lifetime = s.SerializerMethodField()
    not_maintainer_prs = s.SerializerMethodField()
    avg_comment_per_pr = s.SerializerMethodField()
    prs_from_outside_org = s.SerializerMethodField()

    # Chart name
    PRS_LAST_YEAR = 'prs_last_year'

    @property
    def charts(self):
        return self._charts

    @charts.setter
    def charts(self, charts):
        self._charts = charts

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.charts = []
        repo = args[0]
        self._opened_histories = GhPullRequestHistory.objects.filter(
            pull_request__base_repo=repo,
            action=GhPullRequestHistory.OPENED_ACTION,
        ).order_by('-created_at')

        self._most_recent_history = self._opened_histories.first()

        # Get user with the most pull requests for this repo
        self._contrib_most_prs = GhUser.objects.filter(
            pull_requests__base_repo=repo,
        ).annotate(
            contrib_prs=m.Count('pull_requests')
        ).order_by('-contrib_prs').first()

        self._maintainers = repo.maintainers.all()

    def get_card_title(self, repo):
        return MetricField(True, None, 0, None, 'Pull requests')

    def get_pr_count(self, repo):
        return MetricField(True, 'Number of pull requests', 1, None, repo.pr_count)

    def get_prs_last_year(self, repo):
        num_prs, most_recent = self.get_count_list_for_year(self._opened_histories, 'created_at')
        self._charts.append(ChartField(self.PRS_LAST_YEAR, most_recent, 'Pull requests last year', None, None, 1))
        return MetricField(True, 'Pull requests last year', 2, self.PRS_LAST_YEAR, num_prs)

    def get_latest_pr_created_at(self, repo):
        latest = self._most_recent_history.created_at if self._most_recent_history else None
        return MetricField(True, 'Latest pull request created at', 3, None, latest, True)

    def get_contrib_most_prs(self, repo):
        contrib = self._contrib_most_prs.login if self._contrib_most_prs else None
        return MetricField(True, 'Most contributing user', 4, None, contrib)

    def get_prs_no_maintainer_comments(self, repo):
        no_coms = repo.prs_to.exclude(comment_users__in=self._maintainers).count()
        return MetricField(True, "PRs with no maintainer comments", 5, None, no_coms)

    def get_maintainers_count(self, repo):
        return MetricField(True, 'Number of maintainers', 6, None, self._maintainers.count())

    def get_prs_no_comments(self, repo):
        zero_coms = repo.prs_to.annotate(comments_count=m.Count('comments')).filter(comments_count=0).count()
        return MetricField(True, 'PRs with zero comments', 7, None, zero_coms)

    def get_avg_lifetime(self, repo):
        avg = closed = 0
        # An inefficient way to calculate average but I haven't got the aggregation to work
        if repo.pr_count > 0:  # prevent divide by zero
            td = datetime.timedelta()
            for p in repo.prs_to.all():
                if p.closed_at:
                    closed += 1
                    td += p.closed_at - p.created_at
            avg = (td / closed).days

        # Save this code to hopefully aggregate the average at the database level sometime.
        # agg = GhPullRequest.objects.raw(
        #     "SELECT `pull_requests`.`id`, `pull_request_history`.`created_at` as `created_at`, `t`.`created_at` as " +
        #     "`closed_at` from `pull_requests` join `pull_request_history` on `pull_request_history`." +
        #     "`pull_request_id` = `pull_requests`.`id` join `pull_request_history` `t` on`pull_request_history`." +
        #     "`pull_request_id` = `pull_requests`.`id` where `t`.`action` = 'closed' and `pull_request_history`." +
        #     "`action` = 'opened' and `pull_requests`.`base_repo_id` = %s", [repo.id],

        # )
        # agg = repo.prs_to \
        #     .annotate(closed_at=m.Case(
        #         m.When(
        #             history__action=GhPullRequestHistory.CLOSED_ACTION,
        #             then=m.F('history__created_at'),
        #         ), output_field=m.DateTimeField(),
        #     )) \
        #     .annotate(created_at=m.Case(
        #         m.When(
        #             history__action=GhPullRequestHistory.OPENED_ACTION,
        #             then=m.F('history__created_at'),
        #         ), output_field=m.DateTimeField(),
        #     )) \
        #     .values('created_at', 'closed_at', 'id', 'history__action') \
        #     .exclude(m.Q(history__action=GhPullRequestHistory.CLOSED_ACTION) & m.Q(closed_at__isnull=True)).query
            # .aggregate(avg=m.Avg(m.F('created_at') - m.F('closed_at'), output_field=m.DurationField()))
        # print(agg)

        return MetricField(True, 'Average lifetime', 8, None, avg)

    def get_not_maintainer_prs(self, repo):
        prs_not_main = repo.prs_to.exclude(user__in=self._maintainers).count()
        return MetricField(True, 'PRs not from maintainer', 9, None, prs_not_main)

    def get_avg_comment_per_pr(self, repo):
        avg_agg = repo.prs_to.annotate(comment_count=m.Count('comments')) \
            .aggregate(avg=m.Avg('comment_count'))
        return MetricField(True, 'Avg comments per PR', 10, None, avg_agg['avg'])

    def get_prs_from_outside_org(self, repo):
        out_org = None
        if repo.is_owned_by_org():
            out_org = repo.prs_to.exclude(user__organizations=repo.owner).count()
        return MetricField(True, 'PRs from outside org', 11, None, out_org)


text:
#include <Python.h>
#include <csignal>
#include <cstring>
#include <iostream>
#include "pybackend.h"

namespace {
    PyObject *logging()
    {
        static PyObject *module(NULL);

        if (module == NULL) {
            module = PyImport_ImportModule("logging");

            if (module == NULL)
                PyErr_SetString(PyExc_ImportError, "Import of logging failed");
        }

        return module;
    }

    void initializePython()
    {
        Py_Initialize();

        /* Python implements a signal handler for SIGINT that can cause segmentation faults when
         * Stream objects call python functions in their destructors. Resetting the SIGINT handler
         * to its default resolves this problem: */
        PyOS_setsig(SIGINT, SIG_DFL);
    }

    void checkPythonVersion()
    {
        const std::string linkedVersionString(Py_GetVersion(), std::strlen(PY_VERSION));

        if (std::strcmp(PY_VERSION, linkedVersionString.c_str()) != 0)
            std::cerr << "Plic is built against python " << PY_VERSION << " but linked against "
                << linkedVersionString << std::endl;
    }

    void initialize()
    {
        PyObject *nullHandler;
        PyObject *rootLogger;
        PyObject *retValue;

        initializePython();
        checkPythonVersion();

        rootLogger = PyObject_CallMethod(logging(), "getLogger", NULL);
        nullHandler = PyObject_CallMethod(logging(), "NullHandler", NULL);

        retValue = PyObject_CallMethod(rootLogger, "addHandler", "(O)", nullHandler);

        Py_DECREF(rootLogger);
        Py_DECREF(nullHandler);
        Py_DECREF(retValue);
    }

    void initializeIfNecessary()
    {
        if (!Py_IsInitialized())
            initialize();
    }

    PyObject *createLogArgument(const plic::Message& msg)
    {
        static const int pyLevels[] = { 10, 20, 30, 40, 50 };

        return Py_BuildValue("(is)", pyLevels[msg.getLevel()], msg.getText().c_str());
    }

    PyObject *createLogKwarg(const plic::Message& msg)
    {
        const std::string& filename(msg.getFilename());
        const std::string& function(msg.getFunction());
        PyObject *functionName;
        PyObject *lineNumber;
        PyObject *fileName;
        PyObject *metaInfo;
        PyObject *extra;

        metaInfo = PyDict_New();
        extra = PyDict_New();

        lineNumber = Py_BuildValue("i", msg.getLineNumber());
        fileName = filename.empty() ? Py_None : Py_BuildValue("s", filename.c_str());
        functionName = filename.empty() ? Py_None : Py_BuildValue("s", function.c_str());

        PyDict_SetItemString(metaInfo, "cfilename", fileName);
        PyDict_SetItemString(metaInfo, "cfuncName", functionName);
        PyDict_SetItemString(metaInfo, "clineno", lineNumber);
        PyDict_SetItemString(extra, "extra", metaInfo);

        Py_DECREF(lineNumber);
        Py_DECREF(metaInfo);

        if (fileName != Py_None)
            Py_DECREF(fileName);

        if (functionName != Py_None)
            Py_DECREF(functionName);

        return extra;
    }

    void logInitialized(const plic::Message& message)
    {
        PyObject *logger;
        PyObject *result;
        PyObject *logFct;
        PyObject *extra;
        PyObject *args;

        logger = PyObject_CallMethod(logging(), "getLogger", "(s)", message.getLogger().c_str());
        logFct = PyObject_GetAttrString(logger, "log");
        args = createLogArgument(message);
        extra = createLogKwarg(message);

        result = PyObject_Call(logFct, args, extra);

        Py_DECREF(logFct);
        Py_DECREF(result);
        Py_DECREF(logger);
        Py_XDECREF(extra);
        Py_DECREF(args);
    }
}

void plic::pyBackend::log(const Message& message)
{
    initializeIfNecessary();

    logInitialized(message);
}

int plic::pyBackend::configure(FILE *fp, const std::string& pyConfigFilename)
{
    initializeIfNecessary();

    return PyRun_SimpleFile(fp, pyConfigFilename.c_str());
}

int plic::pyBackend::configure(const std::string& pyCommands)
{
    initializeIfNecessary();

    return PyRun_SimpleString(pyCommands.c_str());
}


text:
#ifndef DALE_FORM_PROC_PTRLESSTHAN
#define DALE_FORM_PROC_PTRLESSTHAN

#include "../../../Units/Units.h"

namespace dale {
/*! Parse a pointer less-than form.
 *  @param units The units context.
 *  @param fn The function currently in scope.
 *  @param block The current block.
 *  @param node The node being parsed.
 *  @param get_address Whether to return the address of the result.
 *  @param prefixed_with_core (Unused by this form.)
 *  @param pr The parse result for the response.
 */
bool FormProcPtrLessThanParse(Units *units, Function *fn,
                              llvm::BasicBlock *block, Node *node,
                              bool get_address, bool prefixed_with_core,
                              ParseResult *pr);
}

#endif


text:
package gobblin.runtime.job_catalog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.typesafe.config.Config;

import gobblin.configuration.ConfigurationKeys;
import gobblin.metrics.GobblinMetrics;
import gobblin.metrics.MetricContext;
import gobblin.runtime.api.GobblinInstanceEnvironment;
import gobblin.runtime.api.JobCatalog;
import gobblin.runtime.api.JobSpec;
import gobblin.runtime.api.JobSpecNotFoundException;
import gobblin.util.PathUtils;
import gobblin.util.PullFileLoader;
import gobblin.util.filesystem.PathAlterationDetector;
import gobblin.util.filesystem.PathAlterationObserver;

import lombok.AllArgsConstructor;
import lombok.Getter;

public class ImmutableFSJobCatalog extends JobCatalogBase implements JobCatalog {

  protected final FileSystem fs;
  protected final Config sysConfig;

  protected static final Logger LOGGER = LoggerFactory.getLogger(ImmutableFSJobCatalog.class);

  protected final PullFileLoader loader;

  /* The root configuration directory path.*/
  protected final Path jobConfDirPath;
  private final ImmutableFSJobCatalog.JobSpecConverter converter;

  // A monitor for changes to job conf files for general FS
  // This embedded monitor is monitoring job configuration files instead of JobSpec Object.
  protected final PathAlterationDetector pathAlterationDetector;
  public static final String FS_CATALOG_KEY_PREFIX = "gobblin.fsJobCatalog";
  public static final String VERSION_KEY_IN_JOBSPEC = "gobblin.fsJobCatalog.version";
  // Key used in the metadata of JobSpec.
  public static final String DESCRIPTION_KEY_IN_JOBSPEC = "gobblin.fsJobCatalog.description";

  public ImmutableFSJobCatalog(Config sysConfig)
      throws IOException {
    this(sysConfig, null);
  }

  public ImmutableFSJobCatalog(GobblinInstanceEnvironment env)
      throws IOException {
    this(env.getSysConfig().getConfig(), null, Optional.of(env.getMetricContext()),
         env.isInstrumentationEnabled());
  }

  public ImmutableFSJobCatalog(GobblinInstanceEnvironment env, PathAlterationObserver observer)
      throws IOException {
    this(env.getSysConfig().getConfig(), observer, Optional.of(env.getMetricContext()),
         env.isInstrumentationEnabled());
  }

  public ImmutableFSJobCatalog(Config sysConfig, PathAlterationObserver observer)
      throws IOException {
    this(sysConfig, observer, Optional.<MetricContext>absent(), GobblinMetrics.isEnabled(sysConfig));
  }

  public ImmutableFSJobCatalog(Config sysConfig, PathAlterationObserver observer, Optional<MetricContext> parentMetricContext,
      boolean instrumentationEnabled)
      throws IOException {
    super(Optional.of(LOGGER), parentMetricContext, instrumentationEnabled);
    this.sysConfig = sysConfig;
    ConfigAccessor cfgAccessor = new ConfigAccessor(this.sysConfig);

    this.jobConfDirPath = cfgAccessor.getJobConfDirPath();
    this.fs = cfgAccessor.getJobConfDirFileSystem();

    this.loader = new PullFileLoader(jobConfDirPath, jobConfDirPath.getFileSystem(new Configuration()),
        cfgAccessor.getJobConfigurationFileExtensions(),
        PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS);
    this.converter = new ImmutableFSJobCatalog.JobSpecConverter(this.jobConfDirPath, getInjectedExtension());

    long pollingInterval = cfgAccessor.getPollingInterval();

    if (pollingInterval == ConfigurationKeys.DISABLED_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL) {
      this.pathAlterationDetector = null;
    }
    else {
      this.pathAlterationDetector = new PathAlterationDetector(pollingInterval);

      // If absent, the Optional object will be created automatically by addPathAlterationObserver
      Optional<PathAlterationObserver> observerOptional = Optional.fromNullable(observer);
      FSPathAlterationListenerAdaptor configFilelistener =
          new FSPathAlterationListenerAdaptor(this.jobConfDirPath, this.loader, this.sysConfig, this.listeners,
              this.converter);
      this.pathAlterationDetector.addPathAlterationObserver(configFilelistener, observerOptional, this.jobConfDirPath);
    }
  }

  @Override
  protected void startUp()
      throws IOException {
    super.startUp();

    if (this.pathAlterationDetector != null) {
      this.pathAlterationDetector.start();
    }
  }

  @Override
  protected void shutDown()
      throws IOException {
    try {
      if (this.pathAlterationDetector != null) {
        this.pathAlterationDetector.stop();
      }
    } catch (InterruptedException exc) {
      throw new RuntimeException("Failed to stop " + ImmutableFSJobCatalog.class.getName(), exc);
    }
    super.shutDown();
  }

  /**
   * Fetch all the job files under the jobConfDirPath
   * @return A collection of JobSpec
   */
  @Override
  public synchronized List<JobSpec> getJobs() {
    return Lists.transform(Lists.newArrayList(
        loader.loadPullFilesRecursively(loader.getRootDirectory(), this.sysConfig, shouldLoadGlobalConf())),
        this.converter);
  }

  /**
   * Fetch single job file based on its URI,
   * return null requested URI not existed
   * @param uri The relative Path to the target job configuration.
   * @return
   */
  @Override
  public synchronized JobSpec getJobSpec(URI uri)
      throws JobSpecNotFoundException {
    try {
      Path targetJobSpecFullPath = getPathForURI(this.jobConfDirPath, uri);
      return this.converter.apply(loader.loadPullFile(targetJobSpecFullPath, this.sysConfig, shouldLoadGlobalConf()));
    } catch (FileNotFoundException e) {
      throw new JobSpecNotFoundException(uri);
    } catch (IOException e) {
      throw new RuntimeException("IO exception thrown on loading single job configuration file:" + e.getMessage());
    }
  }

  /**
   * For immutable job catalog,
   * @return
   */
  public boolean shouldLoadGlobalConf() {
    return true;
  }

  /**
   *
   * @param jobConfDirPath The directory path for job cofniguration files.
   * @param uri Uri as the identifier of JobSpec
   * @return
   */
  protected Path getPathForURI(Path jobConfDirPath, URI uri) {
    return PathUtils.mergePaths(jobConfDirPath, new Path(uri));
  }

  protected Optional<String> getInjectedExtension() {
    return Optional.absent();
  }

  @Getter
  public static class ConfigAccessor {
    private final Config cfg;
    private final long pollingInterval;
    private final String jobConfDir;
    private final Path jobConfDirPath;
    private final FileSystem jobConfDirFileSystem;
    private final Set<String> JobConfigurationFileExtensions;

    public ConfigAccessor(Config cfg) {
      this.cfg = cfg;
      this.pollingInterval = this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY) ?
          this.cfg.getLong(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY)  :
          ConfigurationKeys.DEFAULT_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL;

      if (this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) {
        this.jobConfDir = this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY);
      }
      else if (this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY)) {
        File localJobConfigDir = new File(this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY));
        this.jobConfDir = "file://" + localJobConfigDir.getAbsolutePath();
      }
      else {
        throw new IllegalArgumentException("Expected " + ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY
            + " or " + ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY + " properties.");
      }
      this.jobConfDirPath = new Path(this.jobConfDir);
      try {
        this.jobConfDirFileSystem = this.jobConfDirPath.getFileSystem(new Configuration());
      } catch (IOException e) {
        throw new RuntimeException("Unable to detect job config directory file system: " + e, e);
      }

      this.JobConfigurationFileExtensions = ImmutableSet.<String>copyOf(Splitter.on(",")
          .omitEmptyStrings()
          .trimResults()
          .split(getJobConfigurationFileExtensionsString()));
    }

    private String getJobConfigurationFileExtensionsString() {
      String propValue = this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_EXTENSIONS_KEY) ?
          this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_EXTENSIONS_KEY).toLowerCase() :
            ConfigurationKeys.DEFAULT_JOB_CONFIG_FILE_EXTENSIONS;
      return propValue;
    }
  }

  /**
   * Instance of this function is passed as a parameter into other transform function,
   * for converting Properties object into JobSpec object.
   */
  @AllArgsConstructor
  public static class JobSpecConverter implements Function<Config, JobSpec> {
    private final Path jobConfigDirPath;
    private final Optional<String> extensionToStrip;

    public URI computeURI(Path filePath) {
      // Make sure this is relative
      URI uri = PathUtils.relativizePath(filePath,
          jobConfigDirPath).toUri();
      if (this.extensionToStrip.isPresent()) {
        uri = PathUtils.removeExtension(new Path(uri), this.extensionToStrip.get()).toUri();
      }
      return uri;
    }

    @Nullable
    @Override
    public JobSpec apply(Config rawConfig) {

      URI jobConfigURI = computeURI(new Path(rawConfig.getString(ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY)));

      // Points to noted:
      // 1.To ensure the transparency of JobCatalog, need to remove the addtional
      //   options that added through the materialization process.
      // 2. For files that created by user directly in the file system, there might not be
      //   version and description provided. Set them to default then, according to JobSpec constructor.

      String version;
      if (rawConfig.hasPath(VERSION_KEY_IN_JOBSPEC)) {
        version = rawConfig.getString(VERSION_KEY_IN_JOBSPEC);
      } else {
        // Set the version as default.
        version = "1";
      }

      String description;
      if (rawConfig.hasPath(DESCRIPTION_KEY_IN_JOBSPEC)) {
        description = rawConfig.getString(DESCRIPTION_KEY_IN_JOBSPEC);
      } else {
        // Set description as default.
        description = "Gobblin job " + jobConfigURI;
      }

      Config filteredConfig = rawConfig.withoutPath(FS_CATALOG_KEY_PREFIX);
      // The builder has null-checker. Leave the checking there.
      JobSpec.Builder builder = JobSpec.builder(jobConfigURI).withConfig(filteredConfig)
          .withDescription(description)
          .withVersion(version);

      if (rawConfig.hasPath(ConfigurationKeys.JOB_TEMPLATE_PATH)) {
        try {
          builder.withTemplate(new URI(rawConfig.getString(ConfigurationKeys.JOB_TEMPLATE_PATH)));
        } catch (URISyntaxException e) {
          throw new RuntimeException("Bad job template URI " + e, e);
        }
      }

      return builder.build();
    }
  }
}


text:
package com.cryart.sabbathschool.misc;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.commonsware.cwac.wakeful.WakefulIntentService;

import java.util.Calendar;

public class SSReminder implements WakefulIntentService.AlarmListener {
    public void scheduleAlarms(AlarmManager _SSAlarmManager, PendingIntent _SSAlarmIntent, Context context){
        WakefulIntentService.cancelAlarms(context);

        SharedPreferences ssPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        if (ssPreferences.getBoolean(
                SSConstants.SS_SETTINGS_REMINDER_ENABLED_KEY,
                SSConstants.SS_SETTINGS_REMINDER_ENABLED_DEFAULT_VALUE)) {

            long currentTimeInMillis = System.currentTimeMillis();
            Calendar _SSReminderTime = Calendar.getInstance();
            _SSReminderTime.setTimeInMillis(currentTimeInMillis);

            String ss_settings_reminder_time = ssPreferences.getString(SSConstants.SS_SETTINGS_REMINDER_TIME_KEY, SSConstants.SS_SETTINGS_REMINDER_TIME_DEFAULT_VALUE);

            _SSReminderTime.set(Calendar.HOUR_OF_DAY, SSHelper.parseHourFromString(ss_settings_reminder_time, SSConstants.SS_REMINDER_TIME_SETTINGS_FORMAT));
            _SSReminderTime.set(Calendar.MINUTE, SSHelper.parseMinuteFromString(ss_settings_reminder_time, SSConstants.SS_REMINDER_TIME_SETTINGS_FORMAT));
            _SSReminderTime.set(Calendar.SECOND, 0);

            if (_SSReminderTime.getTimeInMillis() < currentTimeInMillis){
                _SSReminderTime.add(Calendar.DATE, 1);
            }

            _SSAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, _SSReminderTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, _SSAlarmIntent);
        }
    }

    public void sendWakefulWork(Context ctxt) {
        WakefulIntentService.sendWakefulWork(ctxt, SSReminderService.class);
    }

    public long getMaxAge() {
        return AlarmManager.INTERVAL_FIFTEEN_MINUTES * 2;
    }
}


text:
sudo apt-get update
sudo apt-get -y upgrade

sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu trusty/" >> /etc/apt/sources.list'
gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9
gpg -a --export E084DAB9 | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install r-base libapparmor1 libcurl4-gnutls-dev libxml2-dev libssl-dev gdebi-core
sudo apt-get -y install libcairo2-dev
sudo apt-get -y install libxt-dev
sudo apt-get -y install git-core
sudo apt-get -y install libgtk2.0-dev

# sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
# sudo /sbin/mkswap /var/swap.1
# sudo /sbin/swapon /var/swap.1
# sudo sh -c 'echo "/var/swap.1 swap swap defaults 0 0 " >> /etc/fstab'

sudo su - -c "R -e \"install.packages('devtools', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('shinydashboard', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('visNetwork', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('igraph', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('plyr', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('dplyr', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('rpart', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('rpart.plot', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('rattle', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('Rcpp', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('ggplot2', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('Cairo', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('evaluate', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('formatR', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('highr', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('markdown', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('htmltools', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('knitr', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('rmarkdown', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('RColorBrewer', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('shiny', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"library(devtools); install_github('wilkox/treemapify'); library(treemapify)\""
sudo su - -c "R -e \"install.packages('tabplot', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('Hmisc', repos='http://cran.rstudio.com/')\""
sudo su - -c "R -e \"install.packages('polycor', repos='http://cran.rstudio.com/')\""

sudo wget https://download2.rstudio.org/rstudio-server-0.99.903-amd64.deb
sudo gdebi --n rstudio-server-0.99.903-amd64.deb

sudo apt-get install gdebi-core
sudo wget http://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.5.1.834-amd64.deb
sudo gdebi --n shiny-server-1.5.1.834-amd64.deb

sudo service shiny-server stop
sudo cp -R ~/20160428_Shiny /srv/shiny-server/20160428_Shiny/

cd /srv/shiny-server
sudo sed -i "s/^.*site_dir.*/site_dir \/srv\/shiny-server\/20160428_Shiny; /" /etc/shiny-server/shiny-server.conf
sudo sed -i "s/^run_as.*/run_as ubuntu;/" /etc/shiny-server/shiny-server.conf
sudo service shiny-server restart


text:
require 'formula'

class JbossForge < Formula
  homepage 'http://forge.jboss.org/'
  url 'https://repository.jboss.org/nexus/service/local/artifact/maven/redirect?r=releases&g=org.jboss.forge&a=forge-distribution&v=2.12.3.Final&e=zip&c=offline'
  version '2.12.3.Final'
  sha1 '86cb164f7553f227ca9689b48c518e1963df3a79'

  def install
    rm_f Dir["bin/*.bat"]
    libexec.install %w{ addons bin img lib logging.properties }
    bin.install_symlink libexec/'bin/forge'
  end
end


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="CheckboxTheme">
        <item name="colorControlNormal">@android:color/black</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>

</resources>


text:
package herddb.index.brin;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

import herddb.codec.RecordSerializer;
import herddb.core.AbstractIndexManager;
import herddb.core.AbstractTableManager;
import herddb.core.HerdDBInternalException;
import herddb.core.MemoryManager;
import herddb.core.PageReplacementPolicy;
import herddb.core.PostCheckpointAction;
import herddb.core.TableSpaceManager;
import herddb.index.IndexOperation;
import herddb.index.SecondaryIndexPrefixScan;
import herddb.index.SecondaryIndexRangeScan;
import herddb.index.SecondaryIndexSeek;
import herddb.index.brin.BlockRangeIndexMetadata.BlockMetadata;
import herddb.log.CommitLog;
import herddb.log.LogSequenceNumber;
import herddb.model.Index;
import herddb.model.StatementEvaluationContext;
import herddb.model.StatementExecutionException;
import herddb.model.Table;
import herddb.model.TableContext;
import herddb.sql.SQLRecordKeyFunction;
import herddb.storage.DataStorageManager;
import herddb.storage.DataStorageManagerException;
import herddb.storage.IndexStatus;
import herddb.utils.Bytes;
import herddb.utils.DataAccessor;
import herddb.utils.ExtendedDataInputStream;
import herddb.utils.ExtendedDataOutputStream;
import herddb.utils.SimpleByteArrayInputStream;

/**
 * Block-range like index with pagination managed by a {@link PageReplacementPolicy}
 *
 * @author enrico.olivelli
 * @author diego.salvi
 */
public class BRINIndexManager extends AbstractIndexManager {

    private static final Logger LOGGER = Logger.getLogger(BRINIndexManager.class.getName());
    LogSequenceNumber bootSequenceNumber;
    private final AtomicLong newPageId = new AtomicLong(1);
    private final BlockRangeIndex<Bytes, Bytes> data;
    private final IndexDataStorage<Bytes, Bytes> storageLayer = new IndexDataStorageImpl();

    public BRINIndexManager(Index index, MemoryManager memoryManager, AbstractTableManager tableManager, CommitLog log, DataStorageManager dataStorageManager, TableSpaceManager tableSpaceManager, String tableSpaceUUID, long transaction) {
        super(index, tableManager, dataStorageManager, tableSpaceManager.getTableSpaceUUID(), log, transaction);
        this.data = new BlockRangeIndex<>(
                memoryManager.getMaxLogicalPageSize(),
                memoryManager.getDataPageReplacementPolicy(),
                storageLayer);
    }

    private static final class PageContents {

        public static final int TYPE_METADATA = 9;
        public static final int TYPE_BLOCKDATA = 10;

        private int type;
        private List<Map.Entry<Bytes, Bytes>> pageData;
        private List<BlockRangeIndexMetadata.BlockMetadata<Bytes>> metadata;

        byte[] serialize() throws IOException {
            try (ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                 ExtendedDataOutputStream eout = new ExtendedDataOutputStream(out)) {
                 serialize(eout);

                 eout.flush();

                 return out.toByteArray();
            }
        }

        void serialize(ExtendedDataOutputStream out) throws IOException {
            out.writeVLong(2); // version
            out.writeVLong(0); // flags for future implementations

            out.writeVInt(this.type);
            switch (type) {
                case TYPE_METADATA:
                    out.writeVInt(metadata.size());
                    for (BlockRangeIndexMetadata.BlockMetadata<Bytes> md : metadata) {
                        /* First key is null if is the head block */
                        boolean head = md.firstKey == null;
                        /* Next block is null if is the tail block */
                        boolean tail = md.nextBlockId == null;

                        /* Prepares hasd/tail flags */
                        byte blockFlags = 0;
                        if (head) {
                            blockFlags |= BlockMetadata.HEAD;
                        }
                        if (tail) {
                            blockFlags |= BlockMetadata.TAIL;
                        }
                        out.writeByte(blockFlags);

                        if (!head) {
                            out.writeArray(md.firstKey.data);
                        }
                        out.writeVLong(md.blockId);
                        out.writeVLong(md.size);
                        out.writeVLong(md.pageId);

                        if (!tail) {
                            out.writeVLong(md.nextBlockId);
                        }
                    }
                    break;
                case TYPE_BLOCKDATA:
                    out.writeVInt(pageData.size());
                    for (Map.Entry<Bytes, Bytes> entry : pageData) {
                        out.writeArray(entry.getKey().data);
                        out.writeArray(entry.getValue().data);
                    }
                    break;
                default:
                    throw new IllegalStateException("bad index page type " + type);
            }
        }

        static PageContents deserialize(ExtendedDataInputStream in) throws IOException {
            long version = in.readVLong(); // version
            long flags = in.readVLong(); // flags for future implementations

            /* Only version 2 actually supported, older versions will need a full rebuild */
            if (version < 2) {
                throw new UnsupportedMetadataVersionException(version);
            }

            if (version > 2 || flags != 0) {
                throw new DataStorageManagerException("corrupted index page");
            }

            PageContents result = new PageContents();
            result.type = in.readVInt();
            switch (result.type) {
                case TYPE_METADATA:
                    int blocks = in.readVInt();
                    result.metadata = new ArrayList<>();
                    for (int i = 0; i < blocks; i++) {
                        byte blockFlags = in.readByte();
                        Bytes firstKey;
                        if ((blockFlags & BlockMetadata.HEAD) > 0) {
                            /* Is HEAD */
                            /* First key is null if is the head block */
                            firstKey = null;
                        } else {
                            firstKey = Bytes.from_array(in.readArray());
                        }

                        long blockId = in.readVLong();
                        long size = in.readVLong();
                        long pageId = in.readVLong();

                        Long nextBlockId;
                        if ((blockFlags & BlockMetadata.TAIL) > 0) {
                            /* Is TAIL */
                            /* Next block is null if is the tail block */
                            nextBlockId = null;
                        } else {
                            nextBlockId = in.readVLong();
                        }

                        BlockRangeIndexMetadata.BlockMetadata<Bytes> md
                            = new BlockRangeIndexMetadata.BlockMetadata<>(firstKey, blockId, size, pageId, nextBlockId);
                        result.metadata.add(md);
                    }
                    break;
                case TYPE_BLOCKDATA:
                    int values = in.readVInt();
                    result.pageData = new ArrayList<>(values);
                    for (int i = 0; i < values; i++) {
                        Bytes key = Bytes.from_array(in.readArray());
                        Bytes value = Bytes.from_array(in.readArray());
                        result.pageData.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
                    }
                    break;
                default:
                    throw new IOException("bad index page type " + result.type);
            }
            return result;
        }

        static PageContents deserialize(byte[] pagedata) throws IOException {
            try (SimpleByteArrayInputStream in = new SimpleByteArrayInputStream(pagedata);
                ExtendedDataInputStream ein = new ExtendedDataInputStream(in)) {
                return deserialize(ein);
            }
        }
    }

    /**
     * Signal that an old unsupported version of page metadata has been read. In
     * such cases the index will need a full rebuild.
     */
    private static final class UnsupportedMetadataVersionException extends HerdDBInternalException {

        /** Default Serial Version UID */
        private static final long serialVersionUID = 1L;

        private final long version;

        public UnsupportedMetadataVersionException(long version) {
            super();
            this.version = version;
        }
    }

    @Override
    protected boolean doStart(LogSequenceNumber sequenceNumber) throws DataStorageManagerException {
        LOGGER.log(Level.SEVERE, " start index {0} uuid {1}", new Object[]{index.name, index.uuid});
        bootSequenceNumber = sequenceNumber;

        if (LogSequenceNumber.START_OF_TIME.equals(sequenceNumber)) {
            /* Empty index (booting from the start) */
            this.data.boot(BlockRangeIndexMetadata.empty());
            LOGGER.log(Level.SEVERE, "loaded empty index {0}", new Object[]{index.name});

            return true;
        } else {

            IndexStatus status;
            try {
                status = dataStorageManager.getIndexStatus(tableSpaceUUID, index.uuid, sequenceNumber);
            } catch (DataStorageManagerException e) {
                LOGGER.log(Level.SEVERE, "cannot load index {0} due to {1}, it will be rebuilt", new Object[] {index.name, e});
                return false;
            }

            try {
                PageContents metadataBlock = PageContents.deserialize(status.indexData);
                this.data.boot(new BlockRangeIndexMetadata<>(metadataBlock.metadata));
            } catch (IOException e) {
                throw new DataStorageManagerException(e);
            } catch (UnsupportedMetadataVersionException e) {
                LOGGER.log(Level.SEVERE, "cannot load index {0} due to an old metadata version ({1}) found, it will be rebuilt", new Object[] {index.name, e.version});
                return false;
            }

            newPageId.set(status.newPageId);
            LOGGER.log(Level.SEVERE, "loaded index {0} {1} blocks", new Object[]{index.name, this.data.getNumBlocks()});
            return true;
        }

    }

    @Override
    public void rebuild() throws DataStorageManagerException {
        long _start = System.currentTimeMillis();
        LOGGER.log(Level.SEVERE, "rebuilding index {0}", index.name);
        data.reset();
        Table table = tableManager.getTable();
        tableManager.scanForIndexRebuild(r -> {
            DataAccessor values = r.getDataAccessor(table);
            Bytes key = RecordSerializer.serializePrimaryKey(values, table, table.primaryKey);
            Bytes indexKey = RecordSerializer.serializePrimaryKey(values, index, index.columnNames);
//            LOGGER.log(Level.SEVERE, "adding " + key + " -> " + values);
            recordInserted(key, indexKey);
        });
        long _stop = System.currentTimeMillis();
        LOGGER.log(Level.SEVERE, "rebuilding index {0} took {1}", new Object[]{index.name, (_stop - _start) + " ms"});
    }

    @Override
    public List<PostCheckpointAction> checkpoint(LogSequenceNumber sequenceNumber, boolean pin) throws DataStorageManagerException {
        try {
            BlockRangeIndexMetadata<Bytes> metadata = data.checkpoint();
            PageContents page = new PageContents();
            page.type = PageContents.TYPE_METADATA;
            page.metadata = metadata.getBlocksMetadata();
            byte[] contents = page.serialize();
            Set<Long> activePages = new HashSet<>();
            page.metadata.forEach(b -> {
                activePages.add(b.pageId);
            });
            IndexStatus indexStatus = new IndexStatus(index.name, sequenceNumber, newPageId.get(), activePages, contents);
            List<PostCheckpointAction> result = new ArrayList<>();
            result.addAll(dataStorageManager.indexCheckpoint(tableSpaceUUID, index.uuid, indexStatus, pin));

            LOGGER.log(Level.INFO, "checkpoint index {0} finished: logpos {1}, {2} blocks",
                    new Object[] {index.name, sequenceNumber, Integer.toString(page.metadata.size())});
            LOGGER.log(Level.FINE, "checkpoint index {0} finished: logpos {1}, pages {2}",
                    new Object[] {index.name, sequenceNumber, activePages});

            return result;
        } catch (IOException err) {
            throw new DataStorageManagerException(err);
        }
    }

    @Override
    public void unpinCheckpoint(LogSequenceNumber sequenceNumber) throws DataStorageManagerException {
        dataStorageManager.unPinIndexCheckpoint(tableSpaceUUID, index.uuid, sequenceNumber);
    }

    @Override
    protected Stream<Bytes> scanner(IndexOperation operation, StatementEvaluationContext context, TableContext tableContext) throws StatementExecutionException {
        if (operation instanceof SecondaryIndexSeek) {
            SecondaryIndexSeek sis = (SecondaryIndexSeek) operation;
            SQLRecordKeyFunction value = sis.value;
            byte[] refvalue = value.computeNewValue(null, context, tableContext);
            return data.query(Bytes.from_array(refvalue));

        } else if (operation instanceof SecondaryIndexPrefixScan) {
            SecondaryIndexPrefixScan sis = (SecondaryIndexPrefixScan) operation;
            SQLRecordKeyFunction value = sis.value;
            byte[] refvalue = value.computeNewValue(null, context, tableContext);
            Bytes firstKey = Bytes.from_array(refvalue);
            Bytes lastKey = firstKey.next();
            return data.query(firstKey, lastKey);

        } else if (operation instanceof SecondaryIndexRangeScan) {

            Bytes firstKey = null;
            Bytes lastKey = null;

            SecondaryIndexRangeScan sis = (SecondaryIndexRangeScan) operation;
            SQLRecordKeyFunction minKey = sis.minValue;
            if (minKey != null) {
                byte[] refminvalue = minKey.computeNewValue(null, context, tableContext);
                firstKey = Bytes.from_array(refminvalue);
            }

            SQLRecordKeyFunction maxKey = sis.maxValue;
            if (maxKey != null) {
                byte[] refmaxvalue = maxKey.computeNewValue(null, context, tableContext);
                lastKey = Bytes.from_array(refmaxvalue);
            }
            LOGGER.log(Level.FINE, "range scan on {0}.{1}, from {2} to {1}", new Object[]{index.table, index.name, firstKey, lastKey});
            return data.query(firstKey, lastKey);

        } else {
            throw new UnsupportedOperationException("unsuppported index access type " + operation);
        }
    }

    @Override
    public void recordDeleted(Bytes key, Bytes indexKey) {
        data.delete(indexKey, key);
    }

    @Override
    public void recordInserted(Bytes key, Bytes indexKey) {
        data.put(indexKey, key);
    }

    @Override
    public void recordUpdated(Bytes key, Bytes indexKeyRemoved, Bytes indexKeyAdded) {
        if (Objects.equals(indexKeyRemoved, indexKeyAdded)) {
            return;
        }
        // BEWARE that this operation is not atomic
        if (indexKeyAdded != null) {
            data.put(indexKeyAdded, key);
        }
        if (indexKeyRemoved != null) {
            data.delete(indexKeyRemoved, key);
        }
    }

    private class IndexDataStorageImpl implements IndexDataStorage<Bytes, Bytes> {

        @Override
        public List<Map.Entry<Bytes, Bytes>> loadDataPage(long pageId) throws IOException {
            try {

                PageContents contents = dataStorageManager.readIndexPage(tableSpaceUUID, index.uuid, pageId, in -> {
                    return PageContents.deserialize(in);
                });

                if (contents.type != PageContents.TYPE_BLOCKDATA) {
                    throw new IOException("page " + pageId + " does not contain blocks data");
                }
                return contents.pageData;
            } catch (DataStorageManagerException err) {
                throw new IOException(err);
            }
        }

        @Override
        public long createDataPage(List<Map.Entry<Bytes, Bytes>> values) throws IOException {
            try {
                PageContents contents = new PageContents();
                contents.type = PageContents.TYPE_BLOCKDATA;
                contents.pageData = values;

                long pageId = newPageId.getAndIncrement();
                dataStorageManager.writeIndexPage(tableSpaceUUID, index.uuid, pageId, (out) -> contents.serialize(out));

                return pageId;
            } catch (DataStorageManagerException err) {
                throw new IOException(err);
            }
        }
    }

    @Override
    public void truncate() throws DataStorageManagerException {
        this.data.reset();
        dropIndexData();
    }

    @Override
    public void close() {
        data.clear();
    }

    public int getNumBlocks() {
        return data.getNumBlocks();
    }

}


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

        <title>Zebra_Mptt example</title>

        <meta http-equiv="content-type" content="text/html;charset=UTF-8">

        <meta http-equiv="Content-Script-Type" content="text/javascript">

        <meta http-equiv="Content-Style-Type" content="text/css">

Zebra_Mptt, database example

For this example, you need to first import the mptt.sql file from the install
        folder and to edit the example.php file and change your database connection related settings.

        <?php

        // database connection details
        $MySQL_host     = '';
        $MySQL_username = '';
        $MySQL_password = '';
        $MySQL_database = '';

        // if could not connect to database
        if (!($connection = @mysql_connect($MySQL_host, $MySQL_username, $MySQL_password))) {

            // stop execution and display error message
            die('Error connecting to the database!
Make sure you have specified correct values for host, username and password.');

        }

        // if database could not be selected
        if (!@mysql_select_db($MySQL_database, $connection)) {

            // stop execution and display error message
            die('Error selecting database!
Make sure you have specified an existing and accessible database.');

        }

        // first, clear everything in the database
        mysql_query('TRUNCATE TABLE mptt');

        // include the Zebra_Mptt class
        require '../Zebra_Mptt.php';

        // instantiate the Zebra_Mptt object
        $mptt = new Zebra_Mptt();

        // populate the table

        // add 'Food' as a topmost node
        $food = $mptt->add(0, 'Food');

        // 'Fruit' and 'Meat' are direct descendants of 'Food'
        $fruit = $mptt->add($food, 'Fruit');
        $meat = $mptt->add($food, 'Meat');

        // 'Red' and 'Yellow' are direct descendants of 'Fruit'
        $red = $mptt->add($fruit, 'Red');
        $yellow = $mptt->add($fruit, 'Yellow');

        // add a fruit of each color
        $mptt->add($red, 'Cherry');
        $mptt->add($yellow, 'Banana');

        // add two kinds of meat
        $mptt->add($meat, 'Beef');
        $mptt->add($meat, 'Pork');

        // get children of 'Red'
        print_r('
Children of "Red"');
        print_r('
');
        print_r($mptt->get_children($red));
        print_r('
');

        // get children of 'Meat'
        print_r('
Children of "Meat"');
        print_r('
');
        print_r($mptt->get_children($meat));
        print_r('
');

        // data in the database as a multidimensional array
        print_r('
The entire tree');
        print_r('
');
        print_r($mptt->get_tree());
        print_r('
');

        ?>


text:
/*jshint forin:false, eqnull:true*/
/* globals JSYG*/

(function(factory) {

    if (typeof define != "undefined" && define.amd) define("jsyg-cropandresize",["jsyg","jsyg-editor","jsyg-canvas"],factory);
    else if (typeof JSYG != "undefined") {
        if (JSYG.Editor && JSYG.Canvas) factory(JSYG,JSYG.Editor,JSYG.Canvas);
        else throw new Error("Dependency is missing");
    }
    else throw new Error("JSYG is needed");

})(function(JSYG,Editor,Canvas) {

    "use strict";

    function Box() {
        this.x = 0;
        this.y = 0;
        this.width = 160;
        this.height = 90;
    };

    /**
     * Recadrage et redimensionnement d'une image (en SVG et canvas) ou d'un noeud SVG (expérimental et incomplet)
     * @param arg argument JSYG faisant référence à l'élément à recadrer
     * @param opt optionnel, objet définissant les options. Si défini, le recadrage sera implicitement activé.
     * @returns {CropAndResize}
     */
    function CropAndResize(arg,opt) {
        /**
         * dimensions initiales du rectangle de recadrage (si keepRatio == true, height sera écrasé par la valeur proportionnelle)
         */
        this.boxInit = new Box();

        /**
         * Objet Editable
         */
        this.editor = new Editor(arg);
        /**
         * Masque pour ombrer ce qui n'est pas sélectionné
         */
        this.mask = new JSYG('<rect>')[0];
        /**
         * Cadre de sélection
         */
        this.selection = new JSYG('<rect>')[0];
        /**
         * Element pattern
         */
        this.pattern = new JSYG('<pattern>')[0];

        if (arg) this.setNode(arg);

        if (opt) this.enable(opt);
    };

    CropAndResize.prototype = {

        constructor : CropAndResize,

        /**
         * Garde ou non le ratio
         */
        keepRatio : false,

        set : JSYG.StdConstruct.prototype.set,
        setNode : JSYG.StdConstruct.prototype.setNode,

        /**
         * Indique si le module est actif ou non
         */
        enabled : false,

        /**
         * Exporte la sélection sous forme d'objet Canvas
         * @param width optionnel, largeur de l'image
         * @param height optionnel, hauteur de l'image
         * @returns {Promise}
         * @see Canvas
         */
        toCanvas : function(width,height) {

            var box = this.selection.getBBox();

            return JSYG(this.node).toCanvas()
            .then(function(canvas) {

                var maxWidth = canvas.getAttribute("width"),
                maxHeight = canvas.getAttribute("height"),
                x = Math.max(0,box.x),
                y = Math.max(0,box.y),
                boxWidth =  Math.min(maxWidth,box.width),
                boxHeight = Math.min(maxHeight,box.height);

                canvas = new Canvas(canvas);

                canvas = canvas.crop(x,y,boxWidth,boxHeight);

                if (width != null || height != null) canvas = canvas.resize(width,height);

                return canvas[0];
            });
        },

        update : function() {

            if (!this.enabled) return this;

            var jNode = new JSYG(this.node),
            svg = jNode.offsetParent(),
            dim = jNode.getDim(svg),
            mtx = jNode.getMtx(svg),
            pattern = new JSYG(this.pattern);

            pattern.find('g').setMtx(mtx);
            pattern.find('rect').setDim(dim);
            pattern.setDim(dim);

            new JSYG(this.mask).setDim(dim);

            this.editor.update();

            return this;
        },
        /**
         * Active le recadrage
         * @param opt optionnel, objet définissant les options
         * @returns {CropAndResize}
         */
        enable : function(opt) {

            this.disable();

            if (opt) this.set(opt);

            var jNode = new JSYG(this.node),
            dim = jNode.getDim(),
            color = jNode.fill(),
            svg = jNode.offsetParent(),
            id = 'idpattern'+JSYG.rand(0,5000),
            g,rect,selection;

            if (!color || color == 'transparent' || color == 'none') color = 'white';

            if (dim.width < this.boxInit.width) this.boxInit.width = dim.width;
            if (dim.height < this.boxInit.height) this.boxInit.height= dim.height;

            rect = new JSYG('<rect>').fill(color);
            g = new JSYG('<g>').append(rect).append(jNode.clone());

            new JSYG(this.pattern)
                .attr({id:id,patternUnits:'userSpaceOnUse'})
                .append(g).appendTo(svg);

            new JSYG(this.mask)
                .css('fill-opacity',0.5)
                .appendTo(svg);

            if (this.keepRatio) this.boxInit.height = dim.height * this.boxInit.width / dim.width;

            selection = new JSYG(this.selection)
                .attr(this.boxInit)
                .attr('fill',"url(#"+id+")")
                .appendTo(svg);

            this.editor.target(selection);
            this.editor.displayShadow = false;

            new JSYG(this.editor.pathBox).css('fill-opacity',0);

            this.editor.ctrlsDrag.enable({
                bounds:0
            });

            this.editor.ctrlsResize.enable({
                keepRatio : this.keepRatio,
                bounds : 0
            });

            this.editor.show();

            this.enabled = true;

            this.update();

            return this;
        },

        /**
         * Désactive le recadrage
         * @returns {CropAndResize}
         */
        disable : function() {

            this.editor.hide();

            new JSYG(this.pattern).remove();
            new JSYG(this.mask).remove();
            new JSYG(this.selection).remove();

            this.enabled = false;

            return this;
        }

    };

    JSYG.CropAndResize = CropAndResize;

    return CropAndResize;

});


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

var Util = require('../../Util');
var SaklientException = require('../../errors/SaklientException');

var Resource = require('./Resource');

var IfaceActivity = require('./IfaceActivity');

'use strict';

/**
* インタフェースの実体1つに対応し、属性の取得や操作を行うためのクラス。
*
* @module saklient.cloud.resources.Iface
* @class Iface
* @constructor
* @extends Resource
*/
var Iface = (function (_super) {
    __extends(Iface, _super);
    /**
    * @private
    * @constructor
    * @param {Client} client
    * @param {any} obj
    * @param {boolean} wrapped=false
    */
    function Iface(client, obj, wrapped) {
        if (typeof wrapped === "undefined") { wrapped = false; }
        _super.call(this, client);
        /**
        * @member saklient.cloud.resources.Iface#n_id
        * @default false
        * @type boolean
        * @private
        */
        this.n_id = false;
        /**
        * @member saklient.cloud.resources.Iface#n_macAddress
        * @default false
        * @type boolean
        * @private
        */
        this.n_macAddress = false;
        /**
        * @member saklient.cloud.resources.Iface#n_ipAddress
        * @default false
        * @type boolean
        * @private
        */
        this.n_ipAddress = false;
        /**
        * @member saklient.cloud.resources.Iface#n_userIpAddress
        * @default false
        * @type boolean
        * @private
        */
        this.n_userIpAddress = false;
        /**
        * @member saklient.cloud.resources.Iface#n_serverId
        * @default false
        * @type boolean
        * @private
        */
        this.n_serverId = false;
        Util.validateArgCount(arguments.length, 2);
        Util.validateType(client, "saklient.cloud.Client");
        Util.validateType(wrapped, "boolean");
        this._activity = new IfaceActivity(client);
        this.apiDeserialize(obj, wrapped);
    }
    /**
    * @private
    * @method _apiPath
    * @protected
    * @return {string}
    */
    Iface.prototype._apiPath = function () {
        return "/interface";
    };

    /**
    * @private
    * @method _rootKey
    * @protected
    * @return {string}
    */
    Iface.prototype._rootKey = function () {
        return "Interface";
    };

    /**
    * @private
    * @method _rootKeyM
    * @protected
    * @return {string}
    */
    Iface.prototype._rootKeyM = function () {
        return "Interfaces";
    };

    /**
    * @private
    * @method _className
    * @return {string}
    */
    Iface.prototype._className = function () {
        return "Iface";
    };

    /**
    * @private
    * @method _id
    * @return {string}
    */
    Iface.prototype._id = function () {
        return this.get_id();
    };

    /**
    * このローカルオブジェクトに現在設定されているリソース情報をAPIに送信し、新規作成または上書き保存します。
    *
    * @method save
    * @chainable
    * @public
    * @return {Iface} this
    */
    Iface.prototype.save = function () {
        return (this._save());
    };

    /**
    * 最新のリソース情報を再取得します。
    *
    * @method reload
    * @chainable
    * @public
    * @return {Iface} this
    */
    Iface.prototype.reload = function () {
        return (this._reload());
    };

    /**
    * @method get_activity
    * @private
    * @return {IfaceActivity}
    */
    Iface.prototype.get_activity = function () {
        return this._activity;
    };

    Object.defineProperty(Iface.prototype, "activity", {
        /**
        * アクティビティ
        *
        * @property activity
        * @type IfaceActivity
        * @readOnly
        * @public
        */
        get: function () {
            return this.get_activity();
        },
        enumerable: true,
        configurable: true
    });

    /**
    * @private
    * @method _onAfterApiDeserialize
    * @protected
    * @param {any} r
    * @param {any} root
    * @return {void}
    */
    Iface.prototype._onAfterApiDeserialize = function (r, root) {
        Util.validateArgCount(arguments.length, 2);
        if (r != null) {
            this._activity.setSourceId(this._id());
        }
        ;
    };

    /**
    * スイッチに接続します。
    *
    * @method connectToSwytch
    * @chainable
    * @public
    * @param {Swytch} swytch 接続先のスイッチ。
    * @return {Iface} this
    */
    Iface.prototype.connectToSwytch = function (swytch) {
        Util.validateArgCount(arguments.length, 1);
        Util.validateType(swytch, "saklient.cloud.resources.Swytch");
        this._client.request("PUT", this._apiPath() + "/" + Util.urlEncode(this._id()) + "/to/switch/" + Util.urlEncode(swytch._id()));
        return this.reload();
    };

    /**
    * 共有セグメントに接続します。
    *
    * @method connectToSharedSegment
    * @chainable
    * @public
    * @return {Iface} this
    */
    Iface.prototype.connectToSharedSegment = function () {
        this._client.request("PUT", this._apiPath() + "/" + Util.urlEncode(this._id()) + "/to/switch/shared");
        return this.reload();
    };

    /**
    * スイッチから切断します。
    *
    * @method disconnectFromSwytch
    * @chainable
    * @public
    * @return {Iface} this
    */
    Iface.prototype.disconnectFromSwytch = function () {
        this._client.request("DELETE", this._apiPath() + "/" + Util.urlEncode(this._id()) + "/to/switch");
        return this.reload();
    };

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method get_id
    * @private
    * @return {string}
    */
    Iface.prototype.get_id = function () {
        return this.m_id;
    };

    Object.defineProperty(Iface.prototype, "id", {
        /**
        * ID
        *
        * @property id
        * @type string
        * @readOnly
        * @public
        */
        get: function () {
            return this.get_id();
        },
        enumerable: true,
        configurable: true
    });

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method get_macAddress
    * @private
    * @return {string}
    */
    Iface.prototype.get_macAddress = function () {
        return this.m_macAddress;
    };

    Object.defineProperty(Iface.prototype, "macAddress", {
        /**
        * MACアドレス
        *
        * @property macAddress
        * @type string
        * @readOnly
        * @public
        */
        get: function () {
            return this.get_macAddress();
        },
        enumerable: true,
        configurable: true
    });

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method get_ipAddress
    * @private
    * @return {string}
    */
    Iface.prototype.get_ipAddress = function () {
        return this.m_ipAddress;
    };

    Object.defineProperty(Iface.prototype, "ipAddress", {
        /**
        * IPv4アドレス(共有セグメントによる自動割当)
        *
        * @property ipAddress
        * @type string
        * @readOnly
        * @public
        */
        get: function () {
            return this.get_ipAddress();
        },
        enumerable: true,
        configurable: true
    });

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method get_userIpAddress
    * @private
    * @return {string}
    */
    Iface.prototype.get_userIpAddress = function () {
        return this.m_userIpAddress;
    };

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method set_userIpAddress
    * @private
    * @param {string} v
    * @return {string}
    */
    Iface.prototype.set_userIpAddress = function (v) {
        Util.validateArgCount(arguments.length, 1);
        Util.validateType(v, "string");
        this.m_userIpAddress = v;
        this.n_userIpAddress = true;
        return this.m_userIpAddress;
    };

    Object.defineProperty(Iface.prototype, "userIpAddress", {
        /**
        * ユーザ設定IPv4アドレス
        *
        * @property userIpAddress
        * @type string
        * @public
        */
        get: function () {
            return this.get_userIpAddress();
        },
        set: function (v) {
            this.set_userIpAddress(v);
        },
        enumerable: true,
        configurable: true
    });

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method get_serverId
    * @private
    * @return {string}
    */
    Iface.prototype.get_serverId = function () {
        return this.m_serverId;
    };

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method set_serverId
    * @private
    * @param {string} v
    * @return {string}
    */
    Iface.prototype.set_serverId = function (v) {
        Util.validateArgCount(arguments.length, 1);
        Util.validateType(v, "string");
        if (!this.isNew) {
            throw new SaklientException("immutable_field", "Immutable fields cannot be modified after the resource creation: " + "saklient.cloud.resources.Iface#serverId");
        }
        ;
        this.m_serverId = v;
        this.n_serverId = true;
        return this.m_serverId;
    };

    Object.defineProperty(Iface.prototype, "serverId", {
        /**
        * このインタフェースが取り付けられているサーバのID
        *
        * @property serverId
        * @type string
        * @public
        */
        get: function () {
            return this.get_serverId();
        },
        set: function (v) {
            this.set_serverId(v);
        },
        enumerable: true,
        configurable: true
    });

    /**
    * (This method is generated in Translator_default#buildImpl)
    *
    * @method apiDeserializeImpl
    * @protected
    * @param {any} r
    */
    Iface.prototype.apiDeserializeImpl = function (r) {
        Util.validateArgCount(arguments.length, 1);
        this.isNew = r == null;
        if (this.isNew) {
            r = {};
        }
        ;
        this.isIncomplete = false;
        if (Util.existsPath(r, "ID")) {
            this.m_id = Util.getByPath(r, "ID") == null ? null : "" + Util.getByPath(r, "ID");
        } else {
            this.m_id = null;
            this.isIncomplete = true;
        }
        ;
        this.n_id = false;
        if (Util.existsPath(r, "MACAddress")) {
            this.m_macAddress = Util.getByPath(r, "MACAddress") == null ? null : "" + Util.getByPath(r, "MACAddress");
        } else {
            this.m_macAddress = null;
            this.isIncomplete = true;
        }
        ;
        this.n_macAddress = false;
        if (Util.existsPath(r, "IPAddress")) {
            this.m_ipAddress = Util.getByPath(r, "IPAddress") == null ? null : "" + Util.getByPath(r, "IPAddress");
        } else {
            this.m_ipAddress = null;
            this.isIncomplete = true;
        }
        ;
        this.n_ipAddress = false;
        if (Util.existsPath(r, "UserIPAddress")) {
            this.m_userIpAddress = Util.getByPath(r, "UserIPAddress") == null ? null : "" + Util.getByPath(r, "UserIPAddress");
        } else {
            this.m_userIpAddress = null;
            this.isIncomplete = true;
        }
        ;
        this.n_userIpAddress = false;
        if (Util.existsPath(r, "Server.ID")) {
            this.m_serverId = Util.getByPath(r, "Server.ID") == null ? null : "" + Util.getByPath(r, "Server.ID");
        } else {
            this.m_serverId = null;
            this.isIncomplete = true;
        }
        ;
        this.n_serverId = false;
    };

    /**
    * @private
    * @method apiSerializeImpl
    * @protected
    * @param {boolean} withClean=false
    * @return {any}
    */
    Iface.prototype.apiSerializeImpl = function (withClean) {
        if (typeof withClean === "undefined") { withClean = false; }
        Util.validateType(withClean, "boolean");
        var missing = [];
        var ret = {};
        if (withClean || this.n_id) {
            Util.setByPath(ret, "ID", this.m_id);
        }
        ;
        if (withClean || this.n_macAddress) {
            Util.setByPath(ret, "MACAddress", this.m_macAddress);
        }
        ;
        if (withClean || this.n_ipAddress) {
            Util.setByPath(ret, "IPAddress", this.m_ipAddress);
        }
        ;
        if (withClean || this.n_userIpAddress) {
            Util.setByPath(ret, "UserIPAddress", this.m_userIpAddress);
        }
        ;
        if (withClean || this.n_serverId) {
            Util.setByPath(ret, "Server.ID", this.m_serverId);
        } else {
            if (this.isNew) {
                missing.push("serverId");
            }
            ;
        }
        ;
        if (missing.length > 0) {
            throw new SaklientException("required_field", "Required fields must be set before the Iface creation: " + missing.join(", "));
        }
        ;
        return ret;
    };
    return Iface;
})(Resource);
module.exports = Iface;


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsCRTGlue_h__
#define nsCRTGlue_h__

#include "nscore.h"

/**
 * Scan a string for the first character that is *not* in a set of
 * delimiters.  If the string is only delimiter characters, the end of the
 * string is returned.
 *
 * @param delims The set of delimiters (null-terminated)
 * @param str    The string to search (null-terminated)
 */
NS_COM_GLUE const char*
NS_strspnp(const char *delims, const char *str);

/**
 * Tokenize a string. This function is similar to the strtok function in the
 * C standard library, but it does not use static variables to maintain state
 * and is therefore thread and reentrancy-safe.
 *
 * Any leading delimiters in str are skipped. Then the string is scanned
 * until an additional delimiter or end-of-string is found. The final
 * delimiter is set to '\0'.
 *
 * @param delims The set of delimiters.
 * @param str    The string to search. This is an in-out parameter; it is
 *               reset to the end of the found token + 1, or to the
 *               end-of-string if there are no more tokens.
 * @return       The token. If no token is found (the string is only
 *               delimiter characters), NULL is returned.
 */
NS_COM_GLUE char*
NS_strtok(const char *delims, char **str);

/**
 * "strlen" for PRUnichar strings
 */
NS_COM_GLUE uint32_t
NS_strlen(const PRUnichar *aString);

/**
 * "strcmp" for PRUnichar strings
 */
NS_COM_GLUE int
NS_strcmp(const PRUnichar *a, const PRUnichar *b);

/**
 * "strdup" for PRUnichar strings, uses the NS_Alloc allocator.
 */
NS_COM_GLUE PRUnichar*
NS_strdup(const PRUnichar *aString);

/**
 * "strdup", but using the NS_Alloc allocator.
 */
NS_COM_GLUE char*
NS_strdup(const char *aString);

/**
 * strndup for PRUnichar strings... this function will ensure that the
 * new string is null-terminated. Uses the NS_Alloc allocator.
 */
NS_COM_GLUE PRUnichar*
NS_strndup(const PRUnichar *aString, uint32_t aLen);

// The following case-conversion methods only deal in the ascii repertoire
// A-Z and a-z

// semi-private data declarations... don't use these directly.
class NS_COM_GLUE nsLowerUpperUtils {
public:
  static const unsigned char kLower2Upper[256];
  static const unsigned char kUpper2Lower[256];
};

inline char NS_ToUpper(char aChar)
{
  return (char)nsLowerUpperUtils::kLower2Upper[(unsigned char)aChar];
}

inline char NS_ToLower(char aChar)
{
  return (char)nsLowerUpperUtils::kUpper2Lower[(unsigned char)aChar];
}

NS_COM_GLUE bool NS_IsUpper(char aChar);
NS_COM_GLUE bool NS_IsLower(char aChar);

NS_COM_GLUE bool NS_IsAscii(PRUnichar aChar);
NS_COM_GLUE bool NS_IsAscii(const PRUnichar* aString);
NS_COM_GLUE bool NS_IsAsciiAlpha(PRUnichar aChar);
NS_COM_GLUE bool NS_IsAsciiDigit(PRUnichar aChar);
NS_COM_GLUE bool NS_IsAsciiWhitespace(PRUnichar aChar);
NS_COM_GLUE bool NS_IsAscii(const char* aString);
NS_COM_GLUE bool NS_IsAscii(const char* aString, uint32_t aLength);

#ifndef XPCOM_GLUE_AVOID_NSPR
NS_COM_GLUE void NS_MakeRandomString(char *buf, int32_t bufLen);
#endif

#define FF '\f'
#define TAB '\t'

#define CRSTR "\015"
#define LFSTR "\012"
#define CRLF "\015\012"     /* A CR LF equivalent string */

#if defined(XP_MACOSX)
  #define FILE_PATH_SEPARATOR        "/"
  #define OS_FILE_ILLEGAL_CHARACTERS ":"
#elif defined(XP_WIN) || defined(XP_OS2)
  #define FILE_PATH_SEPARATOR        "\\"
  #define OS_FILE_ILLEGAL_CHARACTERS "/:*?\"<>|"
#elif defined(XP_UNIX)
  #define FILE_PATH_SEPARATOR        "/"
  #define OS_FILE_ILLEGAL_CHARACTERS ""
#else
  #error need_to_define_your_file_path_separator_and_illegal_characters
#endif

// Not all these control characters are illegal in all OSs, but we don't really
// want them appearing in filenames
#define CONTROL_CHARACTERS     "\001\002\003\004\005\006\007" \
                           "\010\011\012\013\014\015\016\017" \
                           "\020\021\022\023\024\025\026\027" \
                           "\030\031\032\033\034\035\036\037"

#define FILE_ILLEGAL_CHARACTERS CONTROL_CHARACTERS OS_FILE_ILLEGAL_CHARACTERS

#endif // nsCRTGlue_h__


text:
class Other

	def override()
		puts "OTHER override()"
	end

	def implicit()
		puts "OTHER implicit()"
	end

	def altered()
		puts "OTHER altered()"
	end

end

class Child

	def intitialize()
		@other = Other.new()
	end

	def implicit()
		@other.implicit
	end

	def override()
		puts "CHILD override()"
	end

	def altered()
		puts "CHILD, BEFORE OTHER altered()"
	end

end

son = Child.new()

son.implicit()
son.override()
son.altered()


text:
package App::Netdisco::SSHCollector::Platform::GAIAEmbedded;

=head1 NAME

App::Netdisco::SSHCollector::Platform::GAIAEmbedded

=head1 DESCRIPTION

Collect ARP entries from Checkpoint GAIA embedded Systems
To get this Plugin to work you have to add a user like 'netdisco' with
'Network admin' rights in the GAIA embedded OS.

This collector uses "C<arp>" as the command for the arp utility on your
system. If you wish to specify an absolute path, then add an C<arp_command>
item to your configuration:

 device_auth:
   - tag: sshgaia
     driver: cli
     platform: GAIAEmbedded
     only: '192.0.2.1'
     username: oliver
     password: letmein
     arp_command: 'arp'

=cut

use strict;
use warnings;

use Dancer ':script';
use Expect;
use Moo;

=head1 PUBLIC METHODS

=over 4

=item B<arpnip($host, $ssh)>

Retrieve ARP entries from device. C<$host> is the hostname or IP address
of the device. C<$ssh> is a Net::OpenSSH connection to the device.

Returns a list of hashrefs in the format C<{ mac =E<gt> MACADDR, ip =E<gt> IPADDR }>.

=back

=cut

sub arpnip {
    my ($self, $hostlabel, $ssh, $args) = @_;

    debug "$hostlabel $$ arpnip()";

    my ($pty, $pid) = $ssh->open2pty;
    unless ($pty) {
        debug "unable to run remote command [$hostlabel] " . $ssh->error;
        return ();
    }
    my $expect = Expect->init($pty);

    my ($pos, $error, $match, $before, $after);
    my $prompt = qr/>/;

    ($pos, $error, $match, $before, $after) = $expect->expect(30, -re, $prompt);

    my $command = ($args->{arp_command} || 'arp');
    $expect->send("$command -n \n");
    ($pos, $error, $match, $before, $after) = $expect->expect(30, -re, $prompt);

    my @arpentries = ();
    my @lines = split(m/\n/, $before);

#   ? (192.168.17.178) at 5C:F9:DD:71:1F:08 [ether] on LAN1
# https://github.com/netdisco/netdisco/issues/365
    my $linereg = qr/([0-9.]+)\s+ether\s+([a-fA-F0-9:]+).+/;
    foreach my $line (@lines) {
        if ($line =~ $linereg) {
            my ($ip, $mac) = ($1, $2);
            push @arpentries, { mac => $mac, ip => $ip };
        }
    }

    $expect->send("exit\n");
    $expect->soft_close();

    return @arpentries;
}

1;


text:
package io.gitcafe.zhanjiashu.newzhihudialy.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import io.gitcafe.zhanjiashu.newzhihudialy.R;
import io.gitcafe.zhanjiashu.newzhihudialy.adapter.AvatarsAdapter;
import io.gitcafe.zhanjiashu.common.util.LogUtil;
import io.gitcafe.zhanjiashu.newzhihudialy.util.NetworkHelper;
import io.gitcafe.zhanjiashu.newzhihudialy.util.PreferenceHelper;
import io.gitcafe.zhanjiashu.newzhihudialy.widget.ZHLinearLayout;
import io.gitcafe.zhanjiashu.newzhihudialy.model.MemberEntity;
import io.gitcafe.zhanjiashu.newzhihudialy.model.StoryDetailEntity;
import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchDetailTask;
import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchTask;
import io.gitcafe.zhanjiashu.common.util.DisplayUtils;

/**
 * A simple {@link Fragment} subclass.
 */
public class DetailFragment extends Fragment {

    private final String TAG = getClass().getSimpleName();

    public static final String KEY_STORY_ID = "story_id";

    private static final String WEBVIEW_DEFAULT_IMG = "file:///android_asset/default_pic_content_image_download_light.png";

    @InjectView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout mToolbarLayout;

    @InjectView(R.id.toolbar)
    Toolbar mToolbar;

    @InjectView(R.id.iv_top)
    ImageView mTopView;

    @InjectView(R.id.nsv_scroll)
    NestedScrollView mScrollView;

    @InjectView(R.id.ll_editors)
    ZHLinearLayout mRecommendersLayout;

    @InjectView(R.id.rcv_recommenders)
    RecyclerView mRecyclerView;

    @InjectView(R.id.wv_content)
    WebView mWebView;

    @InjectView(R.id.fab_share)
    FloatingActionButton mShareBtn;

    private DisplayImageOptions mImageOptions;

    private TypedArray mActionbarSizeTypedArray;

    private boolean mIsNoPictureMode;

    public static DetailFragment newInstance(int storyId) {
        Bundle args = new Bundle();
        args.putInt(KEY_STORY_ID, storyId);
        DetailFragment fragment = new DetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        PreferenceHelper helper = PreferenceHelper.getInstance(getActivity());
        mIsNoPictureMode = helper.isNoPictureEnabled() && NetworkHelper.getInstance(getActivity()).isMobieNetwork();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);
        ButterKnife.inject(this, view);

        setupView();

        return view;
    }

    private void setupView() {

        final AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
        appCompatActivity.setSupportActionBar(mToolbar);
        ActionBar actionBar = appCompatActivity.getSupportActionBar();

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        intiNestedScrollView();

        mImageOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();

        Bundle arguments = getArguments();
        if (arguments != null) {
            int storyId = arguments.getInt(KEY_STORY_ID);
            FetchDetailTask task= new FetchDetailTask(getActivity(), storyId, false);
            task.execute(new FetchTask.FetchCallback<StoryDetailEntity>() {
                @Override
                public void onFetchResponse(StoryDetailEntity storyDetailEntity) {
                    showStoryDetail(storyDetailEntity);
                }
            });
        }

        mActionbarSizeTypedArray.recycle();
    }

    /**
     * 在布局文件中如果对 NestedScrollView 设置了
     *      app:layout_behavior="@string/appbar_scrolling_view_behavior" ,
     * 将会导致作为其 子View 的 WebView 无法正常显示。这个可能是一个 Bug, 通过本方法可以解决。
     */
    private void intiNestedScrollView() {
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int statusHeight = DisplayUtils.getStatusBarHeight(getActivity());

        mActionbarSizeTypedArray = getActivity().obtainStyledAttributes(new int[]{android.R.attr.actionBarSize});
        int actionBarHeight = (int) mActionbarSizeTypedArray.getDimension(0, 0);

        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mScrollView.getLayoutParams();
        params.height = metrics.heightPixels - statusHeight - actionBarHeight;
        mScrollView.setLayoutParams(params);
    }

    private void showStoryDetail(final StoryDetailEntity entity) {

        mToolbarLayout.setTitle(entity.getTitle());
        if (!mIsNoPictureMode) {
            ImageLoader.getInstance().displayImage(entity.getImage(), mTopView, mImageOptions);
        }
        List<MemberEntity> recommenderEntities = entity.getRecommenders();
        if (recommenderEntities != null && recommenderEntities.size() > 0) {
            List<String> avatarList = new ArrayList<>();
            for (MemberEntity recommenderEntity : recommenderEntities) {
                avatarList.add(recommenderEntity.getAvatar());
            }
            if (avatarList.size() > 0) {
                mRecommendersLayout.setVisibility(View.VISIBLE);
                LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                mRecyclerView.setLayoutManager(manager);
                AvatarsAdapter adapter = new AvatarsAdapter(getActivity(), avatarList, mIsNoPictureMode);
                mRecyclerView.setAdapter(adapter);
            }
        }

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        String contentBody = entity.getBody();
        if (!TextUtils.isEmpty(contentBody)) {
            String html = formatHtml(entity.getCss(), contentBody);
            mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
        } else {
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });
            mWebView.loadUrl(entity.getShare_url());
        }

        mShareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareText(getActivity(), entity.getTitle() + " " + entity.getShare_url());
            }
        });
    }

    private String formatHtml(List<String> cssList, String body) {
        LogUtil.d(TAG, "内容长度" + body.length());
        LogUtil.d(TAG, "当前是否为无图模式和非Wifi网络:" + mIsNoPictureMode);
        String cssLink = formatCssLink(cssList);
        Document document = Jsoup.parse(body);
        document.select("div[class=headline]").remove();
        if (mIsNoPictureMode) {
            Elements imgElts = document.select("img");
            for (Element element : imgElts) {
                String imgUrl = element.attr("src");
                element.attr("src", WEBVIEW_DEFAULT_IMG);
                element.attr("origin-src", imgUrl);
            }
        }
        body = document.html();
        String template = "<!doctype Html>\n" +
                "\n" +
                "\n" +
                "{0}\n" +
                "\n" +
                "\n" +
                "{1}\n" +
                "{2}\n" +
                "\n" +
                "\n" +
                "";

        String js = "";

        return MessageFormat.format(template, cssLink, body, js);

    }

    private String formatCssLink(List<String> cssList) {

        if (cssList != null && cssList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String cssUrl : cssList) {
                if (cssUrl.equals("http://news.at.zhihu.com/css/news_qa.auto.css?v=1edab")) {
                    cssUrl = "file:///android_asset/news_qa.auto.css";
                }
                String cssLink = "<link rel=\"stylesheet\" type=\"text/css\" href=\""+ cssUrl +"\">";
                stringBuilder.append(cssLink);
                stringBuilder.append("\n");
            }
            return stringBuilder.toString();
        }
        return null;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        //inflater.inflate(R.menu.menu_detail, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            getActivity().finish();
            return true;
        }

        if (id == R.id.action_star) {
            shareText(getActivity(), "");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onStop() {
        super.onStop();
        mWebView.clearCache(true);
    }

    private void shareText(Activity activity, String shareText) {

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,
                shareText);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(Intent.createChooser(intent, activity.getResources().getString(R
                .string.app_name)));
    }
}