text:
#ifndef __CCBONENODE_H__
#define __CCBONENODE_H__

#include "base/CCProtocols.h"
#include "2d/CCNode.h"
#include "renderer/CCCustomCommand.h"
#include "editor-support/cocostudio/ActionTimeline/CCTimelineMacro.h"
#include "editor-support/cocostudio/CocosStudioExport.h"
#include "editor-support/cocostudio/ActionTimeline/CCSkinNode.h"

NS_TIMELINE_BEGIN

class SkeletonNode;

class CC_STUDIO_DLL BoneNode : public cocos2d::Node, public cocos2d::BlendProtocol
{
public:
    static BoneNode* create();
    static BoneNode* create(int length);

    using Node::addChild;
    // add child, and add child to bone list and skeleton's sub bone map or add it to skin list
    virtual void addChild(cocos2d::Node* child, int localZOrder, const std::string &name) override;
    virtual void addChild(cocos2d::Node* child, int localZOrder, int tag) override;

    // remove child, and remove child from bone list and skeleton's sub bone map or remove it from skin list
    virtual void removeChild(Node* child, bool cleanup) override;

    // get child bone list
    virtual const  cocos2d::Vector<BoneNode*>& getChildBones() const { return _childBones; }
    virtual cocos2d::Vector<BoneNode*>&  getChildBones() { return _childBones; }

    // get this bone's root skeleton, return null while bone is not in a skeleton
    virtual SkeletonNode* getRootSkeletonNode() const;

    /**
     * @brief: get all bones in this bone tree
     */
    cocos2d::Vector<BoneNode*> getAllSubBones() const;

    /**
    *@brief: add a skin
    *@param: display, whether display this skin
    */
    virtual void addSkin(SkinNode* skin, bool display);

    /**
    *@brief: add a skin
    *@param: display, whether display this skin
    *@param: hideOthers, whether hide other skins added to this bone
    */
    virtual void addSkin(SkinNode* skin, bool display, bool hideOthers);

    /**
    * @brief: display skin
    * @param: hideOthers, set other skins invisible
    */
    virtual void displaySkin(SkinNode* skin, bool hideOthers);

    /**
    * @brief: display all skins named skinName, if hide display only one skin,
    *         prefer to use display(SkinNode* skin, bool hideOthers = false)
    * @param: hideOthers, set other skins invisible
    */
    virtual void displaySkin(const std::string &skinName, bool hideOthers );

    // get the skins which is visible (displaying skins)
    virtual cocos2d::Vector<SkinNode*> getVisibleSkins() const;

    /**
     * get skins in this bone's children
     */
    virtual const  cocos2d::Vector<SkinNode*>& getSkins() const { return _boneSkins; }
    virtual  cocos2d::Vector<SkinNode*>&  getSkins() { return _boneSkins; }

    /**
    * @brief: get all skins in this bone tree
    */
    cocos2d::Vector<SkinNode*> getAllSubSkins() const;

    // blendFunc
    virtual void setBlendFunc(const cocos2d::BlendFunc &blendFunc) override;
    virtual const cocos2d::BlendFunc & getBlendFunc() const override { return _blendFunc; }

    // debug draw show, bone's debugdraw can be draw when bone is visible
    // when bone's added to skeleton, DebugDrawEnabled controlled by skeleton's DebugDrawEnabled
    virtual void setDebugDrawEnabled(bool isDebugDraw);
    virtual bool isDebugDrawEnabled() const { return _isRackShow; }

    // bone's debug draw's length
    virtual void setDebugDrawLength(float length);
    virtual float getDebugDrawLength() const { return _rackLength; }

    // bone's debug draw's width
    virtual void setDebugDrawWidth(float width);
    virtual float getDebugDrawWidth() const { return _rackWidth; }

    // bone's debug draw's width
    virtual void setDebugDrawColor(const cocos2d::Color4F &color);
    virtual cocos2d::Color4F getDebugDrawColor() const { return _rackColor; }

    // get bone's bounding box, depends on getVisibleSkinsRect, apply on node to parent's transform
    cocos2d::Rect getBoundingBox() const override;

    /**
    *get displayings rect in self transform
    */
    virtual cocos2d::Rect getVisibleSkinsRect() const;

    // transform & draw
    virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override;

    // set local zorder, and dirty the debugdraw to make debugdraw's render layer right
    virtual void setLocalZOrder(int localZOrder) override;

    // set name, and replace the subbone map in skeleton
    virtual void setName(const std::string& name) override;

    // set visible, and dirty the debugdraw to make debugdraw's render layer right
    virtual void setVisible(bool visible) override;

    // set contentsize, and recalculate debugdraw
    virtual void setContentSize(const cocos2d::Size& contentSize) override;

    // set localzorder, and recalculate debugdraw
    virtual void setAnchorPoint(const cocos2d::Vec2& anchorPoint) override;

#ifdef CC_STUDIO_ENABLED_VIEW
    // hit test , bonePoint is in self coordinate
    virtual bool isPointOnRack(const cocos2d::Vec2& bonePoint);
#endif

CC_CONSTRUCTOR_ACCESS:
    BoneNode();
    virtual ~BoneNode();
    virtual bool init() override;

protected:

    virtual void addToChildrenListHelper(Node * child);
    virtual void removeFromChildrenListHelper(Node * child);

    // add bone to children bone list, and add bone to skeleton's subbone map
    virtual void addToBoneList(BoneNode* bone);

    // remove bone from children bone list, and remove bone from skeleton's subbone map
    virtual void removeFromBoneList(BoneNode* bone);

    // add skin to skin list
    virtual void addToSkinList(SkinNode* skin);

    // remove skin from skin list
    virtual void removeFromSkinList(SkinNode* skin);

    // sort all _children ,  bone list and skin list
    virtual void sortAllChildren() override;

    virtual void updateVertices();
    virtual void updateColor() override;

    // bone's color and opacity cannot cascade to bone
    virtual void updateDisplayedColor(const cocos2d::Color3B& parentColor) override;
    virtual void updateDisplayedOpacity(GLubyte parentOpacity) override;
    virtual void disableCascadeOpacity() override;
    virtual void disableCascadeColor() override;

    virtual void onDraw(const cocos2d::Mat4 &transform, uint32_t flags);

    // override Node::visit, just visit bones in children
    virtual void visit(cocos2d::Renderer *renderer, const cocos2d::Mat4& parentTransform, uint32_t parentFlags) override;

    // a help function for SkeletonNode
    // for batch bone's draw to _rootSkeleton
    virtual void batchBoneDrawToSkeleton(BoneNode* bone) const;

    // a help function for SkeletonNode
    // @param bone, visit bone's skins
    virtual void visitSkins(cocos2d::Renderer* renderer, BoneNode* bone) const;

    // a help function for SkeletonNode
    // set bone's rootSkeleton = skeleton
    void setRootSkeleton(BoneNode* bone, SkeletonNode* skeleton) const;
protected:
    cocos2d::CustomCommand _customCommand;
    cocos2d::BlendFunc     _blendFunc;

    bool              _isRackShow;
    cocos2d::Color4F  _rackColor;
    int               _rackLength;
    int               _rackWidth;

    cocos2d::Vector<BoneNode*> _childBones;
    cocos2d::Vector<SkinNode*> _boneSkins;
    SkeletonNode*              _rootSkeleton;
private:
    cocos2d::Vec2          _squareVertices[4];
    cocos2d::Color4F       _squareColors[4];
    cocos2d::Vec3          _noMVPVertices[4];
    CC_DISALLOW_COPY_AND_ASSIGN(BoneNode);
};

NS_TIMELINE_END
#endif //__CCBONENODE_H__

redpajama_set_name: RedPajamaGithub


text:
@font-face{
    font-family: 'JetBrains Mono';
    src: url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/web/JetBrainsMono-Regular.eot') format('embedded-opentype'),
         url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/webfonts/JetBrainsMono-Regular.woff2') format('woff2'),
         url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/ttf/JetBrainsMono-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face{
    font-family: 'JetBrains Mono';
    src: url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/web/JetBrainsMono-Bold.eot') format('embedded-opentype'),
         url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/webfonts/JetBrainsMono-Bold.woff2') format('woff2'),
         url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/ttf/JetBrainsMono-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: bold;
}


text:
function varargout = getunit(unit,varargin)
% GETUNIT  returns unit information or converts units.
%__________________________________________________________________________
% SYNTAX:
%   label = getunit(unit)
%   label = getunit(unit,format)
%   [new_number,new_unit] = getunit(unit,'convert',number)
%   [new_number,new_unit] = getunit(unit,'convert',number,conversion)
%
% DESCRIPTION:
%   label = getunit(unit) returns a text string of the unit
%   label = getunit(unit,format) returns a plot axis label in the desired
%       format of 'latex', 'tex', or 'none'. The usage of normal is the
%       same as the above option without the format.
%   [output,unit] = getunit(unit,'convert',number) converts the numeric
%       value in "number" the to the corresponding unit and ouputs the new
%       value and the new unit
%   [output,unit] = getunit(unit,'convert',number,conversion) operates as
%       but utilizes a string ('english' or 'metric') for determining the
%       output units.  If the input is the same as the output nothing
%       changes.
%_________________________________________________________________________

% 1 - PULLS DATA FROM units.txt FILE
    fid = fopen('units.txt');
    form = '%s%s%s%s%s%s%s%f';
    F = textscan(fid,form,'delimiter',',','CommentStyle','#');
    fclose(fid);

% 2 - EXTRACT DATA FOR UNIT INPUT FILE
    %if isnan(unit); varargout = {[],[]}; return; end
    type = ''; unit = strtrim(unit);

    % 2.1 - Search all data for id matches
    for i = 1:length(F{1});

        % 2.1.1 - Determine if the units are metric or english
            metric  = strcmpi(F{1}{i},unit);
            english = strcmpi(F{2}{i},unit);

        % 2.1.2 - Extract data from data read from units.txt
            u = {F{1}{i},F{2}{i},F{3}{i},F{4}{i},...
                    F{5}{i},F{6}{i},F{7}{i},F{8}(i)};

        % 2.1.3 - Exit loop if a match was made
            if metric;  type = 'metric';  desired = 'english'; break; end
            if english; type = 'english'; desired = 'metric';  break; end
     end

    % 2.2 - Exit program if the input is not recongnized
        if isempty(type);
            disp(['The unit, "',unit,'" , was not recongnized.']);
            return;
        end

% 3 - CONVERT UNITS OPTION
    if ~isempty(varargin) && strcmpi(varargin{1},'convert')
        [varargout{1},varargout{2}] = ...
            convertunits(varargin,unit,type,desired,u);
        return;
    end

% 4 - BUILD TEXT LABEL
    % 3.1 - Determine the interpreter
        if isempty(varargin); varargin{1} = 'none'; end
        switch varargin{1};
            case 'latex'; loc = 4;
            case 'tex';   loc = 6;
            otherwise;    loc = 1;
        end

    % 3.2 - Build the character string
        switch type
            case 'metric';  varargout{1} = [u{3},' (',u{loc},')'];
            case 'english'; varargout{1} = [u{3},' (',u{loc+1},')'];
        end

%--------------------------------------------------------------------------
% SUBFUNCTION: convertunits
function [n_out,u_out] = convertunits(input,unit,type,def,u)

% 1 - Test that numeric input is correct
     N = length(input);
     if isempty(input{2});
        errordlg('No value given to convert (getunit.m)','ERROR');
        return;
     elseif ~isnumeric(input{2});
        errordlg('Input must be numeric (getunit.m)','ERROR');
        return;
     else
        num = input{2}; % Input numeric value for converting
        n_out = num; u_out = unit;
     end

% 2 - Determine the ouput units desired (use default if nothing is input)
    % 2.1 - Deterimine the desired output
        if N < 3;
            desired = def;
        else
            desired = input{3};
        end

    % 2.2 - Exit if the desired == type
        if strcmpi(type,desired); return; end

% 3 - Convert the units to the desired output
    % 3.1 - Convert units using custom function (6999 in units.txt)
    if u{8} == 6999;
        [n_out,u_out] = custom(unit,u,type,num);

    % 3.2 - Convert units using multiplier in units.txt
     else
        switch type
            case 'metric';
                n_out = num.*u{8}; u_out = u{2};
            case 'english';
                n_out = num./u{8}; u_out = u{1};
        end
     end

%--------------------------------------------------------------------------
% SUBFUNCTION: CUSTOM - converts units such as temperature that are not
%                       a straight multiplier
function [n_out,u_out] = custom(unit,u,type,num)

switch unit
    % 4.1 - Temperature Conversion
    case {'C','F'}
        switch type
            case 'metric';  n_out = (9/5).*num + 32;    u_out = u{2};
            case 'english'; n_out = (5/9).*(num - 32);  u_out = u{1};
        end
end


text:
Dodger
======

Generating safe trajectories in stochastic dynamic environment by leveraging
information about obstacle motion.

# Install

To make use of the ROS enable features of Dodger, please install ROS Indigo.
Instructions can be found
[here](http://wiki.ros.org/indigo/Installation/Ubuntu). Note that this project
has been tested using Ubuntu 14.04. To build Dodger, see the command line
instructions below.

    $ git clone https://github.com/wallarelvo/Dodger.git && cd Dodger
    $ ./install.sh

# Examples

Scripts are provided to showcase Dodger. To visualize a particular scenario
using Matplotlib, run

    $ scripts/easy_run.sh [name of example]

A number of examples are given in the `examples/` directory. Also, the command
line argument provided to `scripts/easy_run.sh` excludes the `.cpp` extension.
To visualize a particular scenario using RViz run

    $ roslaunch config/tf.launch &
    $ rosrun rviz rviz -d config/config.rviz &
    $ scripts/easy_ros.sh [name of example]

This script has the same constraints for example names as for the Matplotlib
example.


text:
Formato del mensaje

Si utiliza «Auto detectar» el mensaje será considerado HTML en cuanto se encuentre la primera etiqueta HTML (< ... >).

No hay problema en dejar seleccionado «Auto detectar».

Si no está seguro de si «Auto detectar» funciona, y el mensaje que está pegando ha sido formateado en HTML, escoja «HTML».
Referencias a recursos externos (p. ej. imágenes) requieren la URL completa, es decir incluyendo el «http://» (al contrario que las imágines de las plantillas).
En todo lo demás, el formato del texto depende enteramente de usted.

Si quiere que el mensaje se envíe a todos en texto plano, seleccione «Texto».

Esta información se usa para crear la versión en texto plano de un correo HTML, o la versión HTML de un mensaje en texto plano.
El formateado será así:

El original es HTML -> texto plano

El texto en negritas aparecerá enmarcado por *-asteriscos, el texto en cursiva por /-barras.

Los enlaces serán sustituídos por el texto del enlace, seguido por la URL entre paréntesis.

Los fragmentos de texto largos quedarán divididos en líneas de un máximo de 70 caracteres, sin dividir palabras.

El original es Texto -> HTML

Dos saltos de línea seguidos serán sustituídos por <p> (párrafo)

Un sólo salto de línea será sustituído por <br /> (salto de línea)

Se podrá pinchar en las direcciones de correo electrónico

Se podrá pinchar en las URL. Estas pueden tener los siguientes formatos:

http://cierta.página.url/cierta/dirección/fichero.html

www.urlsitioweb.com

Los enlaces creados tendrán, con respecto a la hoja de estilo, class «url» y target «_blank».

Advertencia: Si indica que su mensaje es texto plano, pero pega un texto HTML en el formulario, los usuarios que han escogido recibir mensajes en texto plano recibirán el mensaje con las etiquetas HTML visibles.


text:
using namespace DKFramework;
using namespace DKFramework::Private::Vulkan;

ImageView::ImageView(Image* img, VkImageView view, const VkImageViewCreateInfo& ci)
    : image(img)
    , imageView(view)
    , device(img->device)
    , signalSemaphore(VK_NULL_HANDLE)
    , waitSemaphore(VK_NULL_HANDLE)
{
}

ImageView::ImageView(DKGraphicsDevice* dev, VkImageView view)
    : image(nullptr)
    , imageView(view)
    , device(dev)
    , signalSemaphore(VK_NULL_HANDLE)
    , waitSemaphore(VK_NULL_HANDLE)
{
}

ImageView::~ImageView()
{
    GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(device);

    if (imageView)
        vkDestroyImageView(dev->device, imageView, dev->allocationCallbacks);
    if (signalSemaphore)
        vkDestroySemaphore(dev->device, signalSemaphore, dev->allocationCallbacks);
    if (waitSemaphore)
        vkDestroySemaphore(dev->device, waitSemaphore, dev->allocationCallbacks);
}

#endif //#if DKGL_ENABLE_VULKAN


text:
package org.jetbrains.idea.devkit.dom.impl;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.references.PomService;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopesCore;
import com.intellij.psi.search.ProjectScope;
import com.intellij.util.Processor;
import com.intellij.util.xml.ConvertContext;
import com.intellij.util.xml.DomTarget;
import com.intellij.util.xml.ElementPresentationManager;
import com.intellij.util.xml.ResolvingConverter;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.DevKitBundle;
import org.jetbrains.idea.devkit.dom.Action;
import org.jetbrains.idea.devkit.dom.ActionOrGroup;
import org.jetbrains.idea.devkit.dom.Group;
import org.jetbrains.idea.devkit.dom.index.IdeaPluginRegistrationIndex;

import java.util.*;

public class ActionOrGroupResolveConverter extends ResolvingConverter<ActionOrGroup> {

  @NotNull
  @Override
  public Collection<? extends ActionOrGroup> getVariants(ConvertContext context) {
    final List<ActionOrGroup> variants = new ArrayList<>();
    final Set<String> processedVariants = new HashSet<>();

    processScopes(context, scope -> {
      IdeaPluginRegistrationIndex.processAllActionOrGroup(context.getProject(), scope, actionOrGroup -> {
        if (isRelevant(actionOrGroup) && processedVariants.add(getName(actionOrGroup))) {
          variants.add(actionOrGroup);
        }
        return true;
      });
      return true;
    });
    return variants;
  }

  @Nullable
  @Override
  public PsiElement getPsiElement(@Nullable ActionOrGroup resolvedValue) {
    if (resolvedValue == null) return null;
    DomTarget target = DomTarget.getTarget(resolvedValue);
    return target == null ? super.getPsiElement(resolvedValue) : PomService.convertToPsi(target);
  }

  @Nullable
  @Override
  public ActionOrGroup fromString(@Nullable @NonNls final String value, ConvertContext context) {
    if (StringUtil.isEmptyOrSpaces(value)) return null;

    final Project project = context.getProject();
    Ref<ActionOrGroup> result = Ref.create();
    processScopes(context, scope -> {
      return IdeaPluginRegistrationIndex.processActionOrGroup(project, value, scope, actionOrGroup -> {
        if (isRelevant(actionOrGroup)) {
          result.set(actionOrGroup);
          return false;
        }
        return true;
      });
    });
    return result.get();
  }

  @Nullable
  @Override
  public String toString(@Nullable ActionOrGroup actionGroup, ConvertContext context) {
    return actionGroup == null ? null : getName(actionGroup);
  }

  @Override
  public String getErrorMessage(@Nullable String s, ConvertContext context) {
    return DevKitBundle.message("plugin.xml.convert.action.or.group.cannot.resolve", getResultTypes(), s);
  }

  @Nullable
  @Override
  public LookupElement createLookupElement(ActionOrGroup actionOrGroup) {
    PsiElement psiElement = getPsiElement(actionOrGroup);
    String name = StringUtil.notNullize(getName(actionOrGroup), DevKitBundle.message("plugin.xml.convert.action.or.group.invalid.name"));
    LookupElementBuilder builder = psiElement == null ? LookupElementBuilder.create(name) :
                                   LookupElementBuilder.create(psiElement, name);

    builder = builder.withItemTextUnderlined(actionOrGroup.getPopup().getValue() == Boolean.TRUE);
    builder = builder.withIcon(ElementPresentationManager.getIcon(actionOrGroup));

    final String text = actionOrGroup.getText().getStringValue();
    if (StringUtil.isNotEmpty(text)) {
      String withoutMnemonic = StringUtil.replace(text, "_", "");
      builder = builder.withTailText(" \"" + withoutMnemonic + "\"", true);
    }

    final String description = actionOrGroup.getDescription().getStringValue();
    if (StringUtil.isNotEmpty(description)) {
      builder = builder.withTypeText(description);
    }

    return builder;
  }

  protected boolean isRelevant(ActionOrGroup actionOrGroup) {
    return true;
  }

  @Nls
  protected String getResultTypes() {
    return DevKitBundle.message("plugin.xml.convert.action.or.group.type.action.or.group");
  }

  public static class OnlyActions extends ActionOrGroupResolveConverter {
    @Override
    protected boolean isRelevant(ActionOrGroup actionOrGroup) {
      return actionOrGroup instanceof Action;
    }

    @Override
    protected String getResultTypes() {
      return DevKitBundle.message("plugin.xml.convert.action.or.group.type.action");
    }
  }

  public static class OnlyGroups extends ActionOrGroupResolveConverter {
    @Override
    protected boolean isRelevant(ActionOrGroup actionOrGroup) {
      return actionOrGroup instanceof Group;
    }

    @Override
    protected String getResultTypes() {
      return DevKitBundle.message("plugin.xml.convert.action.or.group.type.group");
    }
  }

  private static void processScopes(ConvertContext context,
                                    final Processor<GlobalSearchScope> processor) {
    final Project project = context.getProject();

    Module module = context.getModule();
    if (module == null) {
      final GlobalSearchScope projectScope = GlobalSearchScopesCore.projectProductionScope(project).
        union(ProjectScope.getLibrariesScope(project));
      processor.process(projectScope);
      return;
    }

    ModuleUtilCore.visitMeAndDependentModules(module, module1 -> {
      return processor.process(module1.getModuleRuntimeScope(false));
    });
  }

  @Nullable
  private static String getName(@NotNull ActionOrGroup actionOrGroup) {
    return actionOrGroup.getId().getStringValue();
  }
}


text:
package async

/*

Parallel is a shorthand function to List.RunParallel without having to
manually create a new list, add the routines, etc.

*/
func Parallel(routines []Routine, callbacks ...Done) {
	l := New()
	l.Multiple(routines...)

	l.RunParallel(callbacks...)
}

/*

RunParallel will run all of the Routine functions from the current list in
parallel mode.

All of the arguments returned in a Routine's Done function will be combined
and returned in the callbacks that are provided.

If there is an error, any further results will be discarded but it will not
immediately exit. It will continue to run all of the other Routine functions
that were passed into it. This is because by the time the error is sent, the
goroutines have already been started. At this current time, there is no way
to cancel a sleep timer in Go.

For example:
  async.Parallel([]async.Routine{
    func(done async.Done, args ...interface{}) {
      time.Sleep(20 * time.Second)
      done(nil, "Won't trigger the callbacks because error has been sent")
    },
    func(done async.Done, args ...interface{}) {
      done(fmt.Errorf("Test error"))
    }
  }, func(err error, results ...interface{}) {
    if err != nil {
      fmt.Printf("Error: %s", err)
      return
    }

    fmt.Printf("Args: %s", args)
  })

If you were to run this example, you would see the error happen immediately.
However, you would also notice that the program doesn't immediately exit.
That is because it is still waiting for responses that it silently discards,
since an error has already occurred.

*/
func (l *List) RunParallel(callbacks ...Done) {
	var (
		results = make([]interface{}, 0)

		result = make(chan interface{})

		_error error

		final = func(err error, results ...interface{}) {
			for i := 0; i < len(callbacks); i++ {
				if err != nil {
					callbacks[i](err)
				} else {
					callbacks[i](err, results...)
				}
			}
		}
	)

	defer close(result)

	l.Wait.Add(l.Len())

	go func() {
		for {
			r := <-result

			if _error != nil {
				continue
			}

			switch r.(type) {
			case error:
				_error = r.(error)
				final(_error)

			case []interface{}:
				results = append(results, r.([]interface{})...)
			}
		}
	}()

	for l.Len() > 0 {
		e := l.Front()
		_, r := l.Remove(e)

		go r(func(err error, args ...interface{}) {
			defer l.Wait.Done()

			if err != nil {
				result <- err
				return
			}

			result <- args
		})
	}

	l.Wait.Wait()

	if _error == nil {
		final(nil, results...)
	}
}


text:
/*
  Inspired by:
  - https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go
*/
package agent

import (
	"fmt"
	"net"

	"github.com/tangfeixiong/go-to-bigdata/nta/pb"
)

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L57

// registerWithAPIServer registers the node with the cluster master. It is safe
// to call multiple times, but not concurrently (kl.registrationCompleted is
// not locked).
func (kl *Kubelet) registerWithAPIServer() {
	if kl.registrationCompleted {
		return
	}
	step := 100 * time.Millisecond

	for {
		time.Sleep(step)
		step = step * 2
		if step >= 7*time.Second {
			step = 7 * time.Second
		}

		node, err := kl.initialNode()
		if err != nil {
			glog.Errorf("Unable to construct v1.Node object for kubelet: %v", err)
			continue
		}

		glog.Infof("Attempting to register node %s", node.Name)
		registered := kl.tryRegisterWithAPIServer(node)
		if registered {
			glog.Infof("Successfully registered node %s", node.Name)
			kl.registrationCompleted = true
			return
		}
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L89

// tryRegisterWithAPIServer makes an attempt to register the given node with
// the API server, returning a boolean indicating whether the attempt was
// successful.  If a node with the same name already exists, it reconciles the
// value of the annotation for controller-managed attach-detach of attachable
// persistent volumes for the node.  If a node of the same name exists but has
// a different externalID value, it attempts to delete that node so that a
// later attempt can recreate it.
func (kl *Kubelet) tryRegisterWithAPIServer(node *v1.Node) bool {
	_, err := kl.kubeClient.CoreV1().Nodes().Create(node)
	if err == nil {
		return true
	}

	if !apierrors.IsAlreadyExists(err) {
		glog.Errorf("Unable to register node %q with API server: %v", kl.nodeName, err)
		return false
	}

	existingNode, err := kl.kubeClient.CoreV1().Nodes().Get(string(kl.nodeName), metav1.GetOptions{})
	if err != nil {
		glog.Errorf("Unable to register node %q with API server: error getting existing node: %v", kl.nodeName, err)
		return false
	}
	if existingNode == nil {
		glog.Errorf("Unable to register node %q with API server: no node instance returned", kl.nodeName)
		return false
	}

	originalNode := existingNode.DeepCopy()
	if originalNode == nil {
		glog.Errorf("Nil %q node object", kl.nodeName)
		return false
	}

	glog.Infof("Node %s was previously registered", kl.nodeName)

	// Edge case: the node was previously registered; reconcile
	// the value of the controller-managed attach-detach
	// annotation.
	requiresUpdate := kl.reconcileCMADAnnotationWithExistingNode(node, existingNode)
	requiresUpdate = kl.updateDefaultLabels(node, existingNode) || requiresUpdate
	if requiresUpdate {
		if _, _, err := nodeutil.PatchNodeStatus(kl.kubeClient.CoreV1(), types.NodeName(kl.nodeName), originalNode, existingNode); err != nil {
			glog.Errorf("Unable to reconcile node %q with API server: error updating node: %v", kl.nodeName, err)
			return false
		}
	}

	return true
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L201

// initialNode constructs the initial v1.Node for this Kubelet, incorporating node
// labels, information from the cloud provider, and Kubelet configuration.
func (kl *Kubelet) initialNode() (*v1.Node, error) {
	node := &v1.Node{
		ObjectMeta: metav1.ObjectMeta{
			Name: string(kl.nodeName),
			Labels: map[string]string{
				kubeletapis.LabelHostname: kl.hostname,
				kubeletapis.LabelOS:       goruntime.GOOS,
				kubeletapis.LabelArch:     goruntime.GOARCH,
			},
		},
		Spec: v1.NodeSpec{
			Unschedulable: !kl.registerSchedulable,
		},
	}
	nodeTaints := make([]v1.Taint, 0)
	if len(kl.registerWithTaints) > 0 {
		taints := make([]v1.Taint, len(kl.registerWithTaints))
		for i := range kl.registerWithTaints {
			if err := k8s_api_v1.Convert_core_Taint_To_v1_Taint(&kl.registerWithTaints[i], &taints[i], nil); err != nil {
				return nil, err
			}
		}
		nodeTaints = append(nodeTaints, taints...)
	}
	if kl.externalCloudProvider {
		taint := v1.Taint{
			Key:    algorithm.TaintExternalCloudProvider,
			Value:  "true",
			Effect: v1.TaintEffectNoSchedule,
		}

		nodeTaints = append(nodeTaints, taint)
	}
	if len(nodeTaints) > 0 {
		node.Spec.Taints = nodeTaints
	}
	// Initially, set NodeNetworkUnavailable to true.
	if kl.providerRequiresNetworkingConfiguration() {
		node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{
			Type:               v1.NodeNetworkUnavailable,
			Status:             v1.ConditionTrue,
			Reason:             "NoRouteCreated",
			Message:            "Node created without a route",
			LastTransitionTime: metav1.NewTime(kl.clock.Now()),
		})
	}

	if kl.enableControllerAttachDetach {
		if node.Annotations == nil {
			node.Annotations = make(map[string]string)
		}

		glog.Infof("Setting node annotation to enable volume controller attach/detach")
		node.Annotations[volutil.ControllerManagedAttachAnnotation] = "true"
	} else {
		glog.Infof("Controller attach/detach is disabled for this node; Kubelet will attach and detach volumes")
	}

	if kl.keepTerminatedPodVolumes {
		if node.Annotations == nil {
			node.Annotations = make(map[string]string)
		}
		glog.Infof("Setting node annotation to keep pod volumes of terminated pods attached to the node")
		node.Annotations[volutil.KeepTerminatedPodVolumesAnnotation] = "true"
	}

	// @question: should this be place after the call to the cloud provider? which also applies labels
	for k, v := range kl.nodeLabels {
		if cv, found := node.ObjectMeta.Labels[k]; found {
			glog.Warningf("the node label %s=%s will overwrite default setting %s", k, v, cv)
		}
		node.ObjectMeta.Labels[k] = v
	}

	if kl.providerID != "" {
		node.Spec.ProviderID = kl.providerID
	}

	if kl.cloud != nil {
		instances, ok := kl.cloud.Instances()
		if !ok {
			return nil, fmt.Errorf("failed to get instances from cloud provider")
		}

		// TODO: We can't assume that the node has credentials to talk to the
		// cloudprovider from arbitrary nodes. At most, we should talk to a
		// local metadata server here.
		var err error
		if node.Spec.ProviderID == "" {
			node.Spec.ProviderID, err = cloudprovider.GetInstanceProviderID(context.TODO(), kl.cloud, kl.nodeName)
			if err != nil {
				return nil, err
			}
		}

		instanceType, err := instances.InstanceType(context.TODO(), kl.nodeName)
		if err != nil {
			return nil, err
		}
		if instanceType != "" {
			glog.Infof("Adding node label from cloud provider: %s=%s", kubeletapis.LabelInstanceType, instanceType)
			node.ObjectMeta.Labels[kubeletapis.LabelInstanceType] = instanceType
		}
		// If the cloud has zone information, label the node with the zone information
		zones, ok := kl.cloud.Zones()
		if ok {
			zone, err := zones.GetZone(context.TODO())
			if err != nil {
				return nil, fmt.Errorf("failed to get zone from cloud provider: %v", err)
			}
			if zone.FailureDomain != "" {
				glog.Infof("Adding node label from cloud provider: %s=%s", kubeletapis.LabelZoneFailureDomain, zone.FailureDomain)
				node.ObjectMeta.Labels[kubeletapis.LabelZoneFailureDomain] = zone.FailureDomain
			}
			if zone.Region != "" {
				glog.Infof("Adding node label from cloud provider: %s=%s", kubeletapis.LabelZoneRegion, zone.Region)
				node.ObjectMeta.Labels[kubeletapis.LabelZoneRegion] = zone.Region
			}
		}
	}

	kl.setNodeStatus(node)

	return node, nil
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L409
// Set IP and hostname addresses for the node.
// func (kl *Kubelet) setNodeAddress(node *v1.Node) error {
func (kl *Agent) setNodeAddress(node *v1.Node) error {
	if kl.nodeIP != nil {
		if err := kl.nodeIPValidator(kl.nodeIP); err != nil {
			return fmt.Errorf("failed to validate nodeIP: %v", err)
		}
		glog.V(2).Infof("Using node IP: %q", kl.nodeIP.String())
	}

	if kl.externalCloudProvider {
		if kl.nodeIP != nil {
			if node.ObjectMeta.Annotations == nil {
				node.ObjectMeta.Annotations = make(map[string]string)
			}
			node.ObjectMeta.Annotations[kubeletapis.AnnotationProvidedIPAddr] = kl.nodeIP.String()
		}
		// We rely on the external cloud provider to supply the addresses.
		return nil
	}
	if kl.cloud != nil {
		instances, ok := kl.cloud.Instances()
		if !ok {
			return fmt.Errorf("failed to get instances from cloud provider")
		}
		// TODO(roberthbailey): Can we do this without having credentials to talk
		// to the cloud provider?
		// TODO(justinsb): We can if CurrentNodeName() was actually CurrentNode() and returned an interface
		// TODO: If IP addresses couldn't be fetched from the cloud provider, should kubelet fallback on the other methods for getting the IP below?
		var nodeAddresses []v1.NodeAddress
		var err error

		// Make sure the instances.NodeAddresses returns even if the cloud provider API hangs for a long time
		func() {
			kl.cloudproviderRequestMux.Lock()
			if len(kl.cloudproviderRequestParallelism) > 0 {
				kl.cloudproviderRequestMux.Unlock()
				return
			}
			kl.cloudproviderRequestParallelism <- 0
			kl.cloudproviderRequestMux.Unlock()

			go func() {
				nodeAddresses, err = instances.NodeAddresses(context.TODO(), kl.nodeName)

				kl.cloudproviderRequestMux.Lock()
				<-kl.cloudproviderRequestParallelism
				kl.cloudproviderRequestMux.Unlock()

				kl.cloudproviderRequestSync <- 0
			}()
		}()

		select {
		case <-kl.cloudproviderRequestSync:
		case <-time.After(kl.cloudproviderRequestTimeout):
			err = fmt.Errorf("Timeout after %v", kl.cloudproviderRequestTimeout)
		}

		if err != nil {
			return fmt.Errorf("failed to get node address from cloud provider: %v", err)
		}
		if kl.nodeIP != nil {
			enforcedNodeAddresses := []v1.NodeAddress{}

			var nodeIPType v1.NodeAddressType
			for _, nodeAddress := range nodeAddresses {
				if nodeAddress.Address == kl.nodeIP.String() {
					enforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address})
					nodeIPType = nodeAddress.Type
					break
				}
			}
			if len(enforcedNodeAddresses) > 0 {
				for _, nodeAddress := range nodeAddresses {
					if nodeAddress.Type != nodeIPType && nodeAddress.Type != v1.NodeHostName {
						enforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address})
					}
				}

				enforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: v1.NodeHostName, Address: kl.GetHostname()})
				node.Status.Addresses = enforcedNodeAddresses
				return nil
			}
			return fmt.Errorf("failed to get node address from cloud provider that matches ip: %v", kl.nodeIP)
		}

		// Only add a NodeHostName address if the cloudprovider did not specify one
		// (we assume the cloudprovider knows best)
		var addressNodeHostName *v1.NodeAddress
		for i := range nodeAddresses {
			if nodeAddresses[i].Type == v1.NodeHostName {
				addressNodeHostName = &nodeAddresses[i]
				break
			}
		}
		if addressNodeHostName == nil {
			hostnameAddress := v1.NodeAddress{Type: v1.NodeHostName, Address: kl.GetHostname()}
			nodeAddresses = append(nodeAddresses, hostnameAddress)
		} else {
			glog.V(2).Infof("Using Node Hostname from cloudprovider: %q", addressNodeHostName.Address)
		}
		node.Status.Addresses = nodeAddresses
	} else {
		var ipAddr net.IP
		var err error

		// 1) Use nodeIP if set
		// 2) If the user has specified an IP to HostnameOverride, use it
		// 3) Lookup the IP from node name by DNS and use the first valid IPv4 address.
		//    If the node does not have a valid IPv4 address, use the first valid IPv6 address.
		// 4) Try to get the IP from the network interface used as default gateway
		if kl.nodeIP != nil {
			ipAddr = kl.nodeIP
		} else if addr := net.ParseIP(kl.hostname); addr != nil {
			ipAddr = addr
		} else {
			var addrs []net.IP
			addrs, _ = net.LookupIP(node.Name)
			for _, addr := range addrs {
				if err = kl.nodeIPValidator(addr); err == nil {
					if addr.To4() != nil {
						ipAddr = addr
						break
					}
					if addr.To16() != nil && ipAddr == nil {
						ipAddr = addr
					}
				}
			}

			if ipAddr == nil {
				ipAddr, err = utilnet.ChooseHostInterface()
			}
		}

		if ipAddr == nil {
			// We tried everything we could, but the IP address wasn't fetchable; error out
			return fmt.Errorf("can't get ip address of node %s. error: %v", node.Name, err)
		}
		node.Status.Addresses = []v1.NodeAddress{
			{Type: v1.NodeInternalIP, Address: ipAddr.String()},
			{Type: v1.NodeHostName, Address: kl.GetHostname()},
		}
	}
	return nil
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L556
func (kl *Kubelet) setNodeStatusMachineInfo(node *v1.Node) {
	// Note: avoid blindly overwriting the capacity in case opaque
	//       resources are being advertised.
	if node.Status.Capacity == nil {
		node.Status.Capacity = v1.ResourceList{}
	}

	var devicePluginAllocatable v1.ResourceList
	var devicePluginCapacity v1.ResourceList
	var removedDevicePlugins []string

	// TODO: Post NotReady if we cannot get MachineInfo from cAdvisor. This needs to start
	// cAdvisor locally, e.g. for test-cmd.sh, and in integration test.
	info, err := kl.GetCachedMachineInfo()
	if err != nil {
		// TODO(roberthbailey): This is required for test-cmd.sh to pass.
		// See if the test should be updated instead.
		node.Status.Capacity[v1.ResourceCPU] = *resource.NewMilliQuantity(0, resource.DecimalSI)
		node.Status.Capacity[v1.ResourceMemory] = resource.MustParse("0Gi")
		node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(int64(kl.maxPods), resource.DecimalSI)
		glog.Errorf("Error getting machine info: %v", err)
	} else {
		node.Status.NodeInfo.MachineID = info.MachineID
		node.Status.NodeInfo.SystemUUID = info.SystemUUID

		for rName, rCap := range cadvisor.CapacityFromMachineInfo(info) {
			node.Status.Capacity[rName] = rCap
		}

		if kl.podsPerCore > 0 {
			node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(
				int64(math.Min(float64(info.NumCores*kl.podsPerCore), float64(kl.maxPods))), resource.DecimalSI)
		} else {
			node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(
				int64(kl.maxPods), resource.DecimalSI)
		}

		if node.Status.NodeInfo.BootID != "" &&
			node.Status.NodeInfo.BootID != info.BootID {
			// TODO: This requires a transaction, either both node status is updated
			// and event is recorded or neither should happen, see issue #6055.
			kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.NodeRebooted,
				"Node %s has been rebooted, boot id: %s", kl.nodeName, info.BootID)
		}
		node.Status.NodeInfo.BootID = info.BootID

		if utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
			// TODO: all the node resources should use GetCapacity instead of deriving the
			// capacity for every node status request
			initialCapacity := kl.containerManager.GetCapacity()
			if initialCapacity != nil {
				node.Status.Capacity[v1.ResourceEphemeralStorage] = initialCapacity[v1.ResourceEphemeralStorage]
			}
		}

		devicePluginCapacity, devicePluginAllocatable, removedDevicePlugins = kl.containerManager.GetDevicePluginResourceCapacity()
		if devicePluginCapacity != nil {
			for k, v := range devicePluginCapacity {
				if old, ok := node.Status.Capacity[k]; !ok || old.Value() != v.Value() {
					glog.V(2).Infof("Update capacity for %s to %d", k, v.Value())
				}
				node.Status.Capacity[k] = v
			}
		}

		for _, removedResource := range removedDevicePlugins {
			glog.V(2).Infof("Set capacity for %s to 0 on device removal", removedResource)
			// Set the capacity of the removed resource to 0 instead of
			// removing the resource from the node status. This is to indicate
			// that the resource is managed by device plugin and had been
			// registered before.
			//
			// This is required to differentiate the device plugin managed
			// resources and the cluster-level resources, which are absent in
			// node status.
			node.Status.Capacity[v1.ResourceName(removedResource)] = *resource.NewQuantity(int64(0), resource.DecimalSI)
		}
	}

	// Set Allocatable.
	if node.Status.Allocatable == nil {
		node.Status.Allocatable = make(v1.ResourceList)
	}
	// Remove extended resources from allocatable that are no longer
	// present in capacity.
	for k := range node.Status.Allocatable {
		_, found := node.Status.Capacity[k]
		if !found && v1helper.IsExtendedResourceName(k) {
			delete(node.Status.Allocatable, k)
		}
	}
	allocatableReservation := kl.containerManager.GetNodeAllocatableReservation()
	for k, v := range node.Status.Capacity {
		value := *(v.Copy())
		if res, exists := allocatableReservation[k]; exists {
			value.Sub(res)
		}
		if value.Sign() < 0 {
			// Negative Allocatable resources don't make sense.
			value.Set(0)
		}
		node.Status.Allocatable[k] = value
	}

	if devicePluginAllocatable != nil {
		for k, v := range devicePluginAllocatable {
			if old, ok := node.Status.Allocatable[k]; !ok || old.Value() != v.Value() {
				glog.V(2).Infof("Update allocatable for %s to %d", k, v.Value())
			}
			node.Status.Allocatable[k] = v
		}
	}
	// for every huge page reservation, we need to remove it from allocatable memory
	for k, v := range node.Status.Capacity {
		if v1helper.IsHugePageResourceName(k) {
			allocatableMemory := node.Status.Allocatable[v1.ResourceMemory]
			value := *(v.Copy())
			allocatableMemory.Sub(value)
			if allocatableMemory.Sign() < 0 {
				// Negative Allocatable resources don't make sense.
				allocatableMemory.Set(0)
			}
			node.Status.Allocatable[v1.ResourceMemory] = allocatableMemory
		}
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L683
// Set versioninfo for the node.
func (kl *Kubelet) setNodeStatusVersionInfo(node *v1.Node) {
	verinfo, err := kl.cadvisor.VersionInfo()
	if err != nil {
		glog.Errorf("Error getting version info: %v", err)
		return
	}

	node.Status.NodeInfo.KernelVersion = verinfo.KernelVersion
	node.Status.NodeInfo.OSImage = verinfo.ContainerOsVersion

	runtimeVersion := "Unknown"
	if runtimeVer, err := kl.containerRuntime.Version(); err == nil {
		runtimeVersion = runtimeVer.String()
	}
	node.Status.NodeInfo.ContainerRuntimeVersion = fmt.Sprintf("%s://%s", kl.containerRuntime.Type(), runtimeVersion)

	node.Status.NodeInfo.KubeletVersion = version.Get().String()
	// TODO: kube-proxy might be different version from kubelet in the future
	node.Status.NodeInfo.KubeProxyVersion = version.Get().String()
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L705
// Set daemonEndpoints for the node.
func (kl *Kubelet) setNodeStatusDaemonEndpoints(node *v1.Node) {
	node.Status.DaemonEndpoints = *kl.daemonEndpoints
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L710
// Set images list for the node
func (kl *Kubelet) setNodeStatusImages(node *v1.Node) {
	// Update image list of this node
	var imagesOnNode []v1.ContainerImage
	containerImages, err := kl.imageManager.GetImageList()
	if err != nil {
		glog.Errorf("Error getting image list: %v", err)
		node.Status.Images = imagesOnNode
		return
	}
	// sort the images from max to min, and only set top N images into the node status.
	if int(kl.nodeStatusMaxImages) > -1 &&
		int(kl.nodeStatusMaxImages) < len(containerImages) {
		containerImages = containerImages[0:kl.nodeStatusMaxImages]
	}

	for _, image := range containerImages {
		names := append(image.RepoDigests, image.RepoTags...)
		// Report up to maxNamesPerImageInNodeStatus names per image.
		if len(names) > maxNamesPerImageInNodeStatus {
			names = names[0:maxNamesPerImageInNodeStatus]
		}
		imagesOnNode = append(imagesOnNode, v1.ContainerImage{
			Names:     names,
			SizeBytes: image.Size,
		})
	}

	node.Status.Images = imagesOnNode
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L741
// Set the GOOS and GOARCH for this node
func (kl *Kubelet) setNodeStatusGoRuntime(node *v1.Node) {
	node.Status.NodeInfo.OperatingSystem = goruntime.GOOS
	node.Status.NodeInfo.Architecture = goruntime.GOARCH
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L747
// Set status for the node.
func (kl *Kubelet) setNodeStatusInfo(node *v1.Node) {
	kl.setNodeStatusMachineInfo(node)
	kl.setNodeStatusVersionInfo(node)
	kl.setNodeStatusDaemonEndpoints(node)
	kl.setNodeStatusImages(node)
	kl.setNodeStatusGoRuntime(node)
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L757
// Set Ready condition for the node.
func (kl *Kubelet) setNodeReadyCondition(node *v1.Node) {
	// NOTE(aaronlevy): NodeReady condition needs to be the last in the list of node conditions.
	// This is due to an issue with version skewed kubelet and master components.
	// ref: https://github.com/kubernetes/kubernetes/issues/16961
	currentTime := metav1.NewTime(kl.clock.Now())
	newNodeReadyCondition := v1.NodeCondition{
		Type:              v1.NodeReady,
		Status:            v1.ConditionTrue,
		Reason:            "KubeletReady",
		Message:           "kubelet is posting ready status",
		LastHeartbeatTime: currentTime,
	}
	rs := append(kl.runtimeState.runtimeErrors(), kl.runtimeState.networkErrors()...)
	requiredCapacities := []v1.ResourceName{v1.ResourceCPU, v1.ResourceMemory, v1.ResourcePods}
	if utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
		requiredCapacities = append(requiredCapacities, v1.ResourceEphemeralStorage)
	}
	missingCapacities := []string{}
	for _, resource := range requiredCapacities {
		if _, found := node.Status.Capacity[resource]; !found {
			missingCapacities = append(missingCapacities, string(resource))
		}
	}
	if len(missingCapacities) > 0 {
		rs = append(rs, fmt.Sprintf("Missing node capacity for resources: %s", strings.Join(missingCapacities, ", ")))
	}
	if len(rs) > 0 {
		newNodeReadyCondition = v1.NodeCondition{
			Type:              v1.NodeReady,
			Status:            v1.ConditionFalse,
			Reason:            "KubeletNotReady",
			Message:           strings.Join(rs, ","),
			LastHeartbeatTime: currentTime,
		}
	}
	// Append AppArmor status if it's enabled.
	// TODO(tallclair): This is a temporary message until node feature reporting is added.
	if newNodeReadyCondition.Status == v1.ConditionTrue &&
		kl.appArmorValidator != nil && kl.appArmorValidator.ValidateHost() == nil {
		newNodeReadyCondition.Message = fmt.Sprintf("%s. AppArmor enabled", newNodeReadyCondition.Message)
	}

	// Record any soft requirements that were not met in the container manager.
	status := kl.containerManager.Status()
	if status.SoftRequirements != nil {
		newNodeReadyCondition.Message = fmt.Sprintf("%s. WARNING: %s", newNodeReadyCondition.Message, status.SoftRequirements.Error())
	}

	readyConditionUpdated := false
	needToRecordEvent := false
	for i := range node.Status.Conditions {
		if node.Status.Conditions[i].Type == v1.NodeReady {
			if node.Status.Conditions[i].Status == newNodeReadyCondition.Status {
				newNodeReadyCondition.LastTransitionTime = node.Status.Conditions[i].LastTransitionTime
			} else {
				newNodeReadyCondition.LastTransitionTime = currentTime
				needToRecordEvent = true
			}
			node.Status.Conditions[i] = newNodeReadyCondition
			readyConditionUpdated = true
			break
		}
	}
	if !readyConditionUpdated {
		newNodeReadyCondition.LastTransitionTime = currentTime
		node.Status.Conditions = append(node.Status.Conditions, newNodeReadyCondition)
	}
	if needToRecordEvent {
		if newNodeReadyCondition.Status == v1.ConditionTrue {
			kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeReady)
		} else {
			kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeNotReady)
			glog.Infof("Node became not ready: %+v", newNodeReadyCondition)
		}
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L834
// setNodeMemoryPressureCondition for the node.
// TODO: this needs to move somewhere centralized...
func (kl *Kubelet) setNodeMemoryPressureCondition(node *v1.Node) {
	currentTime := metav1.NewTime(kl.clock.Now())
	var condition *v1.NodeCondition

	// Check if NodeMemoryPressure condition already exists and if it does, just pick it up for update.
	for i := range node.Status.Conditions {
		if node.Status.Conditions[i].Type == v1.NodeMemoryPressure {
			condition = &node.Status.Conditions[i]
		}
	}

	newCondition := false
	// If the NodeMemoryPressure condition doesn't exist, create one
	if condition == nil {
		condition = &v1.NodeCondition{
			Type:   v1.NodeMemoryPressure,
			Status: v1.ConditionUnknown,
		}
		// cannot be appended to node.Status.Conditions here because it gets
		// copied to the slice. So if we append to the slice here none of the
		// updates we make below are reflected in the slice.
		newCondition = true
	}

	// Update the heartbeat time
	condition.LastHeartbeatTime = currentTime

	// Note: The conditions below take care of the case when a new NodeMemoryPressure condition is
	// created and as well as the case when the condition already exists. When a new condition
	// is created its status is set to v1.ConditionUnknown which matches either
	// condition.Status != v1.ConditionTrue or
	// condition.Status != v1.ConditionFalse in the conditions below depending on whether
	// the kubelet is under memory pressure or not.
	if kl.evictionManager.IsUnderMemoryPressure() {
		if condition.Status != v1.ConditionTrue {
			condition.Status = v1.ConditionTrue
			condition.Reason = "KubeletHasInsufficientMemory"
			condition.Message = "kubelet has insufficient memory available"
			condition.LastTransitionTime = currentTime
			kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasInsufficientMemory")
		}
	} else if condition.Status != v1.ConditionFalse {
		condition.Status = v1.ConditionFalse
		condition.Reason = "KubeletHasSufficientMemory"
		condition.Message = "kubelet has sufficient memory available"
		condition.LastTransitionTime = currentTime
		kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasSufficientMemory")
	}

	if newCondition {
		node.Status.Conditions = append(node.Status.Conditions, *condition)
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L890
// setNodePIDPressureCondition for the node.
// TODO: this needs to move somewhere centralized...
func (kl *Kubelet) setNodePIDPressureCondition(node *v1.Node) {
	currentTime := metav1.NewTime(kl.clock.Now())
	var condition *v1.NodeCondition

	// Check if NodePIDPressure condition already exists and if it does, just pick it up for update.
	for i := range node.Status.Conditions {
		if node.Status.Conditions[i].Type == v1.NodePIDPressure {
			condition = &node.Status.Conditions[i]
		}
	}

	newCondition := false
	// If the NodePIDPressure condition doesn't exist, create one
	if condition == nil {
		condition = &v1.NodeCondition{
			Type:   v1.NodePIDPressure,
			Status: v1.ConditionUnknown,
		}
		// cannot be appended to node.Status.Conditions here because it gets
		// copied to the slice. So if we append to the slice here none of the
		// updates we make below are reflected in the slice.
		newCondition = true
	}

	// Update the heartbeat time
	condition.LastHeartbeatTime = currentTime

	// Note: The conditions below take care of the case when a new NodePIDPressure condition is
	// created and as well as the case when the condition already exists. When a new condition
	// is created its status is set to v1.ConditionUnknown which matches either
	// condition.Status != v1.ConditionTrue or
	// condition.Status != v1.ConditionFalse in the conditions below depending on whether
	// the kubelet is under PID pressure or not.
	if kl.evictionManager.IsUnderPIDPressure() {
		if condition.Status != v1.ConditionTrue {
			condition.Status = v1.ConditionTrue
			condition.Reason = "KubeletHasInsufficientPID"
			condition.Message = "kubelet has insufficient PID available"
			condition.LastTransitionTime = currentTime
			kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasInsufficientPID")
		}
	} else if condition.Status != v1.ConditionFalse {
		condition.Status = v1.ConditionFalse
		condition.Reason = "KubeletHasSufficientPID"
		condition.Message = "kubelet has sufficient PID available"
		condition.LastTransitionTime = currentTime
		kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasSufficientPID")
	}

	if newCondition {
		node.Status.Conditions = append(node.Status.Conditions, *condition)
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L946
// setNodeDiskPressureCondition for the node.
// TODO: this needs to move somewhere centralized...
func (kl *Kubelet) setNodeDiskPressureCondition(node *v1.Node) {
	currentTime := metav1.NewTime(kl.clock.Now())
	var condition *v1.NodeCondition

	// Check if NodeDiskPressure condition already exists and if it does, just pick it up for update.
	for i := range node.Status.Conditions {
		if node.Status.Conditions[i].Type == v1.NodeDiskPressure {
			condition = &node.Status.Conditions[i]
		}
	}

	newCondition := false
	// If the NodeDiskPressure condition doesn't exist, create one
	if condition == nil {
		condition = &v1.NodeCondition{
			Type:   v1.NodeDiskPressure,
			Status: v1.ConditionUnknown,
		}
		// cannot be appended to node.Status.Conditions here because it gets
		// copied to the slice. So if we append to the slice here none of the
		// updates we make below are reflected in the slice.
		newCondition = true
	}

	// Update the heartbeat time
	condition.LastHeartbeatTime = currentTime

	// Note: The conditions below take care of the case when a new NodeDiskPressure condition is
	// created and as well as the case when the condition already exists. When a new condition
	// is created its status is set to v1.ConditionUnknown which matches either
	// condition.Status != v1.ConditionTrue or
	// condition.Status != v1.ConditionFalse in the conditions below depending on whether
	// the kubelet is under disk pressure or not.
	if kl.evictionManager.IsUnderDiskPressure() {
		if condition.Status != v1.ConditionTrue {
			condition.Status = v1.ConditionTrue
			condition.Reason = "KubeletHasDiskPressure"
			condition.Message = "kubelet has disk pressure"
			condition.LastTransitionTime = currentTime
			kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasDiskPressure")
		}
	} else if condition.Status != v1.ConditionFalse {
		condition.Status = v1.ConditionFalse
		condition.Reason = "KubeletHasNoDiskPressure"
		condition.Message = "kubelet has no disk pressure"
		condition.LastTransitionTime = currentTime
		kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasNoDiskPressure")
	}

	if newCondition {
		node.Status.Conditions = append(node.Status.Conditions, *condition)
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1003
// Set OODCondition for the node.
func (kl *Kubelet) setNodeOODCondition(node *v1.Node) {
	currentTime := metav1.NewTime(kl.clock.Now())
	var nodeOODCondition *v1.NodeCondition

	// Check if NodeOutOfDisk condition already exists and if it does, just pick it up for update.
	for i := range node.Status.Conditions {
		if node.Status.Conditions[i].Type == v1.NodeOutOfDisk {
			nodeOODCondition = &node.Status.Conditions[i]
		}
	}

	newOODCondition := nodeOODCondition == nil
	if newOODCondition {
		nodeOODCondition = &v1.NodeCondition{}
	}
	if nodeOODCondition.Status != v1.ConditionFalse {
		nodeOODCondition.Type = v1.NodeOutOfDisk
		nodeOODCondition.Status = v1.ConditionFalse
		nodeOODCondition.Reason = "KubeletHasSufficientDisk"
		nodeOODCondition.Message = "kubelet has sufficient disk space available"
		nodeOODCondition.LastTransitionTime = currentTime
		kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasSufficientDisk")
	}

	// Update the heartbeat time irrespective of all the conditions.
	nodeOODCondition.LastHeartbeatTime = currentTime

	if newOODCondition {
		node.Status.Conditions = append(node.Status.Conditions, *nodeOODCondition)
	}
}

// Maintains Node.Spec.Unschedulable value from previous run of tryUpdateNodeStatus()
// TODO: why is this a package var?
var (
	oldNodeUnschedulable     bool
	oldNodeUnschedulableLock sync.Mutex
)

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1042
// record if node schedulable change.
func (kl *Kubelet) recordNodeSchedulableEvent(node *v1.Node) {
	oldNodeUnschedulableLock.Lock()
	defer oldNodeUnschedulableLock.Unlock()
	if oldNodeUnschedulable != node.Spec.Unschedulable {
		if node.Spec.Unschedulable {
			kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeNotSchedulable)
		} else {
			kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeSchedulable)
		}
		oldNodeUnschedulable = node.Spec.Unschedulable
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1065
// setNodeStatus fills in the Status fields of the given Node, overwriting
// any fields that are currently set.
// TODO(madhusudancs): Simplify the logic for setting node conditions and
// refactor the node status condition code out to a different file.
func (kl *Kubelet) setNodeStatus(node *v1.Node) {
	for i, f := range kl.setNodeStatusFuncs {
		glog.V(5).Infof("Setting node status at position %v", i)
		if err := f(node); err != nil {
			glog.Warningf("Failed to set some node status fields: %s", err)
		}
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1056
// Update VolumesInUse field in Node Status only after states are synced up at least once
// in volume reconciler.
func (kl *Kubelet) setNodeVolumesInUseStatus(node *v1.Node) {
	// Make sure to only update node status after reconciler starts syncing up states
	if kl.volumeManager.ReconcilerStatesHasBeenSynced() {
		node.Status.VolumesInUse = kl.volumeManager.GetVolumesInUse()
	}
}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1078
// defaultNodeStatusFuncs is a factory that generates the default set of
// setNodeStatus funcs
func (kl *Agent) defaultNodeStatusFuncs() []func(*v1.Node) error {
	// initial set of node status update handlers, can be modified by Option's
	withoutError := func(f func(*v1.Node)) func(*v1.Node) error {
		return func(n *v1.Node) error {
			f(n)
			return nil
		}
	}
	return []func(*v1.Node) error{
		kl.setNodeAddress,
		withoutError(kl.setNodeStatusInfo),
		withoutError(kl.setNodeOODCondition),
		withoutError(kl.setNodeMemoryPressureCondition),
		withoutError(kl.setNodeDiskPressureCondition),
		withoutError(kl.setNodePIDPressureCondition),
		withoutError(kl.setNodeReadyCondition),
		withoutError(kl.setNodeVolumesInUseStatus),
		withoutError(kl.recordNodeSchedulableEvent),
	}
}

func dockerMachineStatusFuncs() []func(*pb.AgentNode) error {

}

func openstackNodeStatusFuncs() []func(*pb.AgentNode) error {

}

func physicalMachineStatusFuncs() []func(*pb.AgentNode) error {

}

// Inspired by https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet_node_status.go#L1101
// Validate given node IP belongs to the current host
func validateNodeIP(nodeIP net.IP) error {
	// Honor IP limitations set in setNodeStatus()
	if nodeIP.To4() == nil && nodeIP.To16() == nil {
		return fmt.Errorf("nodeIP must be a valid IP address")
	}
	if nodeIP.IsLoopback() {
		return fmt.Errorf("nodeIP can't be loopback address")
	}
	if nodeIP.IsMulticast() {
		return fmt.Errorf("nodeIP can't be a multicast address")
	}
	if nodeIP.IsLinkLocalUnicast() {
		return fmt.Errorf("nodeIP can't be a link-local unicast address")
	}
	if nodeIP.IsUnspecified() {
		return fmt.Errorf("nodeIP can't be an all zeros address")
	}

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return err
	}
	for _, addr := range addrs {
		var ip net.IP
		switch v := addr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		}
		if ip != nil && ip.Equal(nodeIP) {
			return nil
		}
	}
	return fmt.Errorf("Node IP: %q not found in the host's network interfaces", nodeIP.String())
}


text:
package org.sakaiproject.tool.gradebook.ui;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Provides a way to override UI bean definitions from the Sakai component
 * framework while still visibly injecting them in UI configuration files.
 *
 * (If our UI logic was based on Spring beans rather than JSF backing beans,
 * there might be a more straightforward way to deliver this capability.)
 */
public class ConfigurationBean implements ApplicationContextAware{
	private static final Log log = LogFactory.getLog(ConfigurationBean.class);

    private ApplicationContext applicationContext;

	private Map<String, Object> pluginDefaults;
	private ServerConfigurationService serverConfigurationService;

	/**
	 * @param name
	 * @return the bean configured to match the given plug-in key, or null if none were found
	 */
	public Object getPlugin(String key) {
		Object target = null;
		if (log.isDebugEnabled()) log.debug("key=" + key + ", serverConfigurationService=" + serverConfigurationService + ", default=" + pluginDefaults.get(key));
		if (serverConfigurationService != null) {
			// As of Sakai 2.4, the framework's configuration service
			// returns the empty string instead of null if a property isn't found.
			target = StringUtils.stripToNull(serverConfigurationService.getString(key));
		}
		if (target == null) {
			target = pluginDefaults.get(key);
		}
		if (target != null) {
			if (target instanceof String) {
				// Assume that we got a bean name instead of the
				// bean itself.
				target = applicationContext.getBean((String)target);
			}
		}
		if (log.isDebugEnabled()) log.debug("for " + key + " returning " + target);
		return target;
	}

	public String getConfig(String name, String defaultValue) {
	    String val = defaultValue;
	    if (serverConfigurationService != null) {
	        val = serverConfigurationService.getString(name, defaultValue);
	    }
	    return val;
	}

	public boolean getBooleanConfig(String name, boolean defaultValue) {
        boolean val = defaultValue;
        if (serverConfigurationService != null) {
            val = serverConfigurationService.getBoolean(name, defaultValue);
        }
        return val;
    }

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public void setPluginDefaults(Map<String, Object> pluginDefaults) {
		this.pluginDefaults = pluginDefaults;
	}

	/**
	 * If this method is never called (as in the case of standalone builds), the
	 * default map of property values will be used.
	 * @param serverConfigurationService
	 */
	public void setServerConfigurationService(
			ServerConfigurationService serverConfigurationService) {
		this.serverConfigurationService = serverConfigurationService;
	}
}


text:
"""
Utility functions to help with generation and verification of
verilog math code.
"""

from fpga_sdrlib.generate import copyfile

blocks = {
    # The basic modules.
    'log.v': (None, copyfile, {}),
    'multiply.v': (None, copyfile, {}),
    'multiply_complex.v': (('multiply.v',), copyfile, {}),
    # qa_contents modules.
    'qa_multiply.v': (('multiply.v',), copyfile, {}),
    'qa_multiply_complex.v': (('multiply_complex.v',), copyfile, {}),
    }

# compatible with running on the B100
compatibles = {
    'multiply':
        ('qa_multiply.v', 'uhd/qa_wrapper.v'),
    'multiply_complex':
        ('qa_multiply_complex.v', 'uhd/qa_wrapper.v'),
}

# Not compatible with running on the B100
incompatibles = {
    'multiply_inner':
        ('qa_multiply.v', 'uhd/dut_qa_contents.v'),
    'multiply_complex_inner':
        ('qa_multiply_complex.v', 'uhd/dut_qa_contents.v'),
}


text:
<?php
/**
 * Template Name: Menu Template
 */
?>

<section class="menu">
<?php while (have_posts()) : the_post(); ?>

<?php get_template_part('templates/page', 'header'); ?>
<?php get_template_part('templates/content', 'page'); ?>
<?php endwhile; ?>
</section>


text:
define("gridx/nls/pt-br/NestedSorting", {

	singleSort: "Classificação Única",
	nestedSort: "Classificação Aninhada",
	ascending: "Clique para classificar em ordem crescente",
	descending: "Clique para classificar em ordem decrescente",
	sortingState: "${0} - ${1}",
	unsorted: "Não classificar esta coluna"
});


text:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
    selector: 'starter-reactive-form',
    templateUrl: './starterReactiveForm.component.html'
})
export class StarterReactiveFormComponent implements OnInit {
    customerForm: FormGroup;
    customer: any;
    message: string;
    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.customer = {
            firstName: 'Tina Reactive'
        };

        this.customerForm = this.formBuilder.group({
            firstName: [this.customer.firstName, Validators.required ]
        });
    }

    onSubmit(form: FormGroup) {
        this.message = 'You typed: ' + form.controls.firstName.value;
    }

}


text: SHOW FULL COLUMNS FROM `foo.bar` FROM hohoho LIKE '%xmas%'


text:
package sample;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.util.Map;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.hateoas.MediaTypes;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Series of automated integration tests to verify proper behavior of auto-configured,
 * OAuth2-secured system
 *
 * @author Greg Turnquist
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest("server.port:0")
public class ApplicationTests {

	@Autowired
	WebApplicationContext context;
	@Autowired
	FilterChainProxy filterChain;

	private MockMvc mvc;

	private final ObjectMapper objectMapper = new ObjectMapper();

	@Before
	public void setUp() {

		this.mvc = webAppContextSetup(this.context).addFilters(this.filterChain).build();
		SecurityContextHolder.clearContext();
	}

	@Test
	public void everythingIsSecuredByDefault() throws Exception {

		this.mvc.perform(get("/").//
				accept(MediaTypes.HAL_JSON)).// /
				andExpect(status().isUnauthorized()).//
				andDo(print());

		this.mvc.perform(get("/flights").//
				accept(MediaTypes.HAL_JSON)).// /
				andExpect(status().isUnauthorized()).//
				andDo(print());

		this.mvc.perform(get("/flights/1").//
				accept(MediaTypes.HAL_JSON)).// /
				andExpect(status().isUnauthorized()).//
				andDo(print());

		this.mvc.perform(get("/alps").//
				accept(MediaTypes.HAL_JSON)).// /
				andExpect(status().isUnauthorized()).//
				andDo(print());
	}

	@Test
	@Ignore
	// TODO: maybe show mixed basic + token auth on different resources?
	public void accessingRootUriPossibleWithUserAccount() throws Exception {

		this.mvc.perform(
				get("/").//
				accept(MediaTypes.HAL_JSON).//
						header("Authorization",
								"Basic "
										+ new String(Base64.encode("greg:turnquist"
												.getBytes()))))
				.//
				andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
				.//
				andExpect(status().isOk()).//
				andDo(print());
	}

	@Test
	public void useAppSecretsPlusUserAccountToGetBearerToken() throws Exception {

		// @formatter:off
		MvcResult result = this.mvc
				.perform(
						post("/oauth/token").
								header("Authorization",
										"Basic " + new String(Base64.encode("foo:bar".getBytes()))).
								param("grant_type", "password").
								param("scope", "read").
								param("username", "greg").
								param("password", "turnquist")).
				andExpect(status().isOk()).
				andDo(print()).
				andReturn();
		// @formatter:on

		Object accessToken = this.objectMapper.readValue(
				result.getResponse().getContentAsString(), Map.class).get("access_token");

		MvcResult flightsAction = this.mvc
				.perform(get("/flights/1").//
						accept(MediaTypes.HAL_JSON).//
						header("Authorization", "Bearer " + accessToken))
				.//
				andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
				.//
				andExpect(status().isOk()).//
				andDo(print()).//
				andReturn();

		Flight flight = this.objectMapper.readValue(flightsAction.getResponse()
				.getContentAsString(), Flight.class);

		assertThat(flight.getOrigin(), is("Nashville"));
		assertThat(flight.getDestination(), is("Dallas"));
		assertThat(flight.getAirline(), is("Spring Ways"));
		assertThat(flight.getFlightNumber(), is("OAUTH2"));
		assertThat(flight.getTraveler(), is("Greg Turnquist"));
	}

}


text:
function* foo() { yield 42 }
function* goo() { yield 42 }
var f = foo();
var g = goo();
assertEquals(42, f.next().value);
assertEquals(42, g.next().value);
assertEquals(true, f.next().done);
assertEquals(true, g.next().done);


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Stealing Fire</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">
  <link class="invert" href="css/stealing-fire.css" rel="stylesheet">
  <link rel="icon" href="img/stealingFireLogo.jpg">

      Stealing Fire
      <button class="navbar-toggler" type="button"
      data-toggle="collapse" data-target="#navbarResponsive"
       aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home
              (current)

            About/The Crew

              Comics

              Dream Crasher

            Contact

            Store

The Crew

Daniel Stalter

Writter & Co-Creator

Reed Olsen

Artist & Co-Creator

            Dream Crasher is a new speculative fiction series written by Daniel Stalter with artwork by Reed Olsen. It began as an idea between two high school friends in the summer of 2010. It launched in June 2015 with the digital release of Chapter 1: Creature's
            Keeper, and with Chapter 2: The Land Vomits Ghosts following a year later. A new chapter will be published every fall and spring

        stealingfirecomics@gmail.com

                      Copyright © Stealing Fire 2014