text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if UNITY_2020_2_OR_NEWER
using UnityEditor.AssetImporters;
#else
using UnityEditor.Experimental.AssetImporters;
#endif // UNITY_2020_2_OR_NEWER

namespace Microsoft.MixedReality.Toolkit.Utilities.Gltf.Serialization.Editor
{
#if !MRTK_GLTF_IMPORTER_OFF
    [ScriptedImporter(1, "glb")]
#endif // !MRTK_GLTF_IMPORTER_OFF
    public class GlbAssetImporter : ScriptedImporter
    {
        public override void OnImportAsset(AssetImportContext context)
        {
            GltfEditorImporter.OnImportGltfAsset(context);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
function getrootdir
{
    local TOPFILE="build/Makefile"
    if [[ -n "$ROOTDIR" && -f "$ROOTDIR/$TOPFILE" ]]; then
        # The following circumlocution ensures we remove symlinks from ROOTDIR.
        (cd "${ROOTDIR}"; PWD= /bin/pwd)
    else
        if [[ -f "${TOPFILE}" ]]; then
            # The following circumlocution (repeated below as well) ensures
            # that we record the true directory name and not one that is
            # faked up with symlink names.
            PWD= /bin/pwd
        else
            local HERE="${PWD}"
            local R=
            while [ \( ! \( -f "${TOPFILE}" \) \) -a \( "${PWD}" != "/" \) ]; do
                \cd ..
                R=`PWD= /bin/pwd -P`
            done
            \cd "${HERE}"
            if [ -f "${R}/${TOPFILE}" ]; then
                echo "${R}"
            fi
        fi
    fi
}

export ROOTDIR="$(getrootdir)"
export OUT="${ROOTDIR}/out"
export CACHE="${ROOTDIR}/cache"

export RUSTDIR="${CACHE}/rust_toolchain"
export CARGO_HOME="${RUSTDIR}"
export RUSTUP_HOME="${RUSTDIR}"

export PATH="${HOME}/.local/bin:${PATH}"
export PATH="${CACHE}/toolchain/bin:${PATH}"
export PATH="${RUSTDIR}/bin:${PATH}"
export PATH="${ROOTDIR}/scripts:${PATH}"
export PATH="${CACHE}/renode:${PATH}"
export PATH="${OUT}/host/qemu/riscv32-softmmu:${PATH}"
export PATH="${OUT}/host/flatbuffers/bin:${PATH}"
export PATH="${OUT}/host/verilator/bin:${PATH}"
export PATH="${OUT}/host/verible/bin:${PATH}"

export KATA_RUST_VERSION="nightly-2021-11-05"
export RENODE_PORT=1234

export PYTHONPATH="${PYTHONPATH}:${ROOTDIR}/cicd/"

function renode
{
    "${CACHE}/renode/renode" "$@"
}

function iss
{
    (cd "${ROOTDIR}" && python3 "${ROOTDIR}/scripts/quick_sim.py" "$@")
}

function qemu_sim_springbok
{
    local file="${1}"; shift
    (cd "${ROOTDIR}" && qemu-system-riscv32 -M springbok -nographic -d springbok -device loader,file="${file}" "$@")
}

function sim_springbok
{
    local command="start;"
    if [[ "$2" == "debug" ]]; then
        command="machine StartGdbServer 3333;"
    fi
    local bin_file=$(realpath $1)
    (cd "${ROOTDIR}" && renode -e "\$bin=@${bin_file}; i @sim/config/springbok.resc; \
    ${command} sysbus.vec_controlblock WriteDoubleWord 0xc 0" \
        --disable-xwt --console)

}

function get-groups
{
    git --git-dir="${ROOTDIR}/.repo/manifests.git" config \
        --get manifest.groups
}

function m
{
    (cd "${ROOTDIR}" && make -f "${ROOTDIR}/build/Makefile" "$@")
    return $?
}

function _hmm
{
    local targetname="$1"; shift
    targetname="${targetname}" gawk -f "${ROOTDIR}/build/helpmemake.awk" \
              "${ROOTDIR}/build/Makefile" "${ROOTDIR}"/build/*.mk
}

function hmm
{
    local usage="Usage: hmm [-h] [-l] <targetname>"
    local long=""
    local args=$(getopt hl $*)
    set -- $args

    for i; do
        case "$1" in
            -l)
                long=1
                shift 1
                ;;

            --)
                shift
                break
                ;;

            -h|*)
                echo $usage >/dev/stderr
                return 1
                ;;
        esac
    done

    local targetname="${1}"; shift

    if [[ "${targetname}" ]]; then
        _hmm "${targetname}"
        return 0
    fi

    if [[ -z "${long}" ]]; then
        _hmm | fmt --width=80
    else
        _hmm
    fi
}

function safe-abandon
{
    local branch="${1}"; shift

    if [[ -z "${branch}" ]]; then
        echo "Usage: safe-abandon <branchname>"
        echo
        echo "Abandons a repo branch in the current project only."
        echo "This is much safer than using the actual 'repo abandon'"
        echo "command, since it won't globally revert branches across"
        echo "the entire project space."
        echo
        return 1
    fi

    repo abandon "${branch}" .
}

if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then
    unset JUMP_TARGETS
    declare -Ax JUMP_TARGETS
    JUMP_TARGETS[.]="."
    JUMP_TARGETS[top]="${ROOTDIR}"
    JUMP_TARGETS[rootdir]="${ROOTDIR}"
    JUMP_TARGETS[out]="${OUT}"
    JUMP_TARGETS[build]="${ROOTDIR}/build"
    JUMP_TARGETS[doc]="${ROOTDIR}/doc"

    function j
    {
        local target="$1"; shift
        local splitpath=(${target//\// })
        local subpath=""

        if [[ -z "${target}" ]]; then
            cd "${ROOTDIR}"
            return 0
        fi

        if [[ -z "${JUMP_TARGETS[$target]}" ]]; then
            target="${splitpath[0]}"
            subpath="${splitpath[@]:1}"
        fi

        if [[ -z "${JUMP_TARGETS[$target]}" ]]; then
            echo "Jump targets are:"
            echo "${!JUMP_TARGETS[@]}"
            return 1
        fi

        cd "${JUMP_TARGETS[$target]}"

        if [[ ! -z "${subpath}" ]]; then
            cd "${subpath}"
        fi
    }

    if builtin complete >/dev/null 2>/dev/null; then
        function _j_targets
        {
            echo "${!JUMP_TARGETS[@]}"
        }

        function _j
        {
            local cur="${COMP_WORDS[COMP_CWORD]}"
            COMPREPLY=()
            if [[ "${COMP_CWORD}" -eq 1 ]]; then
                COMPREPLY=( $(compgen -W "$(_j_targets)" $cur) )
            fi
        }

        complete -F _j j

        function _complete_build_targets
        {
            local cur="${COMP_WORDS[COMP_CWORD]}"
            COMPREPLY=()
            if [[ "${COMP_CWORD}" -eq 1 ]]; then
                COMPREPLY=( $(compgen -W "$(hmm -l)" $cur) )
            fi
        }

        complete -F _complete_build_targets m
        complete -F _complete_build_targets hmm
    fi
fi
echo "========================================"
echo ROOTDIR="${ROOTDIR}"
echo OUT="${OUT}"
echo "========================================"
echo
echo Type \'m \[target\]\' to build.
echo
echo "Targets available are:"
echo
hmm
echo
echo "To get more information on a target, use 'hmm [target]'"
echo

if [[ ! -d "${RUSTDIR}" ]] ||
   [[ ! -d "${ROOTDIR}/cache/toolchain" ]] ||
   [[ ! -d "${ROOTDIR}/cache/toolchain_iree_rv32imf" ]] ||
   [[ ! -d "${ROOTDIR}/cache/renode" ]]; then
    echo
    echo '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
    echo You have missing tools. Please run \'m prereqs\' followed
    echo by \'m tools\' to install them.
    echo '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
    echo
    [[ -d "${RUSTDIR}" ]] || echo "${RUSTDIR} is missing!"
    [[ -d "${ROOTDIR}/cache/toolchain" ]] || echo "${ROOTDIR}/cache/toolchain is missing"
    [[ -d "${ROOTDIR}/cache/toolchain_iree_rv32imf" ]] || echo "${ROOTDIR}/cache/toolchain_iree_rv32imf is missing!"
    [[ -d "${ROOTDIR}/cache/renode" ]] || echo "${ROOTDIR}/cache/renode is missing!"
fi


text:
Dieses Dokument beschreibt unsere Sicherheitsrichtlinien für die Codebases und Plattformen, die wir betreiben, und wie du Schwachstellen melden kannst.

## Eine Schwachstelle melden

Wenn du glaubst, dass du eine Schwachstelle gefunden hast, _bitte melde sie verantwortungsvoll_. Erstelle kein GitHub-Issue für Sicherheitsprobleme. Schicke stattdessen bitte eine E-Mail an `security@freecodecamp.org` und wir werden uns sofort darum kümmern.

Stelle sicher, dass du die **neueste**, **stabilste (stable)** und **aktuellste** Version des Betriebssystems und des Webbrowsers verwendest, die dir auf deinem Computer zur Verfügung stehen.

Wir freuen uns über jede verantwortungsvolle Offenlegung von Schwachstellen, die die Integrität unserer Plattformen und Nutzer/innen beeinträchtigen könnten.

Wenn du eine Schwachstelle meldest, werden wir sie untersuchen und sicherstellen, dass es sich nicht um einen Fehlalarm handelt. Wir werden uns bei dir melden, wenn wir noch Details klären müssen. Du kannst für jedes Problem, das du findest, eine gesonderte Mitteilung machen.

Im Moment bieten wir zwar keine Belohnungen oder Swags an, aber wir nehmen deinen Namen gerne in unsere [Hall of Fame](https://contribute.freecodecamp.org/#/security-hall-of-fame)-Liste auf, vorausgesetzt, die Meldungen betreffen keine geringfügigen Probleme.

Wir betrachten die Verwendung von Online-Tools und Hilfsprogrammen zur Meldung von Problemen mit SPF- und DKIM-Einstellungen, SSL-Server-Tests usw. als ["beg bounties"](https://www.troyhunt.com/beg-bounties/) und werden auf diese Meldungen nicht reagieren.

## Plattformen & Codebasen

Hier ist eine Liste der Plattformen und Codebasen, für die wir Meldungen annehmen:

### Lernplattform

| Version     | Branch         | wird unterstützt | aktive Website           |
| ----------- | -------------- | ---------------- | ------------------------ |
| production  | `prod-current` | Ja               | `freecodecamp.org/learn` |
| staging     | `prod-staging` | Ja               | `freecodecamp.dev/learn` |
| development | `main`         | Nein             |                          |

### Plattform für Publikationen

| Version    | wird unterstützt | aktive Website                           |
| ---------- | ---------------- | ---------------------------------------- |
| production | Ja               | `freecodecamp.org/news`                  |
| localized  | Ja               | `freecodecamp.org/<language>/news` |

### Mobile App

| Version    | wird unterstützt | aktive Website                                                   |
| ---------- | ---------------- | ---------------------------------------------------------------- |
| production | Ja               | `https://play.google.com/store/apps/details?id=org.freecodecamp` |

Außerdem nehmen wir auch Meldungen für Repositories entgegen, die auf GitHub unter der freeCodeCamp-Organisation gehostet werden.

Einige unserer Plattformen hosten wir selbst mit Open-Source-Software wie Ghost & Discourse. Wenn du eine Sicherheitslücke meldest, stelle bitte sicher, dass es sich nicht um einen Fehler in der Originalsoftware handelt.


text:
package edu.hypower.gatech.phidget;

import edu.hypower.gatech.phidget.comm.ChannelNames;
import io.vertx.core.*;

public class DataCollectionVerticle extends AbstractVerticle {

	@Override
	public void start(Future<Void> startFuture) throws Exception {
		super.start(startFuture);

		vertx.eventBus().consumer(ChannelNames.DATA_COLLECTOR_RECV, message -> {
			System.out.println("Received data " + message.body());
		});

		System.out.println(this.getClass().getName() + " started.");
	}

	@Override
	public void stop() throws Exception {
		super.stop();
		System.out.println(this.getClass().getName() + " stopped.");
	}

}


text:
001
032
033    package com.jeantessier.metrics;
034
035    import java.util.*;
036
037    public class MetricsComparator implements Comparator<Metrics> {
038        public static final int DESCENDING = -1;
039        public static final int ASCENDING  =  1;
040
041        private String name;
042        private int    direction;
043        private int    dispose;
044
045        public MetricsComparator(String name) {
046            this(name, StatisticalMeasurement.DISPOSE_IGNORE);
047        }
048
049        public MetricsComparator(String name, int dispose) {
050            setName(name);
051            setDispose(dispose);
052            setDirection(ASCENDING);
053        }
054
055        public String getName() {
056            return name;
057        }
058
059        public void setName(String name) {
060            this.name = name;
061        }
062
063        public int getDirection() {
064            return direction;
065        }
066
067        public void setDirection(int direction) {
068            this.direction = direction;
069        }
070
071        public int getDispose() {
072            return dispose;
073        }
074
075        public void setDispose(int dispose) {
076            this.dispose = dispose;
077        }
078
079        public void sortOn(String name, int dispose) {
080            if (name.equals(this.name) && dispose == this.dispose) {
081                reverse();
082            } else {
083                setName(name);
084                setDirection(ASCENDING);
085                setDispose(dispose);
086            }
087        }
088
089        public void reverse() {
090            direction *= -1;
091        }
092
093        public int compare(Metrics metrics1, Metrics metrics2) {
094            int result;
095
096            if ("name".equals(name)) {
097                result = metrics1.getName().compareTo(metrics2.getName());
098            } else {
099                Measurement m1 = metrics1.getMeasurement(name);
100                Measurement m2 = metrics2.getMeasurement(name);
101
102                if (m1 == null && m2 != null) {
103                    result = -1;
104                } else if (m1 != null && m2 == null) {
105                    result = 1;
106                } else if (m1 == m2) {
107                    result = 0;
108                } else {
109                    double v1 = extractValue(m1);
110                    double v2 = extractValue(m2);
111
112                    if (Double.isNaN(v1) && !Double.isNaN(v2)) {
113                        result = 1 * getDirection();
114                    } else if (!Double.isNaN(v1) && Double.isNaN(v2)) {
115                        result = -1 * getDirection();
116                    } else if (Double.isNaN(v1) && Double.isNaN(v2)) {
117                        result = 0;
118                    } else if (v1 < v2) {
119                        result = -1;
120                    } else if (v1 > v2) {
121                        result = 1;
122                    } else {
123                        result = 0;
124                    }
125                }
126            }
127
128            result *= getDirection();
129
130            return result;
131        }
132
133        private double extractValue(Measurement m) {
134            double result = Double.NaN;
135
136            if (m instanceof StatisticalMeasurement) {
137                StatisticalMeasurement sm = (StatisticalMeasurement) m;
138                switch (getDispose()) {
139                    case StatisticalMeasurement.DISPOSE_MINIMUM:
140                        result = sm.getMinimum();
141                        break;
142
143                    case StatisticalMeasurement.DISPOSE_MEDIAN:
144                        result = sm.getMedian();
145                        break;
146
147                    case StatisticalMeasurement.DISPOSE_AVERAGE:
148                        result = sm.getAverage();
149                        break;
150
151                    case StatisticalMeasurement.DISPOSE_STANDARD_DEVIATION:
152                        result = sm.getStandardDeviation();
153                        break;
154
155                    case StatisticalMeasurement.DISPOSE_MAXIMUM:
156                        result = sm.getMaximum();
157                        break;
158
159                    case StatisticalMeasurement.DISPOSE_SUM:
160                        result = sm.getSum();
161                        break;
162
163                    case StatisticalMeasurement.DISPOSE_NB_DATA_POINTS:
164                        result = sm.getNbDataPoints();
165                        break;
166
167                    default:
168                    case StatisticalMeasurement.DISPOSE_IGNORE:
169                        break;
170                }
171            } else {
172                result = m.getValue().doubleValue();
173            }
174
175            return result;
176        }
177    }


text:
package org.apache.beehive.controls.runtime.generator.apt;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorFactory;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;

public class ControlSecondaryAnnotationProcessorFactory implements AnnotationProcessorFactory
{
    private static final Collection<String> _supportedAnnotations =
            Collections.unmodifiableCollection(
                Arrays.asList(new String[] {
                    java.lang.annotation.Target.class.getName(),
                    java.lang.annotation.Retention.class.getName(),
                    org.apache.beehive.controls.api.bean.ExternalPropertySets.class.getName(),
                    org.apache.beehive.controls.api.bean.ControlReferences.class.getName(),
                    org.apache.beehive.controls.api.bean.Threading.class.getName(),
                    org.apache.beehive.controls.api.context.Context.class.getName(),
                    org.apache.beehive.controls.api.events.Client.class.getName(),
                    org.apache.beehive.controls.api.events.EventHandler.class.getName(),
                    org.apache.beehive.controls.api.events.EventSet.class.getName(),
                    org.apache.beehive.controls.api.packaging.BeanInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.EventSetInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.FeatureAttribute.class.getName(),
                    org.apache.beehive.controls.api.packaging.FeatureInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.ManifestAttribute.class.getName(),
                    org.apache.beehive.controls.api.packaging.ManifestAttributes.class.getName(),
                    org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(),
                    org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(),
                    org.apache.beehive.controls.api.properties.BaseProperties.class.getName(),
                    org.apache.beehive.controls.api.versioning.Version.class.getName(),
                    org.apache.beehive.controls.api.versioning.VersionRequired.class.getName(),
                    org.apache.beehive.controls.api.versioning.VersionSupported.class.getName()
                    }));

    private static final Collection<String> _supportedOptions =
            Collections.unmodifiableCollection(
                Arrays.asList(new String[] {
                    "-AcontrolGenerator",   // sets CodeGenerator class
                    }));

    public Collection<String> supportedOptions()
    {
        return _supportedOptions;
    }

    public Collection<String> supportedAnnotationTypes()
    {
        return _supportedAnnotations;
    }

    public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds,
                                               AnnotationProcessorEnvironment env)
    {
        return new ControlSecondaryAnnotationProcessor(atds, env);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2017 By_syk

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

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

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

<resources>

    <!-- Corresponding app name list of all icons in /res/drawable-nodpi/ -->
    <!-- Just KEEP IT EMPTY BUT DO NOT DELETE IT if you do not want to collect app name list. -->
    <string-array name="icon_labels">
        <!-- A -->
        <!-- B -->
        <!-- C -->
        <item>日历</item>
        <!-- D -->
        <!-- E -->
        <!-- F -->
        <!-- G -->
        <!-- H -->
        <!-- I -->
        <!-- J -->
        <!-- K -->
        <!-- L -->
        <!-- M -->
        <!-- N -->
        <item>NanoIconPack (by @Childish)</item>
        <item>NanoIconPack (by @Markuss)</item>
        <item>NanoIconPack (by @pandecheng)</item>
        <item>NanoIconPack (by @atony)</item>
        <item>NanoIconPack (by @可以and不行)</item>
        <item>NanoIconPack (by @ArchieLiu)</item>
        <item>NanoIconPack (by @lnm011223)</item>
        <!-- O -->
        <!-- P -->
        <!-- Q -->
        <!-- R -->
        <!-- S -->
        <!-- T -->
        <!-- U -->
        <!-- V -->
        <!-- W -->
        <!-- X -->
        <!-- Y -->
        <!-- Z -->
    </string-array>

</resources>


text:
using System;
using System.Linq;

using Microsoft.Cci.Differs;
using Microsoft.Cci.Mappings;

namespace Microsoft.Cci.Filters
{
    public sealed class CommonTypesMappingDifferenceFilter : IMappingDifferenceFilter
    {
        private readonly IMappingDifferenceFilter _baseFilter;
        private readonly bool _includeAddedTypes;
        private readonly bool _includeRemovedTypes;

        public CommonTypesMappingDifferenceFilter(IMappingDifferenceFilter baseFilter, bool includeAddedTypes, bool includeRemovedTypes)
        {
            _baseFilter = baseFilter;
            _includeAddedTypes = includeAddedTypes;
            _includeRemovedTypes = includeRemovedTypes;
        }

        public bool Include(AssemblyMapping assembly)
        {
            return _baseFilter.Include(assembly) && assembly.Namespaces.Any(Include);
        }

        public bool Include(NamespaceMapping ns)
        {
            return _baseFilter.Include(ns) && ns.Types.Any(Include);
        }

        public bool Include(TypeMapping type)
        {
            var isAdded = type.Difference == DifferenceType.Added;
            var isRemoved = type.Difference == DifferenceType.Removed;
            var onBothSides = !isAdded && !isRemoved;
            var include = onBothSides ||
                          isAdded && _includeAddedTypes ||
                          isRemoved && _includeRemovedTypes;
            return _baseFilter.Include(type) && include;
        }

        public bool Include(MemberMapping member)
        {
            return _baseFilter.Include(member) && Include(member.ContainingType);
        }

        public bool Include(DifferenceType difference)
        {
            return _baseFilter.Include(difference);
        }
    }
}


text:
<?php

namespace Multidimensional\Cakephpify\Test\TestCase\Shell\Helper;

use Cake\Console\ConsoleIo;
use Cake\TestSuite\Stub\ConsoleOutput;
use Cake\TestSuite\TestCase;
use Multidimensional\Cakephpify\Shell\Helper\HeaderHelper;

class HeaderHelperTest extends TestCase
{

    /**
     * @var ConsoleOutput
     */
    public $stub;

    /**
     * @var ConsoleIo
     */

    public $io;

    /**
     * @var HeaderHelper
     */
    public $helper;

    /**
     * setUp method
     *
     * @return void
     */

    public function setUp()
    {
        parent::setUp();

        $this->stub = new ConsoleOutput();
        $this->io = new ConsoleIo($this->stub);
        $this->helper = new HeaderHelper($this->io);
    }

    public function testOutput()
    {
        $this->markTestIncomplete('Not implemented yet.');
        /*$this->helper->output();
        $expected = [

        ];
        $this->assertEquals($expected, $this->stub->messages());*/
    }
}


text:
<form onsubmit="return false;">

找回密码

    邮箱:
    <input type="email" id="number" ng-blur="checkTelNumber()" class="form-control" placeholder="请输入您的邮箱地址"/>
    验证码:

    <input type="number" id="checkInput" placeholder="请输入验证码" ng-blur="catchMsg()"/>
    <input type="button" id="findPwdBtn" value="免费获取验证码" ng-click="setTime()" />

    <button class="btn btn-primary clickBtn" style="margin: 5px 0 5px 100px" ng-click="clickToBlock()">确定</button>
    设置密码
</form>

    <form onsubmit="return false;">

设置密码

        密码:
        <input id="pwd" type="password" ng-blur="getPwd()" class="form-control" placeholder="请输入4-16位密码"/>
        确认密码:
        <input type="password" id="checkPwd" ng-blur="checkPwdAgain()" class="form-control" placeholder="请确认密码"/>
        <button class="btn" ng-click="rewrite()">重置</button>
        <button class="btn btn-primary"  ng-click="clickToRegister()">保存</button>
    </form>


text:
published: true
layout: posts
title: "OpenSSL's Enumerated SSL/TLS Cipher Suites"
---

[Mapping OpenSSL cipher suite names to RFC names](https://testssl.sh/openssl-rfc.mappping.html)


text:
	vimeoData.video = {};

	vimeoData.video.url = "video";

	// makes a ajax petition and returns a jqXHR promise
	vimeoData.video.byId = function(id){
		var url = vimeoData.makeUrl(this.url,id,'json');
		return vimeoData.$getJson(url);
	};


text:
package org.anc.lapps.stanford;

import org.anc.io.UTF8Reader;
import org.anc.resource.ResourceLoader;
import org.lappsgrid.api.WebService;
import org.lappsgrid.discriminator.*;
import org.lappsgrid.annotations.CommonMetadata;
import org.lappsgrid.metadata.ServiceMetadata;
import org.lappsgrid.serialization.Data;
import org.lappsgrid.serialization.Error;
import org.lappsgrid.serialization.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static org.lappsgrid.discriminator.Discriminators.Uri;

/**
 * @author Keith Suderman
 */
@CommonMetadata(
	vendor = "http://www.anc.org",
	license = "apache2",
	format = "lif",
	language = "en"
)
public abstract class AbstractStanfordService implements WebService
{
	private static final Logger logger = LoggerFactory.getLogger(AbstractStanfordService.class);

   protected String metadata;

   public AbstractStanfordService(Class<?> serviceClass)
   {
      try
      {
         loadMetadata(serviceClass);
      }
      catch (IOException ignore)
      {
         // The only IOException not handled by loadMetadata is the one
         // thrown when closing the InputStream. All other IOExceptions
         // have already been logged.
//         logger.error("Unable to load metadata for {}", serviceClass.getName(), e);
      }
   }

   protected boolean isError(String discriminator)
   {
      return Uri.ERROR.equals(discriminator);
   }

   protected String createError(String message)
   {
      return new Error(message).asPrettyJson();
   }

   private InputStream openStream(Class<?> serviceClass)
   {
      String resourceName = "metadata/" + serviceClass.getName() + ".json";
//      InputStream inputStream = this.getClass().getResourceAsStream(resourceName);
      ClassLoader loader = AbstractStanfordService.class.getClassLoader();
      InputStream inputStream = loader.getResourceAsStream(resourceName);
      if (inputStream != null)
      {
         return inputStream;
      }
      return null;
//      return this.getClass().getClass().getResourceAsStream("/" + resourceName);
   }

   private void loadMetadata(Class<?> serviceClass) throws IOException
   {
//      ClassLoader loader = ResourceLoader.getClassLoader();
//      String resourceName = "/metadata/" + serviceClass.getName() + ".json";
//      InputStream inputStream = this.getClass().getResourceAsStream(resourceName);
      InputStream inputStream = openStream(serviceClass);
      if (inputStream == null)
      {
			String message = "Unable to load resource for " + serviceClass.getName();
			logger.error(message);
         throw new IOException(message);
      }

      UTF8Reader reader = null;
      try
      {
         reader = new UTF8Reader(inputStream);
         String content = reader.readString();
         ServiceMetadata metadata = Serializer.parse(content, ServiceMetadata.class);
         Data<ServiceMetadata> data = new Data<>(Uri.META, metadata);
         this.metadata = data.asJson();
			logger.info("Loaded metadata.");
//         System.out.println(content);
      }
      catch (IOException e)
      {
			String message = "Unable to load metadata for " + serviceClass.getName();
         logger.error(message, e);
         metadata = Serializer.toPrettyJson(new Error(message));
         throw e;
      }
      finally
      {
         if (reader != null)
         {
            reader.close();
         }
      }
   }

   public String getMetadata()
   {
      return metadata;
   }
}


text:
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"syscall"
	"time"

	"golang.org/x/crypto/ssh/terminal"

	log "github.com/Sirupsen/logrus"
	"github.com/urfave/cli"
	"github.com/vrischmann/jsonutil"

	"github.com/intelsdi-x/snap/control"
	"github.com/intelsdi-x/snap/core/serror"
	"github.com/intelsdi-x/snap/mgmt/rest"
	"github.com/intelsdi-x/snap/mgmt/tribe"
	"github.com/intelsdi-x/snap/mgmt/tribe/agreement"
	"github.com/intelsdi-x/snap/pkg/cfgfile"
	"github.com/intelsdi-x/snap/scheduler"
)

var (
	flMaxProcs = cli.StringFlag{
		Name:   "max-procs, c",
		Usage:  fmt.Sprintf("Set max cores to use for Snap Agent (default: %v)", defaultGoMaxProcs),
		EnvVar: "GOMAXPROCS",
	}
	// plugin
	flLogPath = cli.StringFlag{
		Name:   "log-path, o",
		Usage:  "Path for logs. Empty path logs to stdout.",
		EnvVar: "SNAP_LOG_PATH",
	}
	flLogTruncate = cli.BoolFlag{
		Name:  "log-truncate",
		Usage: "Log file truncating mode. Default is false => append (true => truncate).",
	}
	flLogColors = cli.BoolTFlag{
		Name:  "log-colors",
		Usage: "Log file coloring mode. Default is true => colored (--log-colors=false => no colors).",
	}
	flLogLevel = cli.StringFlag{
		Name:   "log-level, l",
		Usage:  fmt.Sprintf("1-5 (Debug, Info, Warning, Error, Fatal; default: %v)", defaultLogLevel),
		EnvVar: "SNAP_LOG_LEVEL",
	}
	flConfig = cli.StringFlag{
		Name:   "config",
		Usage:  "A path to a config file",
		EnvVar: "SNAP_CONFIG_PATH",
	}

	gitversion  string
	coreModules []coreModule

	// used to save a reference to the CLi App
	cliApp *cli.App

	// log levels
	l = map[int]string{
		1: "debug",
		2: "info",
		3: "warning",
		4: "error",
		5: "fatal",
	}
	// plugin trust levels
	t = map[int]string{
		0: "disabled",
		1: "enabled",
		2: "warning",
	}
)

// default configuration values
const (
	defaultLogLevel    int    = 3
	defaultGoMaxProcs  int    = 1
	defaultLogPath     string = ""
	defaultLogTruncate bool   = false
	defaultLogColors   bool   = true
	defaultConfigPath  string = "/etc/snap/snapteld.conf"
)

// holds the configuration passed in through the SNAP config file
//   Note: if this struct is modified, then the switch statement in the
//         UnmarshalJSON method in this same file needs to be modified to
//         match the field mapping that is defined here
type Config struct {
	LogLevel    int               `json:"log_level,omitempty"yaml:"log_level,omitempty"`
	GoMaxProcs  int               `json:"gomaxprocs,omitempty"yaml:"gomaxprocs,omitempty"`
	LogPath     string            `json:"log_path,omitempty"yaml:"log_path,omitempty"`
	LogTruncate bool              `json:"log_truncate,omitempty"yaml:"log_truncate,omitempty"`
	LogColors   bool              `json:"log_colors,omitempty"yaml:"log_colors,omitempty"`
	Control     *control.Config   `json:"control,omitempty"yaml:"control,omitempty"`
	Scheduler   *scheduler.Config `json:"scheduler,omitempty"yaml:"scheduler,omitempty"`
	RestAPI     *rest.Config      `json:"restapi,omitempty"yaml:"restapi,omitempty"`
	Tribe       *tribe.Config     `json:"tribe,omitempty"yaml:"tribe,omitempty"`
}

const (
	CONFIG_CONSTRAINTS = `{
		"$schema": "http://json-schema.org/draft-04/schema#",
		"title": "snapteld global config schema",
		"type": ["object", "null"],
		"properties": {
			"log_level": {
				"description": "log verbosity level for snapteld. Range between 1: debug, 2: info, 3: warning, 4: error, 5: fatal",
				"type": "integer",
				"minimum": 1,
				"maximum": 5
			},
			"log_path": {
				"description": "path to log file for snapteld to use",
				"type": "string"
			},
			"log_truncate": {
				"description": "truncate log file default is false",
				"type": "boolean"
			},
			"log_colors": {
				"description": "log file colored output default is true",
				"type": "boolean"
			},
			"gomaxprocs": {
				"description": "value to be used for gomaxprocs",
				"type": "integer",
				"minimum": 1
			},
			"control": { "$ref": "#/definitions/control" },
			"scheduler": { "$ref": "#/definitions/scheduler"},
			"restapi" : { "$ref": "#/definitions/restapi"},
			"tribe": { "$ref": "#/definitions/tribe"}
		},
		"additionalProperties": false,
		"definitions": { ` +
		control.CONFIG_CONSTRAINTS + `,` +
		scheduler.CONFIG_CONSTRAINTS + `,` +
		rest.CONFIG_CONSTRAINTS + `,` +
		tribe.CONFIG_CONSTRAINTS +
		`}` +
		`}`
	logModule = "snapteld"
)

type coreModule interface {
	Start() error
	Stop()
	Name() string
}

type managesTribe interface {
	GetAgreement(name string) (*agreement.Agreement, serror.SnapError)
	GetAgreements() map[string]*agreement.Agreement
	AddAgreement(name string) serror.SnapError
	RemoveAgreement(name string) serror.SnapError
	JoinAgreement(agreementName, memberName string) serror.SnapError
	LeaveAgreement(agreementName, memberName string) serror.SnapError
	GetMembers() []string
	GetMember(name string) *agreement.Member
}

func main() {
	// Add a check to see if gitversion is blank from the build process
	if gitversion == "" {
		gitversion = "unknown"
	}

	cliApp = cli.NewApp()
	cliApp.Name = "snapteld"
	cliApp.Version = gitversion
	cliApp.Usage = "The open telemetry framework"
	cliApp.Flags = []cli.Flag{
		flLogLevel,
		flLogPath,
		flLogTruncate,
		flLogColors,
		flMaxProcs,
		flConfig,
	}
	cliApp.Flags = append(cliApp.Flags, control.Flags...)
	cliApp.Flags = append(cliApp.Flags, scheduler.Flags...)
	cliApp.Flags = append(cliApp.Flags, rest.Flags...)
	cliApp.Flags = append(cliApp.Flags, tribe.Flags...)

	cliApp.Action = action

	if cliApp.Run(os.Args) != nil {
		os.Exit(1)
	}
}

func action(ctx *cli.Context) error {
	// get default configuration
	cfg := getDefaultConfig()

	// read config file
	readConfig(cfg, ctx.String("config"))

	// apply values that may have been passed from the command line
	// to the configuration that we have built so far, overriding the
	// values that may have already been set (if any) for the
	// same variables in that configuration
	applyCmdLineFlags(cfg, ctx)

	// test the resulting configuration to ensure the values it contains still pass the
	// constraints after applying the environment variables and command-line parameters;
	// if errors are found, report them and exit with a fatal error
	jb, _ := json.Marshal(cfg)
	serrs := cfgfile.ValidateSchema(CONFIG_CONSTRAINTS, string(jb))
	if serrs != nil {
		for _, serr := range serrs {
			log.WithFields(serr.Fields()).Error(serr.Error())
		}
		log.Fatal("Errors found after applying command-line flags")
	}

	// If logPath is set, we verify the logPath and set it so that all logging
	// goes to the log file instead of stdout.
	logPath := cfg.LogPath
	if logPath != "" {
		f, err := os.Stat(logPath)
		if err != nil {
			log.Fatal(err)
		}
		if !f.IsDir() {
			log.Fatal("log path provided must be a directory")
		}
		aMode := os.O_APPEND
		if cfg.LogTruncate {
			aMode = os.O_TRUNC
		}
		file, err := os.OpenFile(fmt.Sprintf("%s/snapteld.log", logPath), os.O_RDWR|os.O_CREATE|aMode, 0666)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()
		log.SetOutput(file)
	}
	// Because even though github.com/Sirupsen/logrus states that
	// 'Logs the event in colors if stdout is a tty, otherwise without colors'
	// Seems like this does not work
	// Please note however that the default output format without colors is somewhat different (timestamps, ...)
	//
	// We could also restrict this command line parameter to only apply when no logpath is given
	// and forcing the coloring to off when using a file but this might not please users who like to use
	// redirect mechanisms like # snapteld -t 0 -l 1 2>&1 | tee my.log
	if !cfg.LogColors {
		log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableColors: true})
	} else {
		log.SetFormatter(&log.TextFormatter{FullTimestamp: true})
	}

	// Validate log level and trust level settings for snapteld
	validateLevelSettings(cfg.LogLevel, cfg.Control.PluginTrust)

	// Switch log level to user defined
	log.SetLevel(getLevel(cfg.LogLevel))
	log.Info("setting log level to: ", l[cfg.LogLevel])

	log.Info("Starting snapteld (version: ", gitversion, ")")

	// Set Max Processors for snapteld.
	setMaxProcs(cfg.GoMaxProcs)

	c := control.New(cfg.Control)

	coreModules = []coreModule{}

	coreModules = append(coreModules, c)
	s := scheduler.New(cfg.Scheduler)
	s.SetMetricManager(c)
	coreModules = append(coreModules, s)

	// Auth requested and not provided as part of config
	if cfg.RestAPI.Enable && cfg.RestAPI.RestAuth && cfg.RestAPI.RestAuthPassword == "" {
		fmt.Println("What password do you want to use for authentication?")
		fmt.Print("Password:")
		password, err := terminal.ReadPassword(0)
		fmt.Println()
		if err != nil {
			log.Fatal("Failed to get credentials")
		}
		cfg.RestAPI.RestAuthPassword = string(password)
	}

	var tr managesTribe
	if cfg.Tribe.Enable {
		cfg.Tribe.RestAPIPort = cfg.RestAPI.Port
		if cfg.RestAPI.RestAuth {
			cfg.Tribe.RestAPIPassword = cfg.RestAPI.RestAuthPassword
		}
		log.Info("Tribe is enabled")
		t, err := tribe.New(cfg.Tribe)
		if err != nil {
			printErrorAndExit(t.Name(), err)
		}
		c.RegisterEventHandler("tribe", t)
		t.SetPluginCatalog(c)
		s.RegisterEventHandler("tribe", t)
		t.SetTaskManager(s)
		coreModules = append(coreModules, t)
		tr = t
	}

	//Setup RESTful API if it was enabled in the configuration
	if cfg.RestAPI.Enable {
		r, err := rest.New(cfg.RestAPI)
		if err != nil {
			log.Fatal(err)
		}
		r.BindMetricManager(c)
		r.BindConfigManager(c.Config)
		r.BindTaskManager(s)

		//Rest Authentication
		if cfg.RestAPI.RestAuth {
			log.Info("REST API authentication is enabled")
			r.SetAPIAuth(cfg.RestAPI.RestAuth)
			log.Info("REST API authentication password is set")
			r.SetAPIAuthPwd(cfg.RestAPI.RestAuthPassword)
			if !cfg.RestAPI.HTTPS {
				log.Warning("Using REST API authentication without HTTPS enabled.")
			}
		}

		if tr != nil {
			r.BindTribeManager(tr)
		}
		go monitorErrors(r.Err())
		coreModules = append(coreModules, r)
		log.Info("REST API is enabled")
	} else {
		log.Info("REST API is disabled")
	}

	// Set interrupt handling so we can either restart the app on a SIGHUP or
	// die gracefully when an interrupt, kill, etc. are received
	startInterruptHandling(coreModules...)

	// Start our modules
	var started []coreModule
	for _, m := range coreModules {
		if err := startModule(m); err != nil {
			for _, m := range started {
				m.Stop()
			}
			printErrorAndExit(m.Name(), err)
		}
		started = append(started, m)
	}

	// Plugin Trust
	c.SetPluginTrustLevel(cfg.Control.PluginTrust)
	log.Info("setting plugin trust level to: ", t[cfg.Control.PluginTrust])
	// Keyring checking for trust levels 1 and 2
	if cfg.Control.PluginTrust > 0 {
		keyrings := filepath.SplitList(cfg.Control.KeyringPaths)
		if len(keyrings) == 0 {
			log.WithFields(
				log.Fields{
					"block":   "main",
					"_module": logModule,
				}).Fatal("need keyring file when trust is on (--keyring-file or -k)")
		}
		for _, k := range keyrings {
			keyringPath, err := filepath.Abs(k)
			if err != nil {
				log.WithFields(
					log.Fields{
						"block":       "main",
						"_module":     logModule,
						"error":       err.Error(),
						"keyringPath": keyringPath,
					}).Fatal("Unable to determine absolute path to keyring file")
			}
			f, err := os.Stat(keyringPath)
			if err != nil {
				log.WithFields(
					log.Fields{
						"block":       "main",
						"_module":     logModule,
						"error":       err.Error(),
						"keyringPath": keyringPath,
					}).Fatal("bad keyring file")
			}
			if f.IsDir() {
				log.Info("Adding keyrings from: ", keyringPath)
				files, err := ioutil.ReadDir(keyringPath)
				if err != nil {
					log.WithFields(
						log.Fields{
							"_block":      "main",
							"_module":     logModule,
							"error":       err.Error(),
							"keyringPath": keyringPath,
						}).Fatal(err)
				}
				if len(files) == 0 {
					log.Fatal(fmt.Sprintf("given keyring path [%s] is an empty directory!", keyringPath))
				}
				for _, keyringFile := range files {
					if keyringFile.IsDir() {
						continue
					}
					if strings.HasSuffix(keyringFile.Name(), ".gpg") || (strings.HasSuffix(keyringFile.Name(), ".pub")) || (strings.HasSuffix(keyringFile.Name(), ".pubring")) {
						f, err := os.Open(keyringPath)
						if err != nil {
							log.WithFields(
								log.Fields{
									"block":       "main",
									"_module":     logModule,
									"error":       err.Error(),
									"keyringPath": keyringPath,
								}).Warning("unable to open keyring file. not adding to keyring path")
							continue
						}
						f.Close()
						log.Info("adding keyring file: ", keyringPath+"/"+keyringFile.Name())
						c.SetKeyringFile(keyringPath + "/" + keyringFile.Name())
					}
				}
			} else {
				f, err := os.Open(keyringPath)
				if err != nil {
					log.WithFields(
						log.Fields{
							"block":       "main",
							"_module":     logModule,
							"error":       err.Error(),
							"keyringPath": keyringPath,
						}).Fatal("unable to open keyring file.")
				}
				f.Close()
				log.Info("adding keyring file ", keyringPath)
				c.SetKeyringFile(keyringPath)
			}
		}
	}

	log.WithFields(
		log.Fields{
			"block":   "main",
			"_module": logModule,
		}).Info("snapteld started", `
                                        ss                  ss
	                             odyssyhhyo         oyhysshhoyo
                                 ddddyssyyysssssyyyyyyyssssyyysssyhy+-
                           ssssssooosyhhysssyyyyyyyyyyyyyyyyyyyyyyyyyyyyssyhh+.
                          ssss lhyssssssyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyssydo
                sssssssssshhhhs lsyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyshh.
           ssyyyysssssssssssyhdo syyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyd.
       syyyyyyyyhhyyyyyyyyyyyyhdo syyyyyyyyyyyyydddhyyyyyyyyyyyyyhhhyyyyyyyyyyyyhh
     ssyyyyyyyh  hhyyyyyyyyyyyyhdo syyyyyyyyyyyddyddddhhhhhhhhdddhhddyyyyyyyyyyyydo
     ddyyyyyyh |  hyyyyyyyyyyyyydds syyyyyyyhhdhyyyhhhhhhhhhhyyyyyyhhdhyyyyyyyyyyym+
     dhyyyyyyyhhhhyyyyyyyyyyyyyyhmds shyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyydyyl
     dhddhyyyyyyhdhyyyyyyyyyyyyyydhmo yhyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyhdhsh
     dhyyhysshhdmdhyyyyyyyyyyyyyyhhdh  hhyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyhhdyoohmh ylo
      yy       dmyyyyyyyyyyyyyyyyhhhm  odhyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyhdhsoshdyyhdddy ylo
            odhhyyyyyyyyyyyyyyyyyyhhdy  oyhhhyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyhhmhyhdhhyyyyyhddoyddy ylo
           dddhhyyyyyyyyyyyyyyyhhhyhhdhs ooosydhhhhyyyyyyyyyyyyyyyyyyyyhhhhhyso+oymyyyyyyyyyyyhhddydmmyys
             ohdyyyyyyyyyyyyyyyhdhyyhhhddyoooohhhhhhhhhhhhhhhhhhhhhdhhyysooosyhhhhhyhhhhhhyyyhyyyhhhhddyy
                dyhyyyyyyyyyyyyydhyyyyyhhdddoooooooooooooooooooooooyysyyhddddhhyyyyydmdddddddmmddddhyyy
               dmmmmoNddddddmddhhhhyyyyyhhhdddddddhhhhhhhhhdddddddddhhhyyyyyyyyyyhNmmmooooooooyyy
                     Nhhhhhhhdmmddmhyyyyyyyyyhhhhhhhhhhhhhhhhhhhhyyyyyyyyyyyyyyyhhm
                     NhhhhhhhhhdmyhdyyyyyyyyyyyyhyyyyyyyyyyyyyyyhhhdhyyyyyyyyyyyhhN
                     NhyyyyyyyyyN dmyyyyyyyyyyhdmdhhhhhhhhhhdhhmmmmN NyyyyyyyyyyhhN
                     NhyyyyyyyyyN  Nyyyyyyyyyhhm               NmddmH Nyyyyyyyyyhdm
       .d8888b.      dmomomommmmh  dhhhhhhyyhhmh               NddddmH Nyyyyyyyyhdh
      d88P  Y88b                   dmomomommmmmh                dmomoH dmomomommmmh
      Y88b.
      "Y888b.   88888b.   8888b.  88888b.
         "Y88b. 888 "88b     "88b 888 "88b
           "888 888  888 .d888888 888  888
     Y88b  d88P 888  888 888  888 888 d88P
      "Y8888P"  888  888 "Y888888 88888P"
                                  888
                                  888
                                  888      `)

	select {} //run forever and ever
}

// get the default snapteld configuration
func getDefaultConfig() *Config {
	return &Config{
		LogLevel:    defaultLogLevel,
		GoMaxProcs:  defaultGoMaxProcs,
		LogPath:     defaultLogPath,
		LogTruncate: defaultLogTruncate,
		LogColors:   defaultLogColors,
		Control:     control.GetDefaultConfig(),
		Scheduler:   scheduler.GetDefaultConfig(),
		RestAPI:     rest.GetDefaultConfig(),
		Tribe:       tribe.GetDefaultConfig(),
	}
}

// Read the snapteld configuration from a configuration file
func readConfig(cfg *Config, fpath string) {
	var path string
	if !defaultConfigFile() && fpath == "" {
		return
	}
	if defaultConfigFile() && fpath == "" {
		path = defaultConfigPath
	}
	if fpath != "" {
		f, err := os.Stat(fpath)
		if err != nil {
			log.Fatal(err)
		}
		if f.IsDir() {
			log.Fatal("configuration path provided must be a file")
		}
		path = fpath
	}

	serrs := cfgfile.Read(path, &cfg, CONFIG_CONSTRAINTS)
	if serrs != nil {
		for _, serr := range serrs {
			log.WithFields(serr.Fields()).Error(serr.Error())
		}
		log.Fatal("Errors found while parsing global configuration file")
	}
}

func defaultConfigFile() bool {
	_, err := os.Stat(defaultConfigPath)
	if err != nil {
		return false
	}
	return true
}

// used to set fields in the configuration to values from the
// command line context if the corresponding flagName is set
// in that context
func setBoolVal(field bool, ctx *cli.Context, flagName string, inverse ...bool) bool {
	// check to see if a value was set (either on the command-line or via the associated
	// environment variable, if any); if so, use that as value for the input field
	val := ctx.Bool(flagName)
	if ctx.IsSet(flagName) || val {
		field = val
		if len(inverse) > 0 {
			field = !field
		}
	}
	return field
}

func setStringVal(field string, ctx *cli.Context, flagName string) string {
	// check to see if a value was set (either on the command-line or via the associated
	// environment variable, if any); if so, use that as value for the input field
	val := ctx.String(flagName)
	if ctx.IsSet(flagName) || val != "" {
		field = val
	}
	return field
}

func setIntVal(field int, ctx *cli.Context, flagName string) int {
	// check to see if a value was set (either on the command-line or via the associated
	// environment variable, if any); if so, use that as value for the input field
	val := ctx.String(flagName)
	if ctx.IsSet(flagName) || val != "" {
		parsedField, err := strconv.Atoi(val)
		if err != nil {
			splitErr := strings.Split(err.Error(), ": ")
			errStr := splitErr[len(splitErr)-1]
			log.Fatal(fmt.Sprintf("Error Parsing %v; value '%v' cannot be parsed as an integer (%v)", flagName, val, errStr))
		}
		field = int(parsedField)
	}
	return field
}

func setUIntVal(field uint, ctx *cli.Context, flagName string) uint {
	// check to see if a value was set (either on the command-line or via the associated
	// environment variable, if any); if so, use that as value for the input field
	val := ctx.String(flagName)
	if ctx.IsSet(flagName) || val != "" {
		parsedField, err := strconv.Atoi(val)
		if err != nil {
			splitErr := strings.Split(err.Error(), ": ")
			errStr := splitErr[len(splitErr)-1]
			log.Fatal(fmt.Sprintf("Error Parsing %v; value '%v' cannot be parsed as an unsigned integer (%v)", flagName, val, errStr))
		}
		field = uint(parsedField)
	}
	return field
}

func setDurationVal(field time.Duration, ctx *cli.Context, flagName string) time.Duration {
	// check to see if a value was set (either on the command-line or via the associated
	// environment variable, if any); if so, use that as value for the input field
	val := ctx.String(flagName)
	if ctx.IsSet(flagName) || val != "" {
		parsedField, err := time.ParseDuration(val)
		if err != nil {
			splitErr := strings.Split(err.Error(), ": ")
			errStr := splitErr[len(splitErr)-1]
			log.Fatal(fmt.Sprintf("Error Parsing %v; value '%v' cannot be parsed as a duration (%v)", flagName, val, errStr))
		}
		field = parsedField
	}
	return field
}

// checks the input addr to see if it can be parsed as an IP address or used
// as a hostname. If both of those tests fail, then it returns an error, otherwise
// it returns a nil (no error) indicating that the addr string is a valid address
func isValidAddress(addr string, errPrefix string) error {
	parsedIP := net.ParseIP(addr)
	if parsedIP == nil {
		_, err := net.LookupHost(addr)
		if err != nil {
			errString := fmt.Sprintf("%s Address '%s' is not a valid address/hostname", errPrefix, addr)
			return errors.New(errString)
		}
	}
	return nil
}

// sanity checks the input address and port values to ensure they are set
// appropriately, specifically:
//
//	  - ensure that if the port value is set, the addr value does not also
//		include as part of the addr value (i.e. that the addr value is not a
//		string of the form IP_ADDR:PORT or HOSTNAME:PORT)
//	  - ensures that if a port is specified as part of the addr value, that port
//		string is not an empty string (i.e. that the ':' character is not the
//		last character in the addr value)
//	  - ensures that the address portion of the addr value can be either parsed
//		as an IP address or used as a hostname
//	  - ensures that the port detected as part of the addr value (if there is one)
//		can be parsed as an integer
//
// this function returns a boolean indicating whether or not a port number was
// found in the address and either nil or an error (depending on whether or not
// an error was detected while parsing the addr string)
func checkHostPortVals(addr string, port *int, errPrefix string) (bool, error) {
	portInAddrFlag := false
	// if the address field is empty, then we don't need to worry
	if len(addr) == 0 {
		return portInAddrFlag, nil
	}
	// If the input address ontains a comma, return an error
	if strings.Index(addr, ",") != -1 {
		errString := fmt.Sprintf("%s Invalid address; comma-separated IP address values are not supported", errPrefix)
		return false, errors.New(errString)
	}
	// check to see if the input address contains a colon or not
	idx := strings.Index(addr, ":")
	if idx == -1 {
		// if we don't find a colon in the address, then just try to parse it as
		// an IP address; return an error if we can't parse it successfully
		err := isValidAddress(addr, errPrefix)
		if err != nil {
			return false, err
		}
	} else if idx == (len(addr) - 1) {
		// if the last character is a colon character, then return an error because
		// while there is a colon, there's no value after that colon to represent
		// the port the RESTful APi should listen on
		errString := fmt.Sprintf("%s Empty port specified as part of API IP address", errPrefix)
		return false, errors.New(errString)
	} else {
		// otherwise attempt to split the input address into a host and port,
		// then try to parse resulting host string as an IP address; return
		// an error if the address cannot be split into a host and port or
		// the resulting host cannot be successfully parsed as an IP address
		host, portStr, err := net.SplitHostPort(addr)
		if err != nil {
			return false, err
		}
		addrErr := isValidAddress(host, errPrefix)
		if addrErr != nil {
			return false, addrErr
		}
		portFromAddr, convErr := strconv.Atoi(portStr)
		if convErr != nil {
			errString := fmt.Sprintf("%s Port detected in address ('%s') cannot be parsed as an integer value", errPrefix, portStr)
			return false, errors.New(errString)
		}
		// if we get this far, and the port is also specified via the 'port' input
		// to this function, then return an error
		if *port > 0 {
			errString := fmt.Sprintf("%s Port can not be specified both as a port value and as part of address", errPrefix)
			return false, errors.New(errString)
		}
		// otherwise save the port that was parsed from the 'addr' as the 'port'
		// value before we return
		portInAddrFlag = true
		*port = portFromAddr
	}
	return portInAddrFlag, nil
}

// santiy check of the command-line flags to ensure that values are set
// appropriately; returns the port read from the command-line arguments, a flag
// indicating whether or not a port was detected in the address read from the
// command-line arguments, and an error if one is detected
func checkCmdLineFlags(ctx *cli.Context) (int, bool, error) {
	// Check to see if the API address is specified (either via the CLI or through
	// the associated environment variable); if so, grab the port and check that the
	// address and port against the constraints (above)
	addr := ctx.String("api-addr")
	port := ctx.Int("api-port")
	if ctx.IsSet("api-addr") || addr != "" {
		portInAddr, err := checkHostPortVals(addr, &port, "Command Line Error:")
		if err != nil {
			return -1, portInAddr, err
		}
		return port, portInAddr, nil
	}
	return port, false, nil
}

// santiy check of the configuration file parameters to ensure that values are set
// appropriately; returns the port read from the global configuration file, a flag
// indicating whether or not a port was detected in the address read from the
// global configuration file, and an error if one is detected
func checkCfgSettings(cfg *Config) (int, bool, error) {
	addr := cfg.RestAPI.Address
	var port int
	if cfg.RestAPI.PortSetByConfigFile() {
		port = cfg.RestAPI.Port
	} else {
		port = -1
	}
	portInAddr, err := checkHostPortVals(addr, &port, "ConfigFile Error:")
	if err != nil {
		return -1, portInAddr, err
	}
	return port, portInAddr, nil
}

// Apply the command line flags set (if any) to override the values
// in the input configuration
func applyCmdLineFlags(cfg *Config, ctx *cli.Context) {
	// check the settings for the command-line arguments included in the cli.Context
	cmdLinePort, cmdLinePortInAddr, cmdLineErr := checkCmdLineFlags(ctx)
	if cmdLineErr != nil {
		log.Fatal(cmdLineErr)
	}
	// check the settings in the input configuration (and return an error if any issues are found)
	cfgFilePort, cfgFilePortInAddr, cfgFileErr := checkCfgSettings(cfg)
	if cfgFileErr != nil {
		log.Fatal(cfgFileErr)
	}
	invertBoolean := true
	// apply any command line flags that might have been set, first for the
	// snapteld-related flags
	cfg.GoMaxProcs = setIntVal(cfg.GoMaxProcs, ctx, "max-procs")
	cfg.LogLevel = setIntVal(cfg.LogLevel, ctx, "log-level")
	cfg.LogPath = setStringVal(cfg.LogPath, ctx, "log-path")
	cfg.LogTruncate = setBoolVal(cfg.LogTruncate, ctx, "log-truncate")
	cfg.LogColors = setBoolVal(cfg.LogColors, ctx, "log-colors")
	// next for the flags related to the control package
	cfg.Control.MaxRunningPlugins = setIntVal(cfg.Control.MaxRunningPlugins, ctx, "max-running-plugins")
	cfg.Control.PluginLoadTimeout = setIntVal(cfg.Control.PluginLoadTimeout, ctx, "plugin-load-timeout")
	cfg.Control.PluginTrust = setIntVal(cfg.Control.PluginTrust, ctx, "plugin-trust")
	cfg.Control.AutoDiscoverPath = setStringVal(cfg.Control.AutoDiscoverPath, ctx, "auto-discover")
	cfg.Control.KeyringPaths = setStringVal(cfg.Control.KeyringPaths, ctx, "keyring-paths")
	cfg.Control.CacheExpiration = jsonutil.Duration{setDurationVal(cfg.Control.CacheExpiration.Duration, ctx, "cache-expiration")}
	cfg.Control.ListenAddr = setStringVal(cfg.Control.ListenAddr, ctx, "control-listen-addr")
	cfg.Control.ListenPort = setIntVal(cfg.Control.ListenPort, ctx, "control-listen-port")
	cfg.Control.Pprof = setBoolVal(cfg.Control.Pprof, ctx, "pprof")
	// next for the RESTful server related flags
	cfg.RestAPI.Enable = setBoolVal(cfg.RestAPI.Enable, ctx, "disable-api", invertBoolean)
	cfg.RestAPI.Port = setIntVal(cfg.RestAPI.Port, ctx, "api-port")
	cfg.RestAPI.Address = setStringVal(cfg.RestAPI.Address, ctx, "api-addr")
	cfg.RestAPI.HTTPS = setBoolVal(cfg.RestAPI.HTTPS, ctx, "rest-https")
	cfg.RestAPI.RestCertificate = setStringVal(cfg.RestAPI.RestCertificate, ctx, "rest-cert")
	cfg.RestAPI.RestKey = setStringVal(cfg.RestAPI.RestKey, ctx, "rest-key")
	cfg.RestAPI.RestAuth = setBoolVal(cfg.RestAPI.RestAuth, ctx, "rest-auth")
	cfg.RestAPI.RestAuthPassword = setStringVal(cfg.RestAPI.RestAuthPassword, ctx, "rest-auth-pwd")
	cfg.RestAPI.Pprof = setBoolVal(cfg.RestAPI.Pprof, ctx, "pprof")
	// next for the scheduler related flags
	cfg.Scheduler.WorkManagerQueueSize = setUIntVal(cfg.Scheduler.WorkManagerQueueSize, ctx, "work-manager-queue-size")
	cfg.Scheduler.WorkManagerPoolSize = setUIntVal(cfg.Scheduler.WorkManagerPoolSize, ctx, "work-manager-pool-size")
	// and finally for the tribe-related flags
	cfg.Tribe.Name = setStringVal(cfg.Tribe.Name, ctx, "tribe-node-name")
	cfg.Tribe.Enable = setBoolVal(cfg.Tribe.Enable, ctx, "tribe")
	cfg.Tribe.BindAddr = setStringVal(cfg.Tribe.BindAddr, ctx, "tribe-addr")
	cfg.Tribe.BindPort = setIntVal(cfg.Tribe.BindPort, ctx, "tribe-port")
	cfg.Tribe.Seed = setStringVal(cfg.Tribe.Seed, ctx, "tribe-seed")
	// check to see if we have duplicate port definitions (check the various
	// combinations of the config file and command-line parameter values that
	// could be used to define the port and make sure we only have one)
	if cmdLinePort > 0 && cfgFilePortInAddr && !cmdLinePortInAddr {
		log.Fatal("Usage Error: Port can not be specified both as a port value on the CLI and as part of address in the global config file")
	} else if cfgFilePort > 0 && cmdLinePortInAddr && !cfgFilePortInAddr {
		log.Fatal("Usage Error: Port can not be specified both as a port value in the global config file and as part of address on the CLI")
	}
	// if we retrieved the port from an address, then use that value as the
	// cfg.RestAPI.Port value (so that we can validate it against the constraints
	// placed on the value for this parameter and ensure that the port in the
	// address complies with those constraints)
	if cmdLinePortInAddr {
		cfg.RestAPI.Port = cmdLinePort
	} else if cfgFilePortInAddr {
		cfg.RestAPI.Port = cfgFilePort
	} else {
		// if get to here, then there is no port number in the input address
		// (regardless of whether it came from the default configuration, configuration
		// file, an environment variable, or a command-line flag); in that case we should
		// set the address in the RestAPI configuration to be the current address and port
		// (separated by a ':')
		cfg.RestAPI.Address = fmt.Sprintf("%v:%v", cfg.RestAPI.Address, cfg.RestAPI.Port)
	}
}

func monitorErrors(ch <-chan error) {
	// Block on the error channel. Will return exit status 1 for an error or just return if the channel closes.
	err, ok := <-ch
	if !ok {
		return
	}
	log.Fatal(err)
}

// setMaxProcs configures runtime.GOMAXPROCS for snapteld. GOMAXPROCS can be set by using
// the env variable GOMAXPROCS and snapteld will honor this setting. A user can override the env
// variable by setting max-procs flag on the command line. snapteld will be limited to the max CPUs
// on the system even if the env variable or the command line setting is set above the max CPUs.
// The default value if the env variable or the command line option is not set is 1.
func setMaxProcs(maxProcs int) {
	var _maxProcs int
	numProcs := runtime.NumCPU()
	if maxProcs <= 0 {
		// We prefer sane values for GOMAXPROCS
		log.WithFields(
			log.Fields{
				"_block":   "main",
				"_module":  logModule,
				"maxprocs": maxProcs,
			}).Error("Trying to set GOMAXPROCS to an invalid value")
		_maxProcs = 1
		log.WithFields(
			log.Fields{
				"_block":   "main",
				"_module":  logModule,
				"maxprocs": _maxProcs,
			}).Warning("Setting GOMAXPROCS to 1")
		_maxProcs = 1
	} else if maxProcs <= numProcs {
		_maxProcs = maxProcs
	} else {
		log.WithFields(
			log.Fields{
				"_block":   "main",
				"_module":  logModule,
				"maxprocs": maxProcs,
			}).Error("Trying to set GOMAXPROCS larger than number of CPUs available on system")
		_maxProcs = numProcs
		log.WithFields(
			log.Fields{
				"_block":   "main",
				"_module":  logModule,
				"maxprocs": _maxProcs,
			}).Warning("Setting GOMAXPROCS to number of CPUs on host")
	}

	log.Info("setting GOMAXPROCS to: ", _maxProcs, " core(s)")
	runtime.GOMAXPROCS(_maxProcs)
	//Verify setting worked
	actualNumProcs := runtime.GOMAXPROCS(0)
	if actualNumProcs != _maxProcs {
		log.WithFields(
			log.Fields{
				"block":          "main",
				"_module":        logModule,
				"given maxprocs": _maxProcs,
				"real maxprocs":  actualNumProcs,
			}).Warning("not using given maxprocs")
	}
}

// UnmarshalJSON unmarshals valid json into a Config.  An example Config can be found
// at github.com/intelsdi-x/snap/blob/master/examples/configs/snap-config-sample.json
func (c *Config) UnmarshalJSON(data []byte) error {
	// construct a map of strings to json.RawMessages (to defer the parsing of individual
	// fields from the unmarshalled interface until later), then unmarshal the input
	// byte array into that map
	t := make(map[string]json.RawMessage)
	if err := json.Unmarshal(data, &t); err != nil {
		return err
	}
	// loop through the individual map elements, parse each in turn, and set
	// the appropriate field in this configuration
	for k, v := range t {
		switch k {
		case "log_level":
			if err := json.Unmarshal(v, &(c.LogLevel)); err != nil {
				return fmt.Errorf("%v (while parsing 'log_level')", err)
			}
		case "gomaxprocs":
			if err := json.Unmarshal(v, &(c.GoMaxProcs)); err != nil {
				return fmt.Errorf("%v (while parsing 'gomaxprocs')", err)
			}
		case "log_path":
			if err := json.Unmarshal(v, &(c.LogPath)); err != nil {
				return fmt.Errorf("%v (while parsing 'log_path')", err)
			}
		case "log_truncate":
			if err := json.Unmarshal(v, &(c.LogTruncate)); err != nil {
				return fmt.Errorf("%v (while parsing 'log_truncate')", err)
			}
		case "log_colors":
			if err := json.Unmarshal(v, &(c.LogColors)); err != nil {
				return fmt.Errorf("%v (while parsing 'log_colors')", err)
			}
		case "control":
			if err := json.Unmarshal(v, c.Control); err != nil {
				return err
			}
		case "restapi":
			if err := json.Unmarshal(v, c.RestAPI); err != nil {
				return err
			}
		case "scheduler":
			if err := json.Unmarshal(v, c.Scheduler); err != nil {
				return err
			}
		case "tribe":
			if err := json.Unmarshal(v, c.Tribe); err != nil {
				return err
			}
		default:
			return fmt.Errorf("Unrecognized key '%v' in global config file", k)
		}
	}
	return nil
}

func startModule(m coreModule) error {
	err := m.Start()
	if err == nil {
		log.WithFields(
			log.Fields{
				"block":       "main",
				"_module":     logModule,
				"snap-module": m.Name(),
			}).Info("module started")
	}
	return err
}

func printErrorAndExit(name string, err error) {
	log.WithFields(
		log.Fields{
			"block":       "main",
			"_module":     logModule,
			"error":       err.Error(),
			"snap-module": name,
		}).Fatal("error starting module")
}

func startInterruptHandling(modules ...coreModule) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGHUP)

	//Let's block until someone tells us to quit
	go func() {
		sig := <-c
		log.WithFields(
			log.Fields{
				"block":   "main",
				"_module": logModule,
			}).Info("shutting down modules")

		for _, m := range modules {
			log.WithFields(
				log.Fields{
					"block":       "main",
					"_module":     logModule,
					"snap-module": m.Name(),
				}).Info("stopping module")
			m.Stop()
		}
		if sig == syscall.SIGHUP {
			// log the action we're taking (restarting the app)
			log.WithFields(
				log.Fields{
					"block":   "main",
					"_module": logModule,
					"signal":  sig.String(),
				}).Info("restarting app")
			// and restart the app (with the current configuration)
			err := cliApp.Run(os.Args)
			if err != nil {
				os.Exit(1)
			}
		} else {
			log.WithFields(
				log.Fields{
					"block":   "main",
					"_module": logModule,
					"signal":  sig.String(),
				}).Info("exiting on signal")
			os.Exit(0)
		}
	}()
}

func getLevel(i int) log.Level {
	switch i {
	case 1:
		return log.DebugLevel
	case 2:
		return log.InfoLevel
	case 3:
		return log.WarnLevel
	case 4:
		return log.ErrorLevel
	case 5:
		return log.FatalLevel
	default:
		panic("bad level")
	}
}

func validateLevelSettings(logLevel, pluginTrust int) {
	if logLevel < 1 || logLevel > 5 {
		log.WithFields(
			log.Fields{
				"block":   "main",
				"_module": logModule,
				"level":   logLevel,
			}).Fatal("log level was invalid (needs: 1-5)")
	}
	if pluginTrust < 0 || pluginTrust > 2 {
		log.WithFields(
			log.Fields{
				"block":   "main",
				"_module": logModule,
				"level":   pluginTrust,
			}).Fatal("Plugin trust was invalid (needs: 0-2)")
	}
}


text:
#ifndef COMPUTE_FUNCTION_H__
#define COMPUTE_FUNCTION_H__

#include <tesseract/base/types.h>

namespace tesseract
{

/** @brief template class ComputeFunction for computing the objective function
 */
template <template <class> class Regularizer, typename T>
struct ComputeFunction
{
	/** regularizer param */
	typedef typename Regularizer<T>::param_type reg_param_type;

	/** default constructor */
	ComputeFunction();

	/*
	 * @param cov the covariance matrix C_S and b_S (the last row and col
	 * corresponds to b_S
	 * @return the function value
	 */
	const T operator ()(const Eigen::Ref<const Matrix<T>>& cov) const;

	/** @param _eta regularization constant */
	void set_eta(T _eta);

	/** @param _param regularizer params */
	void set_reg_params(reg_param_type _reg_params);

	/** regularization constant \f$\eta > 0\f$ */
	T eta;

	/** regularizer params */
	reg_param_type reg_params;

	/** default value of eta = 0.0001 */
	static constexpr T default_eta = static_cast<T>(0.0001);
};

}

#endif // COMPUTE_FUNCTION_H__


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.siu.cs.www.parkingspotfinder.LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/textView" />

    <Button
        android:text="Login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/loginBtn"
        style="@style/Widget.AppCompat.Button.Colored"
        android:background="?attr/actionModeSplitBackground"
        android:layout_marginBottom="11dp"
        android:layout_above="@+id/registerBtn"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_above="@+id/passwordField"
        android:layout_toRightOf="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="E-Mail:"
        android:id="@+id/emailField"
        android:inputType="textEmailAddress" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/gospaceslogo"
        android:id="@+id/imageView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/emailField"
        android:cropToPadding="false"
        android:adjustViewBounds="false" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:id="@+id/passwordField"
        android:hint="Password:"
        android:layout_marginBottom="84dp"
        android:selectAllOnFocus="false"
        style="@style/Widget.AppCompat.EditText"
        android:inputType="textPassword"
        android:layout_above="@+id/loginBtn"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:text="Register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/registerBtn"
        style="@style/Widget.AppCompat.Button.Colored"
        android:background="@color/colorPrimaryDark"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RefresherButtonComponent } from './refresher-button.component';

describe('RefresherButtonComponent', () => {
  let component: RefresherButtonComponent;
  let fixture: ComponentFixture<RefresherButtonComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RefresherButtonComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(RefresherButtonComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Using Directives
using System;
using Ninject.Extensions.Cache;
#endregion

namespace Ninject.Tests.Extensions.Cache.Mocks
{
	[Cache(TimeoutMs = 250)]
	public class CacheMockWithTimeout
	{
		/*----------------------------------------------------------------------------------------*/
		public static int GetValueCount { get; set; }
		/*----------------------------------------------------------------------------------------*/
		public static int MultiplyCount { get; set; }
		/*----------------------------------------------------------------------------------------*/
		public static int ConvertCount { get; set; }
		/*----------------------------------------------------------------------------------------*/
		public static void ResetCounts()
		{
			GetValueCount = 0;
			MultiplyCount = 0;
			ConvertCount = 0;
		}
		/*----------------------------------------------------------------------------------------*/
		public virtual int GetValue()
		{
			GetValueCount++;

			return 42;
		}
		/*----------------------------------------------------------------------------------------*/
		public virtual int Multiply(int x, int y)
		{
			MultiplyCount++;

			return x * y;
		}
		/*----------------------------------------------------------------------------------------*/
		public virtual string Convert(object obj)
		{
			ConvertCount++;

			return obj.ToString();
		}
		/*----------------------------------------------------------------------------------------*/
	}
}


text:
package unluac.util;

import java.util.ArrayList;
import java.util.Collections;

public class Stack<T> {

  private final ArrayList<T> data;

  public Stack() {
    data = new ArrayList<T>();
  }

  public boolean isEmpty() {
    return data.isEmpty();
  }

  public T peek() {
    return data.get(data.size() - 1);
  }

  public T pop() {
    return data.remove(data.size() - 1);
  }

  public void push(T item) {
    data.add(item);
  }

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

  public void reverse() {
    Collections.reverse(data);
  }

}


text:
<phpunit
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
>
 <php>
  <includePath>.:..</includePath>
 </php>
</phpunit>


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Crud\Grid\Filter;

use Vein\Core\Crud\Grid\Filter;

/**
 * Class filter grid.
 *
 * @category   Vein\Core
 * @package    Crud
 * @subpackage Grid
 */
class Extjs extends Filter
{
    /**
     * Initialize decorator
     *
     * @return void
     */
    protected function _initDecorator()
    {
        $this->_decorator = 'extjs';
    }

    /**
     * Get grid action
     *
     * @return string
     */
    public function getModulePrefix()
    {
        return $this->_grid->getModulePrefix();
    }

    /**
     * Return module name
     *
     * @return string
     */
    public function getModuleName()
    {
        return $this->_grid->getModuleName();
    }

    /**
     * Return grid key
     *
     * @return string
     */
    public function getKey()
    {
        return $this->_grid->getKey();
    }

    /**
     * Get grid action
     *
     * @return string
     */
    public function getAction()
    {
        return $this->_grid->getAction();
    }
}


text:
package com.microsoft.azure.batch.protocol.models;

import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A user Account for RDP or SSH access on a Compute Node.
 */
public class ComputeNodeUser {
    /**
     * The user name of the Account.
     */
    @JsonProperty(value = "name", required = true)
    private String name;

    /**
     * Whether the Account should be an administrator on the Compute Node.
     * The default value is false.
     */
    @JsonProperty(value = "isAdmin")
    private Boolean isAdmin;

    /**
     * The time at which the Account should expire.
     * If omitted, the default is 1 day from the current time. For Linux
     * Compute Nodes, the expiryTime has a precision up to a day.
     */
    @JsonProperty(value = "expiryTime")
    private DateTime expiryTime;

    /**
     * The password of the Account.
     * The password is required for Windows Compute Nodes (those created with
     * 'cloudServiceConfiguration', or created with
     * 'virtualMachineConfiguration' using a Windows Image reference). For
     * Linux Compute Nodes, the password can optionally be specified along with
     * the sshPublicKey property.
     */
    @JsonProperty(value = "password")
    private String password;

    /**
     * The SSH public key that can be used for remote login to the Compute
     * Node.
     * The public key should be compatible with OpenSSH encoding and should be
     * base 64 encoded. This property can be specified only for Linux Compute
     * Nodes. If this is specified for a Windows Compute Node, then the Batch
     * service rejects the request; if you are calling the REST API directly,
     * the HTTP status code is 400 (Bad Request).
     */
    @JsonProperty(value = "sshPublicKey")
    private String sshPublicKey;

    /**
     * Get the name value.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name value.
     *
     * @param name the name value to set
     * @return the ComputeNodeUser object itself.
     */
    public ComputeNodeUser withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the default value is false.
     *
     * @return the isAdmin value
     */
    public Boolean isAdmin() {
        return this.isAdmin;
    }

    /**
     * Set the default value is false.
     *
     * @param isAdmin the isAdmin value to set
     * @return the ComputeNodeUser object itself.
     */
    public ComputeNodeUser withIsAdmin(Boolean isAdmin) {
        this.isAdmin = isAdmin;
        return this;
    }

    /**
     * Get if omitted, the default is 1 day from the current time. For Linux Compute Nodes, the expiryTime has a precision up to a day.
     *
     * @return the expiryTime value
     */
    public DateTime expiryTime() {
        return this.expiryTime;
    }

    /**
     * Set if omitted, the default is 1 day from the current time. For Linux Compute Nodes, the expiryTime has a precision up to a day.
     *
     * @param expiryTime the expiryTime value to set
     * @return the ComputeNodeUser object itself.
     */
    public ComputeNodeUser withExpiryTime(DateTime expiryTime) {
        this.expiryTime = expiryTime;
        return this;
    }

    /**
     * Get the password is required for Windows Compute Nodes (those created with 'cloudServiceConfiguration', or created with 'virtualMachineConfiguration' using a Windows Image reference). For Linux Compute Nodes, the password can optionally be specified along with the sshPublicKey property.
     *
     * @return the password value
     */
    public String password() {
        return this.password;
    }

    /**
     * Set the password is required for Windows Compute Nodes (those created with 'cloudServiceConfiguration', or created with 'virtualMachineConfiguration' using a Windows Image reference). For Linux Compute Nodes, the password can optionally be specified along with the sshPublicKey property.
     *
     * @param password the password value to set
     * @return the ComputeNodeUser object itself.
     */
    public ComputeNodeUser withPassword(String password) {
        this.password = password;
        return this;
    }

    /**
     * Get the public key should be compatible with OpenSSH encoding and should be base 64 encoded. This property can be specified only for Linux Compute Nodes. If this is specified for a Windows Compute Node, then the Batch service rejects the request; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request).
     *
     * @return the sshPublicKey value
     */
    public String sshPublicKey() {
        return this.sshPublicKey;
    }

    /**
     * Set the public key should be compatible with OpenSSH encoding and should be base 64 encoded. This property can be specified only for Linux Compute Nodes. If this is specified for a Windows Compute Node, then the Batch service rejects the request; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request).
     *
     * @param sshPublicKey the sshPublicKey value to set
     * @return the ComputeNodeUser object itself.
     */
    public ComputeNodeUser withSshPublicKey(String sshPublicKey) {
        this.sshPublicKey = sshPublicKey;
        return this;
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>Chipotle for Honduras</title>

    <link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />

  <!doctype html>

	<meta charset="UTF-8">
	<title>scrollingBanner</title>
	<link href='http://fonts.googleapis.com/css?family=Lato:300,400' rel='stylesheet' type='text/css'>

			Students Helping Honduras

Who?

        Students Helping Honduras is a national organization with a simple mission: to end poverty & violence in Honduras through education
        and youth empowerment. Check out our main website at Students Helping Honduras

What?

CHIPOTLE!

 Not complicated. Show up to Barrack Road's Chipotle Tuesday, November 18th between 4 and 8 PM and half the proceeds will go to SHH.

 No Car? No Problem!

          Use the form below to order online and we will deliver for only a $3 delivery fee. We accept cash and credit.

How?

 All day on Tuesday, 11/18, until 4 PM, you can fill out this form  and select what time you would like to receive your food and we will make it happen!

 You can view Chipotle's menu here. Please keep in mind that once you press submit, your order is final! Contact pp5nv@virginia.edu with any questions.


text:
Start a debugging session in the Web Inspector and open this file.

Before running the tests please perform the following:
Make sure the execution is not paused in the debugger.

Click the button and when the debugger breaks, set a breakpoint on the first line in the loop
(as indicated by the comment), and click continue.

The debugger should stop at the beggining of the loop.

The above actions should be performed before each of the following tests.

<input type="button" value="run for" onclick="runFor()"/>

TEST 1: Click 'continue'. Execution should continue without stopping on the loop breakpoint again.

TEST 2: Click 'Step over'. Debugger should step inside the loop to the next statement line.

TEST 3: Click 'Step into'. Debugger should step into 'initialize' function. Click 'Step into' until
outside of the 'initialize' function - debugger should enter the 'condition' function.

TEST 4: 'Step over' to the statement line and then 'Step over' again. Debugger should pause on
the for loop again. Click 'Step into'. Debugger should step into the 'increment' function.
Click 'Step into' until outside of the 'increment' function - debugger should enter the 'condition'
function.


text:
import { connect } from 'react-redux';
import gameListView from './GameListView';

function mapStateToProps(state) {
  console.log('GameListView========>');
  console.log(state);
  return {
    dataSource: state.gameSwitchReducer.dataSource || [],
  };
}

function mapDispatchToProps(dispatch) {
  return {
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(gameListView);


text:
package com.mparticle.sdk.model.eventprocessing;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class RokuRuntimeEnvironment  extends RuntimeEnvironment {

    @JsonProperty("build_id")
    private String buildId;

    @JsonProperty("brand")
    private String brand;

    @JsonProperty("product")
    private String product;

    @JsonProperty("name")
    private String name;

    @JsonProperty("manufacturer")
    private String manufacturer;

    @JsonProperty("os_version")
    private String osVersion;

    @JsonProperty("model")
    private String model;

    @JsonProperty("country")
    private String country;

    @JsonProperty("locale_language")
    private String localeLanguage;

    @JsonProperty("locale_country")
    private String localeCountry;

    @JsonProperty("timezone_offset")
    private int utcOffset;

    @JsonProperty("timezone_name")
    private String timeZoneName;

    @JsonProperty("cpu_architecture")
    private String cpuArchitecture;

    @JsonProperty("application_name")
    private String applicationName;

    @JsonProperty("application_version")
    private String applicationVersion;

    @JsonProperty("application_package")
    private String applicationPackage;

    public String getBuildId() {
        return buildId;
    }

    public void setBuildId(String buildId) {
        this.buildId = buildId;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public String getName() {
        return name;
    }

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

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getOsVersion() {
        return osVersion;
    }

    public void setOsVersion(String osVersion) {
        this.osVersion = osVersion;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocaleLanguage() {
        return localeLanguage;
    }

    public void setLocaleLanguage(String localeLanguage) {
        this.localeLanguage = localeLanguage;
    }

    public String getLocaleCountry() {
        return localeCountry;
    }

    public void setLocaleCountry(String localeCountry) {
        this.localeCountry = localeCountry;
    }

    public int getUtcOffset() {
        return utcOffset;
    }

    public void setUtcOffset(int utcOffset) {
        this.utcOffset = utcOffset;
    }

    public String getTimeZoneName() {
        return timeZoneName;
    }

    public void setTimeZoneName(String timeZoneName) {
        this.timeZoneName = timeZoneName;
    }

    public String getCpuArchitecture() {
        return cpuArchitecture;
    }

    public void setCpuArchitecture(String cpuArchitecture) {
        this.cpuArchitecture = cpuArchitecture;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getApplicationVersion() {
        return applicationVersion;
    }

    public void setApplicationVersion(String applicationVersion) {
        this.applicationVersion = applicationVersion;
    }

    public String getApplicationPackage() {
        return applicationPackage;
    }

    public void setApplicationPackage(String applicationPackage) {
        this.applicationPackage = applicationPackage;
    }

    public RokuRuntimeEnvironment() {
        super(Type.ROKU);
    }
}


text:
<?php namespace CCConsole; use CCCli;

class migrator extends \CCConsoleController {

	/**
	 * return an array with information about the script
	 */
	public function help()
	{
		return array(
			'name'	=> 'CCF Database migrator',
			'desc'	=> 'Helps keeping the database updated when developing in teams.',
			'actions'	=> array(
				'migrate'	=> 'checks for new migrations and runs them.',
				'rollback'	=> 'reverts the last migration.',
			),
		);
	}

	/**
	 * Migrate the database to the lasted version
	 *
	 * @param array 		$params
	 */
	public function action_migrate( $params )
	{
		\DB\Migrator::migrate();
	}

	/**
	 * Revert the last revision
	 *
	 * @param array 		$params
	 */
	public function action_rollback( $params )
	{
		\DB\Migrator::rollback();
	}

	/**
	 * Revert all revisions
	 *
	 * @param array 		$params
	 */
	public function action_reset( $params )
	{
		while( \DB\Migrator::rollback() );
	}

	/**
	 * Create new migration
	 *
	 * @param array 		$params
	 * @return void
	 */
	public function action_create( $params )
	{
		$name = array_shift( $params );

		$file = \DB\Migrator::path( $name );

		\CCFile::write( $file, "# ---> up\n\n\n\n# ---> down\n\n" );
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="traceFileAppend=true attribute" />
<meta content="traceFileAppend=true database connection URL attribute" name="DC.subject" />
<meta content="traceFileAppend=true database connection URL attribute" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefattrib24612.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefattribtracefileappend" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>traceFileAppend=true attribute</title>

traceFileAppend=true attribute

Function

Specifies that the Derby
Network Client should append JDBC trace information to a trace file. The file
can be specified by the
traceFile=path
attribute. If you do not specify a trace file but you specify the
traceDirectory=path
attribute, the trace information is appended to the default file. If you do not
specify traceFileAppend=true, any previous version of the trace file is
overwritten.

For more information about tracing, see "Network client tracing" in the
Java DB Server and Administration Guide. See traceDirectory=path
and
traceLevel=value
for other attributes related to tracing.

Combining with other attributes

This attribute must be specified in conjunction with either the
traceFile=path attribute or the traceDirectory=path attribute. You
can also combine this attribute with other attributes.

Example

-- enable tracing on an existing database, appending to the
--   specified file
jdbc:derby://localhost:1527/mydb;traceFile=trace.out;traceFileAppend=true
-- enable tracing on an existing database, appending to the default file
--   within the specified directory, relative to the Derby home directory
jdbc:derby://localhost:1527/mydb;traceDirectory=mytracedir;traceFileAppend=true

Parent topic: Setting attributes for the database connection URL


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public Provider()
```
## See also
- [Provider](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.Provider.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)


text:
package org.apache.hadoop.hbase.regionserver.wal;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Metadata;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.DefaultCodec;

/**
 * Implementation of {@link HLog.Writer} that delegates to
 * SequenceFile.Writer.
 */
@InterfaceAudience.Private
public class SequenceFileLogWriter implements HLog.Writer {
  static final Text WAL_VERSION_KEY = new Text("version");
  // Let the version be 1.  Let absence of a version meta tag be old, version 0.
  // Set this version '1' to be the version that introduces compression,
  // the COMPRESSION_VERSION.
  private static final int COMPRESSION_VERSION = 1;
  static final int VERSION = COMPRESSION_VERSION;
  static final Text WAL_VERSION = new Text("" + VERSION);
  static final Text WAL_COMPRESSION_TYPE_KEY = new Text("compression.type");
  static final Text DICTIONARY_COMPRESSION_TYPE = new Text("dictionary");

  private final Log LOG = LogFactory.getLog(this.getClass());
  // The sequence file we delegate to.
  private SequenceFile.Writer writer;
  // This is the FSDataOutputStream instance that is the 'out' instance
  // in the SequenceFile.Writer 'writer' instance above.
  private FSDataOutputStream writer_out;

  private Class<? extends HLogKey> keyClass;

  /**
   * Context used by our wal dictionary compressor.  Null if we're not to do
   * our custom dictionary compression.  This custom WAL compression is distinct
   * from sequencefile native compression.
   */
  private CompressionContext compressionContext;

  /**
   * Default constructor.
   */
  public SequenceFileLogWriter() {
    super();
  }

  /**
   * This constructor allows a specific HLogKey implementation to override that
   * which would otherwise be chosen via configuration property.
   *
   * @param keyClass
   */
  public SequenceFileLogWriter(Class<? extends HLogKey> keyClass) {
    this.keyClass = keyClass;
  }

  /**
   * Create sequence file Metadata for our WAL file with version and compression
   * type (if any).
   * @param conf
   * @param compress
   * @return Metadata instance.
   */
  private static Metadata createMetadata(final Configuration conf,
      final boolean compress) {
    TreeMap<Text, Text> metaMap = new TreeMap<Text, Text>();
    metaMap.put(WAL_VERSION_KEY, WAL_VERSION);
    if (compress) {
      // Currently we only do one compression type.
      metaMap.put(WAL_COMPRESSION_TYPE_KEY, DICTIONARY_COMPRESSION_TYPE);
    }
    return new Metadata(metaMap);
  }

  /**
   * Call this method after init() has been executed
   *
   * @return whether WAL compression is enabled
   */
  static boolean isWALCompressionEnabled(final Metadata metadata) {
    // Check version is >= VERSION?
    Text txt = metadata.get(WAL_VERSION_KEY);
    if (txt == null || Integer.parseInt(txt.toString()) < COMPRESSION_VERSION) {
      return false;
    }
    // Now check that compression type is present.  Currently only one value.
    txt = metadata.get(WAL_COMPRESSION_TYPE_KEY);
    return txt != null && txt.equals(DICTIONARY_COMPRESSION_TYPE);
  }

  @Override
  public void init(FileSystem fs, Path path, Configuration conf)
  throws IOException {
    // Should we do our custom WAL compression?
    boolean compress = conf.getBoolean(HConstants.ENABLE_WAL_COMPRESSION, false);
    if (compress) {
      try {
        if (this.compressionContext == null) {
          this.compressionContext = new CompressionContext(LRUDictionary.class);
        } else {
          this.compressionContext.clear();
        }
      } catch (Exception e) {
        throw new IOException("Failed to initiate CompressionContext", e);
      }
    }

    if (null == keyClass) {
      keyClass = HLogUtil.getKeyClass(conf);
    }

    // Create a SF.Writer instance.
    try {
      // reflection for a version of SequenceFile.createWriter that doesn't
      // automatically create the parent directory (see HBASE-2312)
      this.writer = (SequenceFile.Writer) SequenceFile.class
        .getMethod("createWriter", new Class[] {FileSystem.class,
            Configuration.class, Path.class, Class.class, Class.class,
            Integer.TYPE, Short.TYPE, Long.TYPE, Boolean.TYPE,
            CompressionType.class, CompressionCodec.class, Metadata.class})
        .invoke(null, new Object[] {fs, conf, path, HLogUtil.getKeyClass(conf),
            WALEdit.class,
            Integer.valueOf(fs.getConf().getInt("io.file.buffer.size", 4096)),
            Short.valueOf((short)
              conf.getInt("hbase.regionserver.hlog.replication",
              fs.getDefaultReplication())),
            Long.valueOf(conf.getLong("hbase.regionserver.hlog.blocksize",
                fs.getDefaultBlockSize())),
            Boolean.valueOf(false) /*createParent*/,
            SequenceFile.CompressionType.NONE, new DefaultCodec(),
            createMetadata(conf, compress)
            });
    } catch (InvocationTargetException ite) {
      // function was properly called, but threw it's own exception
      throw new IOException(ite.getCause());
    } catch (Exception e) {
      // ignore all other exceptions. related to reflection failure
    }

    // if reflection failed, use the old createWriter
    if (this.writer == null) {
      LOG.debug("new createWriter -- HADOOP-6840 -- not available");
      this.writer = SequenceFile.createWriter(fs, conf, path,
        HLogUtil.getKeyClass(conf), WALEdit.class,
        fs.getConf().getInt("io.file.buffer.size", 4096),
        (short) conf.getInt("hbase.regionserver.hlog.replication",
          fs.getDefaultReplication()),
        conf.getLong("hbase.regionserver.hlog.blocksize",
          fs.getDefaultBlockSize()),
        SequenceFile.CompressionType.NONE,
        new DefaultCodec(),
        null,
        createMetadata(conf, compress));
    } else {
      LOG.debug("using new createWriter -- HADOOP-6840");
    }

    this.writer_out = getSequenceFilePrivateFSDataOutputStreamAccessible();
    LOG.debug("Path=" + path + ", compression=" + compress);
  }

  // Get at the private FSDataOutputStream inside in SequenceFile so we can
  // call sync on it.  Make it accessible.
  private FSDataOutputStream getSequenceFilePrivateFSDataOutputStreamAccessible()
  throws IOException {
    FSDataOutputStream out = null;
    final Field fields [] = this.writer.getClass().getDeclaredFields();
    final String fieldName = "out";
    for (int i = 0; i < fields.length; ++i) {
      if (fieldName.equals(fields[i].getName())) {
        try {
          // Make the 'out' field up in SF.Writer accessible.
          fields[i].setAccessible(true);
          out = (FSDataOutputStream)fields[i].get(this.writer);
          break;
        } catch (IllegalAccessException ex) {
          throw new IOException("Accessing " + fieldName, ex);
        } catch (SecurityException e) {
          LOG.warn("Does not have access to out field from FSDataOutputStream",
              e);
        }
      }
    }
    return out;
  }

  @Override
  public void append(HLog.Entry entry) throws IOException {
    entry.setCompressionContext(compressionContext);
    try {
      this.writer.append(entry.getKey(), entry.getEdit());
    } catch (NullPointerException npe) {
      // Concurrent close...
      throw new IOException(npe);
    }
  }

  @Override
  public void close() throws IOException {
    if (this.writer != null) {
      try {
        this.writer.close();
      } catch (NullPointerException npe) {
        // Can get a NPE coming up from down in DFSClient$DFSOutputStream#close
        LOG.warn(npe);
      }
      this.writer = null;
    }
  }

  @Override
  public void sync() throws IOException {
    this.writer.syncFs();
  }

  @Override
  public long getLength() throws IOException {
    try {
      return this.writer.getLength();
    } catch (NullPointerException npe) {
      // Concurrent close...
      throw new IOException(npe);
    }
  }

  /**
   * @return The dfsclient out stream up inside SF.Writer made accessible, or
   * null if not available.
   */
  public FSDataOutputStream getWriterFSDataOutputStream() {
    return this.writer_out;
  }
}