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

#include "third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h"

#include "third_party/blink/renderer/core/layout/layout_fieldset.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fieldset_break_token_data.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"

namespace blink {

namespace {

enum class LegendBlockAlignment {
  kStart,
  kCenter,
  kEnd,
};

// This function is very similar to BlockAlignment() in ng_length_utils.cc, but
// it supports text-align:left/center/right.
inline LegendBlockAlignment ComputeLegendBlockAlignment(
    const ComputedStyle& legend_style,
    const ComputedStyle& fieldset_style) {
  bool start_auto = legend_style.MarginStartUsing(fieldset_style).IsAuto();
  bool end_auto = legend_style.MarginEndUsing(fieldset_style).IsAuto();
  if (start_auto || end_auto) {
    if (start_auto) {
      return end_auto ? LegendBlockAlignment::kCenter
                      : LegendBlockAlignment::kEnd;
    }
    return LegendBlockAlignment::kStart;
  }
  const bool is_ltr = fieldset_style.IsLeftToRightDirection();
  switch (legend_style.GetTextAlign()) {
    case ETextAlign::kLeft:
      return is_ltr ? LegendBlockAlignment::kStart : LegendBlockAlignment::kEnd;
    case ETextAlign::kRight:
      return is_ltr ? LegendBlockAlignment::kEnd : LegendBlockAlignment::kStart;
    case ETextAlign::kCenter:
      return LegendBlockAlignment::kCenter;
    default:
      return LegendBlockAlignment::kStart;
  }
}

}  // namespace

NGFieldsetLayoutAlgorithm::NGFieldsetLayoutAlgorithm(
    const NGLayoutAlgorithmParams& params)
    : NGLayoutAlgorithm(params),
      writing_direction_(ConstraintSpace().GetWritingDirection()),
      consumed_block_size_(BreakToken() ? BreakToken()->ConsumedBlockSize()
                                        : LayoutUnit()) {
  DCHECK(params.fragment_geometry.scrollbar.IsEmpty());
  border_box_size_ = container_builder_.InitialBorderBoxSize();
}

const NGLayoutResult* NGFieldsetLayoutAlgorithm::Layout() {
  // Layout of a fieldset container consists of two parts: Create a child
  // fragment for the rendered legend (if any), and create a child fragment for
  // the fieldset contents anonymous box (if any).
  // Fieldset scrollbars and padding will not be applied to the fieldset
  // container itself, but rather to the fieldset contents anonymous child box.
  // The reason for this is that the rendered legend shouldn't be part of the
  // scrollport; the legend is essentially a part of the block-start border,
  // and should not scroll along with the actual fieldset contents. Since
  // scrollbars are handled by the anonymous child box, and since padding is
  // inside the scrollport, padding also needs to be handled by the anonymous
  // child.
  intrinsic_block_size_ =
      IsBreakInside(BreakToken()) ? LayoutUnit() : Borders().block_start;

  if (InvolvedInBlockFragmentation(container_builder_)) {
    container_builder_.SetBreakTokenData(
        MakeGarbageCollected<NGFieldsetBreakTokenData>(
            container_builder_.GetBreakTokenData()));
  }

  NGBreakStatus break_status = LayoutChildren();
  if (break_status == NGBreakStatus::kNeedsEarlierBreak) {
    // We need to abort the layout. No fragment will be generated.
    return container_builder_.Abort(NGLayoutResult::kNeedsEarlierBreak);
  }

  intrinsic_block_size_ = ClampIntrinsicBlockSize(
      ConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(),
      intrinsic_block_size_ + Borders().block_end);

  // Recompute the block-axis size now that we know our content size.
  border_box_size_.block_size =
      ComputeBlockSizeForFragment(ConstraintSpace(), Style(), BorderPadding(),
                                  intrinsic_block_size_ + consumed_block_size_,
                                  border_box_size_.inline_size);

  // The above computation utility knows nothing about fieldset weirdness. The
  // legend may eat from the available content box block size. Make room for
  // that if necessary.
  // Note that in size containment, we have to consider sizing as if we have no
  // contents, with the conjecture being that legend is part of the contents.
  // Thus, only do this adjustment if we do not contain size.
  if (!Node().ShouldApplyBlockSizeContainment()) {
    border_box_size_.block_size =
        std::max(border_box_size_.block_size, minimum_border_box_block_size_);
  }

  // TODO(almaher): end border and padding may overflow the parent
  // fragmentainer, and we should avoid that.
  LayoutUnit all_fragments_block_size = border_box_size_.block_size;

  container_builder_.SetIntrinsicBlockSize(intrinsic_block_size_);
  container_builder_.SetFragmentsTotalBlockSize(all_fragments_block_size);
  container_builder_.SetIsFieldsetContainer();

  if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) {
    NGBreakStatus status = FinishFragmentation(
        Node(), ConstraintSpace(), Borders().block_end,
        FragmentainerSpaceLeft(ConstraintSpace()), &container_builder_);
    if (status == NGBreakStatus::kNeedsEarlierBreak) {
      // If we found a good break somewhere inside this block, re-layout and
      // break at that location.
      return RelayoutAndBreakEarlier<NGFieldsetLayoutAlgorithm>(
          container_builder_.EarlyBreak());
    } else if (status == NGBreakStatus::kDisableFragmentation) {
      return RelayoutWithoutFragmentation<NGFieldsetLayoutAlgorithm>();
    }
    DCHECK_EQ(status, NGBreakStatus::kContinue);
  } else {
#if DCHECK_IS_ON()
    // If we're not participating in a fragmentation context, no block
    // fragmentation related fields should have been set.
    container_builder_.CheckNoBlockFragmentation();
#endif
  }

  NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run();

  const auto& style = Style();
  if (style.LogicalHeight().IsPercentOrCalc() ||
      style.LogicalMinHeight().IsPercentOrCalc() ||
      style.LogicalMaxHeight().IsPercentOrCalc()) {
    // The height of the fieldset content box depends on the percent-height of
    // the fieldset. So we should assume the fieldset has a percent-height
    // descendant.
    container_builder_.SetHasDescendantThatDependsOnPercentageBlockSize();
  }

  return container_builder_.ToBoxFragment();
}

NGBreakStatus NGFieldsetLayoutAlgorithm::LayoutChildren() {
  const NGBlockBreakToken* content_break_token = nullptr;
  bool has_seen_all_children = false;
  if (const auto* token = BreakToken()) {
    const auto child_tokens = token->ChildBreakTokens();
    if (wtf_size_t break_token_count =
            base::checked_cast<wtf_size_t>(child_tokens.size())) {
      const NGBlockBreakToken* child_token =
          To<NGBlockBreakToken>(child_tokens[0].Get());
      if (child_token) {
        DCHECK(!child_token->InputNode().IsRenderedLegend());
        content_break_token = child_token;
      }
      // There shouldn't be any additional break tokens.
      DCHECK_EQ(child_tokens.size(), 1u);
    }
    if (token->HasSeenAllChildren()) {
      container_builder_.SetHasSeenAllChildren();
      has_seen_all_children = true;
    }
  }

  LogicalSize adjusted_padding_box_size =
      ShrinkLogicalSize(border_box_size_, Borders());

  NGBlockNode legend = Node().GetRenderedLegend();
  if (legend) {
    if (!IsBreakInside(BreakToken()))
      LayoutLegend(legend);
    LayoutUnit legend_size_contribution;
    if (IsBreakInside(BreakToken())) {
      const auto* token_data =
          To<NGFieldsetBreakTokenData>(BreakToken()->TokenData());
      legend_size_contribution = token_data->legend_block_size_contribution;
    } else {
      // We're at the first fragment. The current layout position
      // (intrinsic_block_size_) is at the outer block-end edge of the legend
      // or just after the block-start border, whichever is larger.
      legend_size_contribution = intrinsic_block_size_ - Borders().block_start;
    }

    if (InvolvedInBlockFragmentation(container_builder_)) {
      auto* token_data =
          To<NGFieldsetBreakTokenData>(container_builder_.GetBreakTokenData());
      token_data->legend_block_size_contribution = legend_size_contribution;
    }

    if (adjusted_padding_box_size.block_size != kIndefiniteSize) {
      DCHECK_NE(border_box_size_.block_size, kIndefiniteSize);
      adjusted_padding_box_size.block_size = std::max(
          adjusted_padding_box_size.block_size - legend_size_contribution,
          Padding().BlockSum());
    }

    // The legend may eat from the available content box block size. Calculate
    // the minimum block size needed to encompass the legend.
    if (!Node().ShouldApplyBlockSizeContainment()) {
      minimum_border_box_block_size_ =
          BorderPadding().BlockSum() + legend_size_contribution;
    }
  }

  // Proceed with normal fieldset children (excluding the rendered legend). They
  // all live inside an anonymous child box of the fieldset container.
  if (content_break_token || !has_seen_all_children) {
    NGBlockNode fieldset_content = Node().GetFieldsetContent();
    DCHECK(fieldset_content);
    NGBreakStatus break_status =
        LayoutFieldsetContent(fieldset_content, content_break_token,
                              adjusted_padding_box_size, !!legend);
    if (break_status == NGBreakStatus::kNeedsEarlierBreak)
      return break_status;
  }

  return NGBreakStatus::kContinue;
}

void NGFieldsetLayoutAlgorithm::LayoutLegend(NGBlockNode& legend) {
  // Lay out the legend. While the fieldset container normally ignores its
  // padding, the legend is laid out within what would have been the content
  // box had the fieldset been a regular block with no weirdness.
  LogicalSize percentage_size = CalculateChildPercentageSize(
      ConstraintSpace(), Node(), ChildAvailableSize());
  NGBoxStrut legend_margins =
      ComputeMarginsFor(legend.Style(), percentage_size.inline_size,
                        ConstraintSpace().GetWritingDirection());

  auto legend_space = CreateConstraintSpaceForLegend(
      legend, ChildAvailableSize(), percentage_size);
  const NGLayoutResult* result = legend.Layout(legend_space, BreakToken());

  // Legends are monolithic, so abortions are not expected.
  DCHECK_EQ(result->Status(), NGLayoutResult::kSuccess);

  const auto& physical_fragment = result->PhysicalFragment();

  LayoutUnit legend_border_box_block_size =
      NGFragment(writing_direction_, physical_fragment).BlockSize();
  LayoutUnit legend_margin_box_block_size = legend_margins.block_start +
                                            legend_border_box_block_size +
                                            legend_margins.block_end;

  LayoutUnit space_left = Borders().block_start - legend_border_box_block_size;
  LayoutUnit block_offset;
  if (space_left > LayoutUnit()) {
    // https://html.spec.whatwg.org/C/#the-fieldset-and-legend-elements
    // * The element is expected to be positioned in the block-flow direction
    //   such that its border box is centered over the border on the
    //   block-start side of the fieldset element.
    block_offset += space_left / 2;
  }
  // If the border is smaller than the block end offset of the legend margin
  // box, intrinsic_block_size_ should now be based on the the block end
  // offset of the legend margin box instead of the border.
  LayoutUnit legend_margin_end_offset =
      block_offset + legend_margin_box_block_size - legend_margins.block_start;
  if (legend_margin_end_offset > Borders().block_start)
    intrinsic_block_size_ = legend_margin_end_offset;

  // If the margin box of the legend is at least as tall as the fieldset
  // block-start border width, it will start at the block-start border edge
  // of the fieldset. As a paint effect, the block-start border will be
  // pushed so that the center of the border will be flush with the center
  // of the border-box of the legend.

  LayoutUnit legend_inline_start = ComputeLegendInlineOffset(
      legend.Style(),
      NGFragment(writing_direction_, result->PhysicalFragment()).InlineSize(),
      legend_margins, Style(), BorderScrollbarPadding().inline_start,
      ChildAvailableSize().inline_size);
  LogicalOffset legend_offset = {legend_inline_start, block_offset};

  container_builder_.AddResult(*result, legend_offset);
}

LayoutUnit NGFieldsetLayoutAlgorithm::ComputeLegendInlineOffset(
    const ComputedStyle& legend_style,
    LayoutUnit legend_border_box_inline_size,
    const NGBoxStrut& legend_margins,
    const ComputedStyle& fieldset_style,
    LayoutUnit fieldset_border_padding_inline_start,
    LayoutUnit fieldset_content_inline_size) {
  LayoutUnit legend_inline_start =
      fieldset_border_padding_inline_start + legend_margins.inline_start;
  // The following logic is very similar to ResolveInlineMargins(), but it uses
  // ComputeLegendBlockAlignment().
  const LayoutUnit available_space =
      fieldset_content_inline_size - legend_border_box_inline_size;
  if (available_space > LayoutUnit()) {
    auto alignment = ComputeLegendBlockAlignment(legend_style, fieldset_style);
    if (alignment == LegendBlockAlignment::kCenter)
      legend_inline_start += available_space / 2;
    else if (alignment == LegendBlockAlignment::kEnd)
      legend_inline_start += available_space - legend_margins.inline_end;
  }
  return legend_inline_start;
}

NGBreakStatus NGFieldsetLayoutAlgorithm::LayoutFieldsetContent(
    NGBlockNode& fieldset_content,
    const NGBlockBreakToken* content_break_token,
    LogicalSize adjusted_padding_box_size,
    bool has_legend) {
  const NGEarlyBreak* early_break_in_child = nullptr;
  if (UNLIKELY(early_break_)) {
    if (IsEarlyBreakTarget(*early_break_, container_builder_,
                           fieldset_content)) {
      container_builder_.AddBreakBeforeChild(fieldset_content,
                                             kBreakAppealPerfect,
                                             /* is_forced_break */ false);
      ConsumeRemainingFragmentainerSpace();
      return NGBreakStatus::kContinue;
    } else {
      early_break_in_child =
          EnterEarlyBreakInChild(fieldset_content, *early_break_);
    }
  }

  const NGLayoutResult* result = nullptr;
  bool is_past_end = BreakToken() && BreakToken()->IsAtBlockEnd();

  LayoutUnit max_content_block_size = LayoutUnit::Max();
  if (adjusted_padding_box_size.block_size == kIndefiniteSize) {
    max_content_block_size =
        ResolveMaxBlockLength(ConstraintSpace(), Style(), BorderPadding(),
                              Style().LogicalMaxHeight());
  }

  // If we are past the block-end and had previously laid out the content with a
  // block-size limitation, skip the normal layout call and apply the block-size
  // limitation for all future fragments.
  if (!is_past_end || max_content_block_size == LayoutUnit::Max()) {
    auto child_space = CreateConstraintSpaceForFieldsetContent(
        fieldset_content, adjusted_padding_box_size, intrinsic_block_size_);
    result = fieldset_content.Layout(child_space, content_break_token,
                                     early_break_in_child);
  }

  // If the following conditions meet, the content should be laid out with
  // a block-size limitation:
  // - The FIELDSET block-size is indefinite.
  // - It has max-block-size.
  // - The intrinsic block-size of the content is larger than the
  //   max-block-size.
  if (max_content_block_size != LayoutUnit::Max() &&
      (!result || result->Status() == NGLayoutResult::kSuccess)) {
    DCHECK_EQ(adjusted_padding_box_size.block_size, kIndefiniteSize);
    if (max_content_block_size > Padding().BlockSum()) {
      // intrinsic_block_size_ is
      // max(Borders().block_start, legend margin box block size).
      max_content_block_size =
          std::max(max_content_block_size -
                       (intrinsic_block_size_ + Borders().block_end),
                   Padding().BlockSum());
    }

    if (result) {
      const auto& fragment = result->PhysicalFragment();
      LayoutUnit total_block_size =
          NGFragment(writing_direction_, fragment).BlockSize();
      if (content_break_token)
        total_block_size += content_break_token->ConsumedBlockSize();
      if (total_block_size >= max_content_block_size)
        result = nullptr;
    } else {
      DCHECK(is_past_end);
    }

    if (!result) {
      adjusted_padding_box_size.block_size = max_content_block_size;
      auto adjusted_child_space = CreateConstraintSpaceForFieldsetContent(
          fieldset_content, adjusted_padding_box_size, intrinsic_block_size_);
      result = fieldset_content.Layout(
          adjusted_child_space, content_break_token, early_break_in_child);
    }
  }
  DCHECK(result);

  NGBreakStatus break_status = NGBreakStatus::kContinue;
  if (ConstraintSpace().HasBlockFragmentation() && !early_break_) {
    break_status = BreakBeforeChildIfNeeded(
        ConstraintSpace(), fieldset_content, *result,
        ConstraintSpace().FragmentainerOffset() + intrinsic_block_size_,
        /* has_container_separation */ false, &container_builder_);
  }

  if (break_status == NGBreakStatus::kContinue) {
    DCHECK_EQ(result->Status(), NGLayoutResult::kSuccess);
    LogicalOffset offset(Borders().inline_start, intrinsic_block_size_);
    container_builder_.AddResult(*result, offset);

    const auto& fragment =
        To<NGPhysicalBoxFragment>(result->PhysicalFragment());
    if (auto first_baseline = fragment.FirstBaseline()) {
      container_builder_.SetFirstBaseline(offset.block_offset +
                                          *first_baseline);
    }
    if (auto last_baseline = fragment.LastBaseline())
      container_builder_.SetLastBaseline(offset.block_offset + *last_baseline);
    if (fragment.UseLastBaselineForInlineBaseline())
      container_builder_.SetUseLastBaselineForInlineBaseline();

    intrinsic_block_size_ +=
        NGFragment(writing_direction_, fragment).BlockSize();
    container_builder_.SetHasSeenAllChildren();
  } else if (break_status == NGBreakStatus::kBrokeBefore) {
    ConsumeRemainingFragmentainerSpace();
  }

  return break_status;
}

LayoutUnit NGFieldsetLayoutAlgorithm::FragmentainerSpaceAvailable() const {
  // The legend may have extended past the end of the fragmentainer. Clamp to
  // zero if this is the case.
  return std::max(LayoutUnit(), FragmentainerSpaceLeft(ConstraintSpace()) -
                                    intrinsic_block_size_);
}

void NGFieldsetLayoutAlgorithm::ConsumeRemainingFragmentainerSpace() {
  if (ConstraintSpace().HasKnownFragmentainerBlockSize()) {
    // The remaining part of the fragmentainer (the unusable space for child
    // content, due to the break) should still be occupied by this container.
    intrinsic_block_size_ += FragmentainerSpaceAvailable();
  }
}

MinMaxSizesResult NGFieldsetLayoutAlgorithm::ComputeMinMaxSizes(
    const MinMaxSizesFloatInput&) {
  MinMaxSizesResult result;

  bool has_inline_size_containment = Node().ShouldApplyInlineSizeContainment();
  if (has_inline_size_containment) {
    // Size containment does not consider the legend for sizing.
    absl::optional<MinMaxSizesResult> result_without_children =
        CalculateMinMaxSizesIgnoringChildren(Node(), BorderScrollbarPadding());
    if (result_without_children)
      return *result_without_children;
  } else {
    if (NGBlockNode legend = Node().GetRenderedLegend()) {
      NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), legend,
                                             /* is_new_fc */ true);
      builder.SetAvailableBlockSize(kIndefiniteSize);
      const auto space = builder.ToConstraintSpace();

      result = ComputeMinAndMaxContentContribution(Style(), legend, space);
      result.sizes +=
          ComputeMarginsFor(space, legend.Style(), ConstraintSpace())
              .InlineSum();
    }
  }

  // The fieldset content includes the fieldset padding (and any scrollbars),
  // while the legend is a regular child and doesn't. We may have a fieldset
  // without any content or legend, so add the padding here, on the outside.
  result.sizes += ComputePadding(ConstraintSpace(), Style()).InlineSum();

  // Size containment does not consider the content for sizing.
  if (!has_inline_size_containment) {
    NGBlockNode content = Node().GetFieldsetContent();
    DCHECK(content);
    NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), content,
                                           /* is_new_fc */ true);
    builder.SetAvailableBlockSize(kIndefiniteSize);
    const auto space = builder.ToConstraintSpace();

    MinMaxSizesResult content_result =
        ComputeMinAndMaxContentContribution(Style(), content, space);
    content_result.sizes +=
        ComputeMarginsFor(space, content.Style(), ConstraintSpace())
            .InlineSum();
    result.sizes.Encompass(content_result.sizes);
    result.depends_on_block_constraints |=
        content_result.depends_on_block_constraints;
  }

  result.sizes += ComputeBorders(ConstraintSpace(), Node()).InlineSum();
  return result;
}

const NGConstraintSpace
NGFieldsetLayoutAlgorithm::CreateConstraintSpaceForLegend(
    NGBlockNode legend,
    LogicalSize available_size,
    LogicalSize percentage_size) {
  NGConstraintSpaceBuilder builder(ConstraintSpace(),
                                   legend.Style().GetWritingDirection(),
                                   /* is_new_fc */ true);
  SetOrthogonalFallbackInlineSizeIfNeeded(Style(), legend, &builder);

  builder.SetAvailableSize(available_size);
  builder.SetPercentageResolutionSize(percentage_size);
  return builder.ToConstraintSpace();
}

const NGConstraintSpace
NGFieldsetLayoutAlgorithm::CreateConstraintSpaceForFieldsetContent(
    NGBlockNode fieldset_content,
    LogicalSize padding_box_size,
    LayoutUnit block_offset) {
  DCHECK(fieldset_content.CreatesNewFormattingContext());
  NGConstraintSpaceBuilder builder(
      ConstraintSpace(), fieldset_content.Style().GetWritingDirection(),
      /* is_new_fc */ true);
  builder.SetAvailableSize(padding_box_size);
  builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit);
  // We pass the container's PercentageResolutionSize because percentage
  // padding for the fieldset content should be computed as they are in
  // the container.
  //
  // https://html.spec.whatwg.org/C/#anonymous-fieldset-content-box
  // > * For the purpose of calculating percentage padding, act as if the
  // >   padding was calculated for the fieldset element.
  builder.SetPercentageResolutionSize(
      ConstraintSpace().PercentageResolutionSize());
  builder.SetIsFixedBlockSize(padding_box_size.block_size != kIndefiniteSize);
  builder.SetBaselineAlgorithmType(ConstraintSpace().BaselineAlgorithmType());

  if (ConstraintSpace().HasBlockFragmentation()) {
    SetupSpaceBuilderForFragmentation(
        ConstraintSpace(), fieldset_content, block_offset, &builder,
        /* is_new_fc */ true,
        container_builder_.RequiresContentBeforeBreaking());
  }
  return builder.ToConstraintSpace();
}

}  // namespace blink


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UserHelper.Models
{
    public static class BatchState
    {
        public static UserProcessState State { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package middleware

import (
        "time"
        "github.com/TortugaSurf/Auth/routers/handler"
        "github.com/TortugaSurf/Auth/config"
        "gopkg.in/appleboy/gin-jwt.v2"
)

var configuration config.Config

func GetMiddleware() *jwt.GinJWTMiddleware {
        return &jwt.GinJWTMiddleware{
                Realm:      "test zone",
                Key:        []byte(configuration.Mysql.Secret_key),
                Timeout:    time.Hour * 24,
                MaxRefresh: time.Hour * 24,
                Authenticator: handler.AuthenticatorHandler,
                PayloadFunc: handler.PayloadFuncHandler,
                Authorizator: handler.AuthorizatorHandler,
                Unauthorized: handler.UnauthorizedHandler,
                TokenLookup: "header:Authorization",
        }
}


text:
<?php

namespace Spriter\Dumper;

use Spriter\Dumper\RuleNameGeneratorInterface;
use Spriter\Dumper\DumperInterface;

class LessDumper implements DumperInterface {

	/**
	 * List of elements where key is an image path an valie if a Imaging\Image\Point instance
	 * @var array
	 */
	protected $elements;

	/**
	 * Rules container template
	 * @var string
	 */
	protected $fileTemplate = <<<EOF
#sprites {
{rules}
}

EOF;

	/**
	 * Single rule template
	 * @var string
	 */
	protected $template = <<<EOF
	.{name} {
		background-position: -{x}px -{y}px;
	}\n
EOF;

	/**
	 * Style rule name generator.
	 * @var Spriter/Dumper/RuleNameGeneratorInterface
	 */
	protected $nameGenerator;

	/**
	 * {@inheritdoc}
	 */
	public function __construct(array $elements, RuleNameGeneratorInterface $nameGenerator)
	{
		$this->elements = $elements;
		$this->nameGenerator = $nameGenerator;
	}

	/**
	 * {@inheritdoc}
	 */
	public function dump()
	{
		$output = '';

		foreach ($this->elements as $path => $position) {
			$name = $this->nameGenerator->get($path);
			$output .= str_replace(array('{name}', '{x}', '{y}'), array($name, $position->getX(), $position->getY()), $this->template);
		}

		$output = str_replace('{rules}', $output, $this->fileTemplate);

		return $output;
	}

}


text:
<?php

namespace PhpBench\Expression\Func;

use PhpBench\Expression\Ast\PhpValue;
use PhpBench\Expression\Ast\StringNode;
use RuntimeException;

use function error_clear_last;

final class FormatFunction
{
    public function __invoke(StringNode $format, PhpValue ...$values): StringNode
    {
        error_clear_last();

        $formatted = @sprintf($format->value(), ...array_map(function (PhpValue $value) {
            return $value->value();
        }, $values));

        if (!is_string($formatted)) {
            $error = error_get_last();
            $message = isset($error['message']) ? $error['message'] : 'could not format string';
            $message = str_replace('sprintf', 'format', $message);

            throw new RuntimeException($message);
        }

        return new StringNode($formatted);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tests.gl_500;

import com.jogamp.opengl.GL;
import static com.jogamp.opengl.GL.GL_FLOAT;
import static com.jogamp.opengl.GL.GL_TRIANGLES;
import static com.jogamp.opengl.GL.GL_TRUE;
import static com.jogamp.opengl.GL2.GL_SM_COUNT_NV;
import static com.jogamp.opengl.GL2.GL_WARPS_PER_SM_NV;
import static com.jogamp.opengl.GL2.GL_WARP_SIZE_NV;
import static com.jogamp.opengl.GL2ES2.GL_FRAGMENT_SHADER;
import static com.jogamp.opengl.GL2ES2.GL_FRAGMENT_SHADER_BIT;
import static com.jogamp.opengl.GL2ES2.GL_PROGRAM_SEPARABLE;
import static com.jogamp.opengl.GL2ES2.GL_VERTEX_SHADER;
import static com.jogamp.opengl.GL2ES2.GL_VERTEX_SHADER_BIT;
import static com.jogamp.opengl.GL2ES3.GL_COLOR;
import static com.jogamp.opengl.GL2ES3.GL_UNIFORM_BUFFER;
import com.jogamp.opengl.GL4;
import com.jogamp.opengl.util.GLBuffers;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import framework.BufferUtils;
import framework.Profile;
import framework.Semantic;
import framework.Test;
import glm.glm;
import glm.mat._4.Mat4;
import glm.vec._2.Vec2;
import glm.vec._2.i.Vec2i;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

/**
 *
 * @author GBarbieri
 */
public class Gl_500_shader_invocation_nv extends Test {

    public static void main(String[] args) {
        Gl_500_shader_invocation_nv gl_500_shader_invocation_nv = new Gl_500_shader_invocation_nv();
    }

    public Gl_500_shader_invocation_nv() {
        super("gl-500-shader-invocation-nv", Profile.CORE, 4, 5, new Vec2i(1280, 720));
    }

    private final String SHADERS_SOURCE = "shader-invocation";
    private final String SHADERS_ROOT = "src/data/gl_500";

    private class Buffer {

        public static final int CONSTANT = 0;
        public static final int TRANSFORM = 1;
        public static final int VERTEX = 2;
        public static final int MAX = 3;
    }

    private IntBuffer pipelineName = GLBuffers.newDirectIntBuffer(1), vertexArrayName = GLBuffers.newDirectIntBuffer(1),
            bufferName = GLBuffers.newDirectIntBuffer(Buffer.MAX);
    private int programName;
    private FloatBuffer white = GLBuffers.newDirectFloatBuffer(new float[]{1.0f, 1.0f, 1.0f, 1.0f});
    private int quadOverlapCount = 1, vertexCount;
    /**
     * https://jogamp.org/bugzilla/show_bug.cgi?id=1287
     */
    private boolean bug1287 = true;

    @Override
    protected boolean begin(GL gl) {

        GL4 gl4 = (GL4) gl;

        boolean validated = gl4.isExtensionAvailable("GL_NV_shader_thread_group");

        if (validated) {
            validated = initBuffer(gl4);
        }
        if (validated) {
            validated = initProgram(gl4);
        }
        if (validated) {
            validated = initVertexArray(gl4);
        }

        return validated;
    }

    private boolean initProgram(GL4 gl4) {

        boolean validated = true;

        if (validated) {

            ShaderCode vertShaderCode = ShaderCode.create(gl4, GL_VERTEX_SHADER,
                    this.getClass(), SHADERS_ROOT, null, SHADERS_SOURCE, "vert", null, true);
            ShaderCode fragShaderCode = ShaderCode.create(gl4, GL_FRAGMENT_SHADER,
                    this.getClass(), SHADERS_ROOT, null, SHADERS_SOURCE, "frag", null, true);

            ShaderProgram shaderProgram = new ShaderProgram();
            shaderProgram.init(gl4);

            programName = shaderProgram.program();

            gl4.glProgramParameteri(programName, GL_PROGRAM_SEPARABLE, GL_TRUE);

            shaderProgram.add(vertShaderCode);
            shaderProgram.add(fragShaderCode);
            shaderProgram.link(gl4, System.out);
        }

        if (validated) {

            gl4.glGenProgramPipelines(1, pipelineName);
            gl4.glUseProgramStages(pipelineName.get(0), GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT, programName);
        }

        return validated & checkError(gl4, "initProgram");
    }

    private boolean initVertexArray(GL4 gl4) {

        int bindingIndex = 0;

        gl4.glCreateVertexArrays(1, vertexArrayName);

        gl4.glVertexArrayAttribBinding(vertexArrayName.get(0), Semantic.Attr.POSITION, bindingIndex);
        gl4.glVertexArrayAttribFormat(vertexArrayName.get(0), Semantic.Attr.POSITION, 2, GL_FLOAT, false, 0);
        gl4.glEnableVertexArrayAttrib(vertexArrayName.get(0), Semantic.Attr.POSITION);

        gl4.glVertexArrayVertexBuffer(vertexArrayName.get(0), bindingIndex, bufferName.get(Buffer.VERTEX), 0, Vec2.SIZE);

        return true;
    }

    private boolean initBuffer(GL4 gl4) {

        IntBuffer constants = GLBuffers.newDirectIntBuffer(3);

        gl4.glCreateBuffers(Buffer.MAX, bufferName);

        Mat4 mvp = glm.ortho_(0.0f, windowSize.x * 1.0f, 0.0f, windowSize.y * 1f);
        FloatBuffer mvpBuffer = GLBuffers.newDirectFloatBuffer(mvp.toFa_());

        if (!bug1287) {
            gl4.glNamedBufferStorage(bufferName.get(Buffer.TRANSFORM), mvp.SIZE, mvpBuffer, 0);
        } else {
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.TRANSFORM));
            gl4.glBufferStorage(GL_UNIFORM_BUFFER, mvp.SIZE, mvpBuffer, 0);
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);
        }

        gl4.glGetIntegerv(GL_WARP_SIZE_NV, constants);
        constants.position(1);
        gl4.glGetIntegerv(GL_WARPS_PER_SM_NV, constants);
        constants.position(2);
        gl4.glGetIntegerv(GL_SM_COUNT_NV, constants);
        constants.rewind();

        System.out.println("GL_WARP_SIZE_NV: " + constants.get(0));
        System.out.println("GL_WARPS_PER_SM_NV: " + constants.get(1));
        System.out.println("GL_SM_COUNT_NV: " + constants.get(2));

        if (!bug1287) {
            gl4.glNamedBufferStorage(bufferName.get(Buffer.CONSTANT), constants.capacity() * Integer.BYTES, constants, 0);
        } else {
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.CONSTANT));
            gl4.glBufferStorage(GL_UNIFORM_BUFFER, constants.capacity() * Integer.BYTES, constants, 0);
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);
        }

        int windowDiv = 1;
        vertexCount = (windowSize.x / windowDiv) * (windowSize.y / windowDiv) * 6 * quadOverlapCount;
        float[] vertexPosition = new float[vertexCount * 2];

        for (int quadCoordIndexY = 0, quadCoordCountY = windowSize.y / windowDiv; quadCoordIndexY < quadCoordCountY;
                quadCoordIndexY++) {

            for (int quadCoordIndexX = 0, quadCoordCountX = windowSize.x / windowDiv; quadCoordIndexX < quadCoordCountX;
                    quadCoordIndexX++) {

                for (int quadOverlapIndex = 0; quadOverlapIndex < quadOverlapCount; quadOverlapIndex++) {

                    int quadIndex = (quadCoordIndexX + quadCoordCountX * quadCoordIndexY) * quadOverlapCount
                            + quadOverlapIndex;

                    vertexPosition[(quadIndex * 6 + 0) * 2 + 0] = quadCoordIndexX * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 0) * 2 + 1] = quadCoordIndexY * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 1) * 2 + 0] = quadCoordIndexX * 1 + 1;
                    vertexPosition[(quadIndex * 6 + 1) * 2 + 1] = quadCoordIndexY * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 2) * 2 + 0] = quadCoordIndexX * 1 + 1;
                    vertexPosition[(quadIndex * 6 + 2) * 2 + 1] = quadCoordIndexY * 1 + 1;
                    vertexPosition[(quadIndex * 6 + 3) * 2 + 0] = quadCoordIndexX * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 3) * 2 + 1] = quadCoordIndexY * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 4) * 2 + 0] = quadCoordIndexX * 1 + 1;
                    vertexPosition[(quadIndex * 6 + 4) * 2 + 1] = quadCoordIndexY * 1 + 1;
                    vertexPosition[(quadIndex * 6 + 5) * 2 + 0] = quadCoordIndexX * 1 + 0;
                    vertexPosition[(quadIndex * 6 + 5) * 2 + 1] = quadCoordIndexY * 1 + 1;
                }
            }
        }
        FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexPosition);
        if (!bug1287) {
            gl4.glNamedBufferStorage(bufferName.get(Buffer.VERTEX), vertexPosition.length * Float.BYTES, vertexBuffer, 0);
        } else {
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.VERTEX));
            gl4.glBufferStorage(GL_UNIFORM_BUFFER, vertexBuffer.capacity() * Float.BYTES, vertexBuffer, 0);
            gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);
        }
        BufferUtils.destroyDirectBuffer(constants);

        BufferUtils.destroyDirectBuffer(mvpBuffer);
        BufferUtils.destroyDirectBuffer(constants);

        return true;
    }

    @Override
    protected boolean render(GL gl) {

        GL4 gl4 = (GL4) gl;

        gl4.glViewportIndexedf(0, 0, 0, windowSize.x, windowSize.y);
        gl4.glClearBufferfv(GL_COLOR, 0, white);

        gl4.glBindProgramPipeline(pipelineName.get(0));
        gl4.glBindBufferBase(GL_UNIFORM_BUFFER, Semantic.Uniform.CONSTANT, bufferName.get(Buffer.CONSTANT));
        gl4.glBindBufferBase(GL_UNIFORM_BUFFER, Semantic.Uniform.TRANSFORM0, bufferName.get(Buffer.TRANSFORM));
        gl4.glBindVertexArray(vertexArrayName.get(0));

        gl4.glDrawArraysInstancedBaseInstance(GL_TRIANGLES, 0, 6 * vertexCount, 1, 0);

        return true;
    }

    @Override
    protected boolean end(GL gl) {

        GL4 gl4 = (GL4) gl;

        gl4.glDeleteBuffers(Buffer.MAX, bufferName);
        BufferUtils.destroyDirectBuffer(bufferName);
        gl4.glDeleteProgramPipelines(1, pipelineName);
        BufferUtils.destroyDirectBuffer(pipelineName);
        gl4.glDeleteProgram(programName);
        gl4.glDeleteVertexArrays(1, vertexArrayName);
        BufferUtils.destroyDirectBuffer(vertexArrayName);
        BufferUtils.destroyDirectBuffer(white);

        return true;
    }
}


text:
/** *********************** RandomWalker.java *************************************************
*** This program reads a starting point on the 2D plane from a file, as well as a number of	***
*** steps to take. Each step is in a random direction dependent on the random value given	***
*** the random number generator. Steps and final distance squared are written to a file.	***
*** NOTE: THE SAMPLE FILE FROM THE ASSIGNMENT IS CALLED "input.txt"!!! Enter this!			***
***********************************************************************************************/

import java.util.Random; // required to generate random direction
import java.util.Scanner; // required to get name of file
import java.io.*;

public class RandomWalker
{
	public static void main(String[] args) throws IOException
	{
		// Variable declaration
		String directionname = new String();
		int i,x,y,direction,steps;
		int walknumber = 0;

		// Scanner for getting the input file name
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the input file name: ");
		String filename = input.nextLine();

		Random generator = new Random(); // random generator

		// Opens the specified file for input
		File infile = new File(filename);
		Scanner inputFile = new Scanner(infile);

		while (inputFile.hasNext())
		{
			walknumber++;

			x = inputFile.nextInt();
			y = inputFile.nextInt();
			steps = inputFile.nextInt();

			// Opens the specified file for output, with a name depending on the walknumber
			FileWriter file_p = new FileWriter("walk_" + walknumber + ".txt");
			PrintWriter walkfile_p = new PrintWriter(file_p);

			walkfile_p.println("Start at (" + x + "," + y + ") take " + steps + " steps");

			// Loop for each step
			for(i=1;i<=steps;i++)
			{

				// Directions represented by a random integer between 0 and 3 inclusive
				direction = generator.nextInt(4);
				if (direction == 0)
				{
					directionname = "North";
					y = (y + 1);
				}
				if (direction == 1)
				{
					directionname = "East";
					x = (x + 1);
				}
				if (direction == 2)
				{
					directionname = "South";
					y = (y - 1);
				}
				if (direction == 3)
				{
					directionname = "West";
					x = (x - 1);
				}

				walkfile_p.println("Step " + directionname + " to (" + x + "," + y + ")");
			}

			walkfile_p.println("distance squared from start is " + (x * x + y * y));
			walkfile_p.close(); // Closes file
		}
		inputFile.close(); // Closes file
	}
}


text:
"use strict";

const GraphQL = require("../../../../../../src/client/request/graphql");
const GraphQLRequest = require("../../../../../../src/client/request/graphql/request");

describe("GraphQL Configuration", () => {
  let testContext;

  beforeEach(() => {
    testContext = {};
    testContext.configurationUrl =
      "https://localhost/merchant_id/client_api/v1/configuration";
    testContext.config = {
      graphQL: {
        url: "https://localhost/graphql",
        features: ["configuration"],
      },
    };
    testContext.fakeMetadata = {
      source: "my-source",
      integration: "my-integration",
      sessionId: "my-session-id",
    };
    testContext.options = {
      graphQL: new GraphQL(testContext.config),
      url: testContext.configurationUrl,
      headers: {
        FAKE_HEADER: "Fake header",
      },
      metadata: testContext.fakeMetadata,
    };
  });

  describe("adaptResponseBody", () => {
    it("normalizes a GraphQL configuration response", () => {
      const graphQLRequest = new GraphQLRequest(testContext.options);
      const fakeConfigurationResponse = {
        data: {
          clientConfiguration: {
            analyticsUrl: "https://localhost/analytics",
            environment: "DEVELOPMENT",
            merchantId: "merchant_id",
            assetsUrl: "https://localhost",
            clientApiUrl: "https://localhost/merchants/merchant_id/client_api",
            creditCard: {
              supportedCardBrands: [
                "AMERICAN_EXPRESS",
                "DINERS",
                "DISCOVER",
                "ELO",
                "HIPER",
                "HIPERCARD",
                "INTERNATIONAL_MAESTRO",
                "JCB",
                "MASTERCARD",
                "SOLO",
                "UK_MAESTRO",
                "UNION_PAY",
                "UNKNOWN",
                "VISA",
              ],
              challenges: ["CVV"],
              threeDSecureEnabled: false,
              threeDSecure: {
                cardinalAuthenticationJWT: "3ds-jwt",
              },
            },
            supportedFeatures: ["TOKENIZE_CREDIT_CARDS"],
            applePayWeb: {
              countryCode: "US",
              currencyCode: "USD",
              merchantIdentifier: "merchant_id",
              supportedCardBrands: [
                "VISA",
                "MASTERCARD",
                "AMERICAN_EXPRESS",
                "DISCOVER",
                "INTERNATIONAL_MAESTRO",
                "ELO",
              ],
            },
            googlePay: {
              displayName: "merchant",
              environment: "SANDBOX",
              googleAuthorization: "fake_authorization",
              paypalClientId: "client_id",
              supportedCardBrands: [
                "VISA",
                "MASTERCARD",
                "AMERICAN_EXPRESS",
                "DISCOVER",
                "INTERNATIONAL_MAESTRO",
                "ELO",
              ],
            },
            ideal: {
              routeId: "route_id",
              assetsUrl: "https://localhost",
            },
            kount: {
              merchantId: "600000",
            },
            masterpass: {
              merchantCheckoutId: "merchant_checkout_id",
              supportedCardBrands: [
                "VISA",
                "MASTERCARD",
                "AMERICAN_EXPRESS",
                "DISCOVER",
                "DINERS",
                "INTERNATIONAL_MAESTRO",
                "JCB",
              ],
            },
            paypal: {
              displayName: "display_name",
              clientId: "client_id",
              privacyUrl: "http://www.example.com/privacy_policy",
              userAgreementUrl: "http://www.example.com/user_agreement",
              assetsUrl: "https://localhost",
              environmentNoNetwork: false,
              environment: "CUSTOM",
              unvettedMerchant: false,
              braintreeClientId: "braintree_client_id",
              billingAgreementsEnabled: false,
              merchantAccountId: "merchant_account_id",
              currencyCode: "USD",
              payeeEmail: "user@example.com",
            },
            unionPay: {
              merchantAccountId: "merchant_account_id",
            },
            usBankAccount: {
              routeId: "route_id",
              plaidPublicKey: "plaid_public_key",
            },
            venmo: {
              merchantId: "merchant_id",
              accessToken: "access_token",
              environment: "DEVELOPMENT",
            },
            visaCheckout: {
              apiKey: "visa_checkout_api_key",
              encryptionKey: "visa_checkout_encryption_key",
              externalClientId: "external_client_id",
              supportedCardBrands: [
                "VISA",
                "MASTERCARD",
                "AMERICAN_EXPRESS",
                "DISCOVER",
              ],
            },
            braintreeApi: {
              accessToken: "access_token",
              url: "https://payments.sandbox.braintree-api.com",
            },
          },
        },
        extensions: {
          requestId: "fake-request-id",
        },
      };
      const configurationResponse = {
        challenges: ["cvv"],
        threeDSecureEnabled: false,
        threeDSecure: {
          cardinalAuthenticationJWT: "3ds-jwt",
        },
        analytics: {
          url: "https://localhost/analytics",
        },
        environment: "development",
        merchantId: "merchant_id",
        assetsUrl: "https://localhost",
        clientApiUrl: "https://localhost/merchants/merchant_id/client_api",
        applePayWeb: {
          countryCode: "US",
          currencyCode: "USD",
          merchantIdentifier: "merchant_id",
          supportedNetworks: [
            "visa",
            "mastercard",
            "amex",
            "discover",
            "maestro",
            "elo",
          ],
        },
        kount: {
          kountMerchantId: "600000",
        },
        masterpass: {
          merchantCheckoutId: "merchant_checkout_id",
          supportedNetworks: [
            "visa",
            "master",
            "amex",
            "discover",
            "diners",
            "maestro",
            "jcb",
          ],
        },
        paypalEnabled: true,
        paypal: {
          displayName: "display_name",
          clientId: "client_id",
          privacyUrl: "http://www.example.com/privacy_policy",
          userAgreementUrl: "http://www.example.com/user_agreement",
          assetsUrl: "https://localhost",
          environment: "custom",
          environmentNoNetwork: false,
          unvettedMerchant: false,
          braintreeClientId: "braintree_client_id",
          billingAgreementsEnabled: false,
          merchantAccountId: "merchant_account_id",
          currencyIsoCode: "USD",
          payeeEmail: "user@example.com",
        },
        unionPay: {
          enabled: true,
          merchantAccountId: "merchant_account_id",
        },
        visaCheckout: {
          apikey: "visa_checkout_api_key",
          encryptionKey: "visa_checkout_encryption_key",
          externalClientId: "external_client_id",
          supportedCardTypes: [
            "Visa",
            "MasterCard",
            "American Express",
            "Discover",
          ],
        },
        graphQL: {
          url: "https://localhost/graphql",
          features: ["tokenize_credit_cards"],
        },
        venmo: "off",
        braintreeApi: {
          accessToken: "access_token",
          url: "https://payments.sandbox.braintree-api.com",
        },
        payWithVenmo: {
          accessToken: "access_token",
          environment: "development",
          merchantId: "merchant_id",
        },
        androidPay: {
          displayName: "merchant",
          enabled: true,
          environment: "sandbox",
          googleAuthorizationFingerprint: "fake_authorization",
          paypalClientId: "client_id",
          supportedNetworks: [
            "visa",
            "mastercard",
            "amex",
            "discover",
            "maestro",
            "elo",
          ],
        },
        creditCards: {
          supportedCardTypes: [
            "American Express",
            "Discover",
            "Elo",
            "Hiper",
            "Hipercard",
            "Maestro",
            "JCB",
            "MasterCard",
            "Solo",
            "UK Maestro",
            "UnionPay",
            "Visa",
          ],
        },
        ideal: {
          routeId: "route_id",
          assetsUrl: "https://localhost",
        },
        usBankAccount: {
          routeId: "route_id",
          plaid: {
            publicKey: "plaid_public_key",
          },
        },
      };
      const adaptedResponse = graphQLRequest.adaptResponseBody(
        fakeConfigurationResponse
      );

      expect(adaptedResponse.challenges).toEqual(
        configurationResponse.challenges
      );
      expect(adaptedResponse.threeDSecureEnabled).toEqual(
        configurationResponse.threeDSecureEnabled
      );
      expect(adaptedResponse.analytics).toEqual(
        configurationResponse.analytics
      );
      expect(adaptedResponse.environment).toEqual(
        configurationResponse.environment
      );
      expect(adaptedResponse.merchantId).toEqual(
        configurationResponse.merchantId
      );
      expect(adaptedResponse.assetsUrl).toEqual(
        configurationResponse.assetsUrl
      );
      expect(adaptedResponse.clientApiUrl).toEqual(
        configurationResponse.clientApiUrl
      );

      expect(adaptedResponse.applePayWeb).toEqual(
        configurationResponse.applePayWeb
      );
      expect(adaptedResponse.kount).toEqual(configurationResponse.kount);
      expect(adaptedResponse.masterpass).toEqual(
        configurationResponse.masterpass
      );
      expect(adaptedResponse.paypalEnabled).toEqual(
        configurationResponse.paypalEnabled
      );
      expect(adaptedResponse.paypal).toEqual(configurationResponse.paypal);
      expect(adaptedResponse.unionPay).toEqual(configurationResponse.unionPay);
      expect(adaptedResponse.visaCheckout).toEqual(
        configurationResponse.visaCheckout
      );

      expect(adaptedResponse.graphQL).toEqual(configurationResponse.graphQL);
      expect(adaptedResponse.venmo).toEqual(configurationResponse.venmo);
      expect(adaptedResponse.payWithVenmo).toEqual(
        configurationResponse.payWithVenmo
      );
      expect(adaptedResponse.androidPay).toEqual(
        configurationResponse.androidPay
      );
      expect(adaptedResponse.creditCards).toEqual(
        configurationResponse.creditCards
      );
      expect(adaptedResponse.ideal).toEqual(configurationResponse.ideal);
      expect(adaptedResponse.usBankAccount).toEqual(
        configurationResponse.usBankAccount
      );
      expect(adaptedResponse.braintreeApi).toEqual(
        configurationResponse.braintreeApi
      );

      expect(adaptedResponse).toEqual(configurationResponse);
    });

    describe("field adapters", () => {
      beforeEach(() => {
        testContext.graphQLRequest = new GraphQLRequest(testContext.options);
        testContext.fakeEmptyConfigurationResponse = {
          data: {
            clientConfiguration: {
              analyticsUrl: "https://localhost/analytics",
              environment: "DEVELOPMENT",
              merchantId: "merchant_id",
              assetsUrl: "https://localhost",
              clientApiUrl:
                "https://localhost/merchants/merchant_id/client_api",
              creditCard: null,
              applePayWeb: null,
              googlePay: null,
              ideal: null,
              kount: null,
              masterpass: null,
              paypal: null,
              unionPay: null,
              usBankAccount: null,
              venmo: null,
              visaCheckout: null,
            },
          },
          extensions: {
            requestId: "fake-request-id",
          },
        };
      });
      it("correctly handles null fields", () => {
        const adaptedResponse = testContext.graphQLRequest.adaptResponseBody(
          testContext.fakeEmptyConfigurationResponse
        );

        expect(adaptedResponse.creditCards).toEqual({
          supportedCardTypes: [],
        });
        expect(adaptedResponse.challenges).toEqual([]);
        expect(adaptedResponse.threeDSecureEnabled).toBe(false);

        expect(adaptedResponse.paypal).toBeUndefined();
        expect(adaptedResponse.paypalEnabled).toBe(false);

        expect(adaptedResponse.payWithVenmo).toBeUndefined();
        expect(adaptedResponse.androidPay).toBeUndefined();
        expect(adaptedResponse.braintreeApi).toBeUndefined();
        expect(adaptedResponse.kount).toBeUndefined();
        expect(adaptedResponse.unionPay).toBeUndefined();
        expect(adaptedResponse.visaCheckout).toBeUndefined();
        expect(adaptedResponse.masterpass).toBeUndefined();
        expect(adaptedResponse.usBankAccount).toBeUndefined();
        expect(adaptedResponse.ideal).toBeUndefined();
        expect(adaptedResponse.graphQL).toBeUndefined();
      });
    });
  });
});


text:
<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <title>FizzBuzzApp</title>
  </head>
  <body>
    <div style="width: 80%; margin-left: 25px;">
      <app>Loading…</app>
      <script src="./bundle.js"></script>
    </div>
  </body>
</html>


text:
<?php

class Model_User extends CI_Model
{

  function __construct()
  {
    parent::__construct();
    $this->load->database();
  }

  public function selPerfil(){
    $query = $this->db->query("Select * from perfil");
    return $query->result();
  }

  public function insertUsuario($idper, $nombre, $apellido, $correo, $telefono){

        $arrayDatos = array(
            'per_id' => $idper,
            'usu_nombres' => $nombre,
            'usu_apellidos' => $apellido,
            'usu_correo' => $correo,
            'usu_telefono' => $telefono
        );

        $this->db->insert('usuario', $arrayDatos);

    }

    //funcion para listar usuarios
    public function listUsuario(){
        $query = $this->db->query("SELECT * FROM usuario u inner join perfil p on u.per_id=p.per_id");
        return $query->result();
    }

    public function deleteUsuario($id){
        $this->db->where('usu_id', $id);
        $this->db->delete('usuario');
    }

    public function editUsuario($id){
      $consulta = $this->db->query("SELECT * FROM usuario u inner join perfil p on u.per_id = p.per_id WHERE u.usu_id = $id");
      return $consulta->result();
    }

    public function updateUsuario($txtUsuid,$txtPerid, $txtNombre, $txtApellido, $txtCorreo, $txtTelefono){
        $array = array(
            'per_id' => $txtPerid,
            'usu_nombres' => $txtNombre,
            'usu_apellidos' => $txtApellido,
            'usu_correo' => $txtCorreo,
            'usu_telefono' => $txtTelefono
        );
        $this->db->where('usu_id', $txtUsuid);
        $this->db->update('usuario',$array);
    }

}


text:
My Ph.D. dissertation.

Yep. Finally created this repo.


text:
package org.apache.geronimo.system.logging.log4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.Configurator;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.xml.DOMConfigurator;

/**
 * Handles the details of configuring Log4j from a URL.
 *
 * @version $Rev$ $Date$
 */
public class URLConfigurator implements Configurator {
    private static final Log log = LogFactory.getLog(URLConfigurator.class);

    public static void configure(final URL url) {
        new URLConfigurator().doConfigure(url, LogManager.getLoggerRepository());
    }

    private Configurator getConfigurator(final URL url) throws FileNotFoundException {
        String contentType = null;

        // Get the content type to see if it is XML or not
        URLConnection connection = null;
        try {
            connection = url.openConnection();
            contentType = connection.getContentType();
            if (log.isTraceEnabled()) {
                log.trace("Content type: " + contentType);
            }
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            log.warn("Could not determine content type from URL; ignoring", e);
        }
        if (contentType != null) {
            if (contentType.toLowerCase().endsWith("/xml")) {
                return new DOMConfigurator();
            }
        }

        // Check thr file name
        String filename = url.getFile().toLowerCase();
        if (filename.endsWith(".xml")) {
            return new DOMConfigurator();
        } else if (filename.endsWith(".properties")) {
            return new PropertyConfigurator();
        }

        // Check for <?xml in content
        if (connection != null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                try {
                    String head = reader.readLine();
                    if (head.startsWith("<?xml")) {
                        return new DOMConfigurator();
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException e) {
                log.warn("Failed to check content header; ignoring", e);
            }
        }

        log.warn("Unable to determine content type, using property configurator");
        return new PropertyConfigurator();
    }

    public void doConfigure(final URL url, final LoggerRepository repo) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring from URL: " + url);
        }

        // Get the config delegate and target repository to config with
        Configurator delegate = null;
        try {
            delegate = getConfigurator(url);
        } catch (FileNotFoundException e) {
            return;
        }

        if (log.isTraceEnabled()) {
            log.trace("Configuring Log4j using configurator: " +
                    delegate + ", repository: " + repo);
        }

        // Now actually configure Log4j
        delegate.doConfigure(url, repo);
    }
}


text:
@extends('layouts.app')

{{--  // add default navbar to your page  --}}

@section('content')

{{--  // body content   --}}

Add New Task

    <form method="POST" action="/task">
        {{ csrf_field() }}

            <textarea name="description" class="form-control"></textarea>

            <button type="submit" class="btn btn-primary">Add Task</button>

    </form>

@endsection


text:
#import "CHLinkedList.h"

/**
 @file CHSinglyLinkedList.h
 A standard singly-linked list implementation with pointers to head and tail.
 */

/** A struct for nodes in a CHSinglyLinkedList. */
typedef struct CHSinglyLinkedListNode {
	id object; ///< The object associated with this node in the list.
	__strong struct CHSinglyLinkedListNode *next; ///< The next node in the list.
} CHSinglyLinkedListNode;

#pragma mark -

/**
 A standard singly-linked list implementation with pointers to head and tail. This is ideally suited for use in LIFO and FIFO structures (stacks and queues). The lack of backwards links precludes backwards enumeration, and removing from the tail of the list is O(n), rather than O(1). However, other operations are slightly faster than for doubly-linked lists. Nodes are represented with C structs, providing much faster performance than Objective-C objects.

 This implementation uses a dummy head node, which simplifies both insertion and deletion by eliminating the need to check whether the first node in the list must change. We opt not to use a dummy tail node since the lack of a previous pointer makes starting at the end of the list rather pointless. The pointer to the tail (either the dummy head node or the last "real" node in the list) is only used for inserting at the end without traversing the entire list first. The figures below demonstrate what a singly-linked list looks like when it contains 0 objects, 1 object, and 2 or more objects.

 @image html singly-linked-0.png Figure 1 - Singly-linked list with 0 objects.

 @image html singly-linked-1.png Figure 2 - Singly-linked list with 1 object.

 @image html singly-linked-N.png Figure 3 - Singly-linked list with 2+ objects.

 To reduce code duplication, all methods that append or prepend objects to the list call \link #insertObject:atIndex:\endlink, and the methods to remove the first or last objects use \link #removeObjectAtIndex:\endlink underneath.

 Singly-linked lists are well-suited as an underlying collection for other data structures, such as stacks and queues (see CHListStack and CHListQueue). The same functionality can be achieved using a circular buffer and an array, and many libraries choose to do so when objects are only added to or removed from the ends, but the dynamic structure of a linked list is much more flexible when inserting and deleting in the middle of a list.

 The primary weakness of singly-linked lists is the absence of a previous link. Since insertion and deletion involve changing the @c next link of the preceding node, and there is no way to step backwards through the list, traversal must always begin at the head, even if searching for an index that is very close to the tail. This does not mean that singly-linked lists are inherently bad, only that they are not well-suited for all possible applications. As usual, all data access attributes should be considered before choosing a data strcuture.
 */
@interface CHSinglyLinkedList : NSObject <CHLinkedList>
{
	__strong CHSinglyLinkedListNode *head; // Dummy node at the front of the list.
	__strong CHSinglyLinkedListNode *tail; // Pointer to last node in a list.
	__strong CHSinglyLinkedListNode *cachedNode; // Pointer to last accessed node.
	NSUInteger cachedIndex; // Index of last accessed node.
	NSUInteger count; // The number of objects currently stored in a list.
	unsigned long mutations; // Tracks mutations for NSFastEnumeration.
}

@end


text:
const co = require('co');
const Node = require('../../../lib/Kubernetes/Node');

module.exports = function makeSchedulable(nodeName) {
	const node = new Node(nodeName);
	return node.makeSchedulable()
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE476_NULL_Pointer_Dereference__int64_t_01.c
Label Definition File: CWE476_NULL_Pointer_Dereference.label.xml
Template File: sources-sinks-01.tmpl.c
*/
/*
 * @description
 * CWE: 476 NULL Pointer Dereference
 * BadSource:  Set data to NULL
 * GoodSource: Initialize data
 * Sinks:
 *    GoodSink: Check for NULL before attempting to print data
 *    BadSink : Print data
 * Flow Variant: 01 Baseline
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE476_NULL_Pointer_Dereference__int64_t_01_bad()
{
    int64_t * data;
    /* POTENTIAL FLAW: Set data to NULL */
    data = NULL;
    /* POTENTIAL FLAW: Attempt to use data, which may be NULL */
    printLongLongLine(*data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    int64_t * data;
    int64_t tmpData = 5LL;
    /* FIX: Initialize data */
    {
        data = &tmpData;
    }
    /* POTENTIAL FLAW: Attempt to use data, which may be NULL */
    printLongLongLine(*data);
}

/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
    int64_t * data;
    /* POTENTIAL FLAW: Set data to NULL */
    data = NULL;
    /* FIX: Check for NULL before attempting to print data */
    if (data != NULL)
    {
        printLongLongLine(*data);
    }
    else
    {
        printLine("data is NULL");
    }
}

void CWE476_NULL_Pointer_Dereference__int64_t_01_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE476_NULL_Pointer_Dereference__int64_t_01_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE476_NULL_Pointer_Dereference__int64_t_01_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
/* $Id$ */

package org.apache.fop.render.bitmap;

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

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.apps.io.InternalResourceResolver;
import org.apache.fop.fonts.EmbedFontInfo;
import org.apache.fop.fonts.FontCollection;
import org.apache.fop.render.RendererConfig.RendererConfigParser;
import org.apache.fop.render.bitmap.BitmapRendererConfig.BitmapRendererConfigParser;
import org.apache.fop.render.intermediate.IFDocumentHandler;
import org.apache.fop.render.java2d.Base14FontCollection;
import org.apache.fop.render.java2d.ConfiguredFontCollection;
import org.apache.fop.render.java2d.InstalledFontCollection;
import org.apache.fop.render.java2d.Java2DFontMetrics;
import org.apache.fop.render.java2d.Java2DRendererConfigurator;

/**
 * Configurator for bitmap output.
 */
public class BitmapRendererConfigurator extends Java2DRendererConfigurator {

    /**
     * Default constructor
     * @param userAgent user agent
     */
    public BitmapRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) {
        super(userAgent, rendererConfigParser);
    }

    // ---=== IFDocumentHandler configuration ===---

    /** {@inheritDoc} */
    public void configure(IFDocumentHandler documentHandler) throws FOPException {
        AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler) documentHandler;
        BitmapRenderingSettings settings = bitmapHandler.getSettings();
        configure(documentHandler, settings,
                new BitmapRendererConfigParser(MimeConstants.MIME_BITMAP));
    }

    void configure(IFDocumentHandler documentHandler, BitmapRenderingSettings settings,
            BitmapRendererConfigParser parser) throws FOPException {
        BitmapRendererConfig config = (BitmapRendererConfig) userAgent.getRendererConfig(
                documentHandler.getMimeType(), parser);
        configure(config, settings);
    }

    private void configure(BitmapRendererConfig config, BitmapRenderingSettings settings)
            throws FOPException {
        if (config.hasTransparentBackround()) {
            settings.setPageBackgroundColor(null);
        } else if (config.getBackgroundColor() != null) {
            settings.setPageBackgroundColor(config.getBackgroundColor());
        }
        if (config.hasAntiAliasing() != null) {
            settings.setAntiAliasing(config.hasAntiAliasing());
        }
        if (config.isRenderHighQuality() != null) {
            settings.setQualityRendering(config.isRenderHighQuality());
        }
        if (config.getColorMode() != null) {
            settings.setBufferedImageType(config.getColorMode());
        }
    }

    @Override
    protected FontCollection createCollectionFromFontList(InternalResourceResolver resourceResolver,
            List<EmbedFontInfo> fontList) {
        return new ConfiguredFontCollection(resourceResolver, fontList, userAgent.isComplexScriptFeaturesEnabled());
    }

    @Override
    protected List<FontCollection> getDefaultFontCollection() {
        final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics();
        final List<FontCollection> fontCollection = new ArrayList<FontCollection>();
        fontCollection.add(new Base14FontCollection(java2DFontMetrics));
        fontCollection.add(new InstalledFontCollection(java2DFontMetrics));
        return fontCollection;
    }
}


text:
import {AuthService} from '../auth/AuthService';
import {autoinject} from 'aurelia-framework';

@autoinject
export class Logout{

	auth:AuthService;

	constructor(auth:AuthService){
		this.auth = auth;
	};

	 activate(){
		this.auth.logout("/login").then(response=>{
			console.log("ok logged out on  logout.js");
		})
		.catch(err=>{
			console.log("error logged out  logout.js");

		});
	}
}


text:
<?php
if(!defined('SYSTEM_PATH')) exit('Access Denied');

/**
 * 需要安装phpredis扩展
 * 继承自Redis,用于操作redis
 */
class Rediz extends Redis{
    public function __construct($redisconfig = array()){
        parent::__construct();
        if(empty($redisconfig)){
            $redisconfigs = load_config("redis");
            $redisconfig = $redisconfigs['default'];
        }
        if(!empty($redisconfig['host']) && empty($redisconfig['port']) && empty($redisconfig['timeout']))
            parent::connect($redisconfig['host']);
        else if(!empty($redisconfig['host']) && !empty($redisconfig['port']) && empty($redisconfig['timeout']))
            parent::connect($redisconfig['host'], $redisconfig['port']);
        else if(!empty($redisconfig['host']) && !empty($redisconfig['port']) && !empty($redisconfig['timeout']))
            parent::connect($redisconfig['host'], $redisconfig['port'], $redisconfig['timeout']);
        if(!empty($redisconfig['auth']))
            parent::auth($redisconfig['auth']);
    }
}


text:
namespace content {
namespace {

base::LazyInstance<std::set<gfx::GpuMemoryBuffer::Usage>>
    g_enabled_gpu_memory_buffer_usages;
}

BrowserGpuChannelHostFactory* BrowserGpuChannelHostFactory::instance_ = NULL;

struct BrowserGpuChannelHostFactory::CreateRequest {
  CreateRequest(int32 route_id)
      : event(true, false),
        gpu_host_id(0),
        route_id(route_id),
        result(CREATE_COMMAND_BUFFER_FAILED) {}
  ~CreateRequest() {}
  base::WaitableEvent event;
  int gpu_host_id;
  int32 route_id;
  CreateCommandBufferResult result;
};

class BrowserGpuChannelHostFactory::EstablishRequest
    : public base::RefCountedThreadSafe<EstablishRequest> {
 public:
  static scoped_refptr<EstablishRequest> Create(CauseForGpuLaunch cause,
                                                int gpu_client_id,
                                                int gpu_host_id);
  void Wait();
  void Cancel();

  int gpu_host_id() { return gpu_host_id_; }
  IPC::ChannelHandle& channel_handle() { return channel_handle_; }
  gpu::GPUInfo gpu_info() { return gpu_info_; }

 private:
  friend class base::RefCountedThreadSafe<EstablishRequest>;
  explicit EstablishRequest(CauseForGpuLaunch cause,
                            int gpu_client_id,
                            int gpu_host_id);
  ~EstablishRequest() {}
  void EstablishOnIO();
  void OnEstablishedOnIO(const IPC::ChannelHandle& channel_handle,
                         const gpu::GPUInfo& gpu_info);
  void FinishOnIO();
  void FinishOnMain();

  base::WaitableEvent event_;
  CauseForGpuLaunch cause_for_gpu_launch_;
  const int gpu_client_id_;
  int gpu_host_id_;
  bool reused_gpu_process_;
  IPC::ChannelHandle channel_handle_;
  gpu::GPUInfo gpu_info_;
  bool finished_;
  scoped_refptr<base::MessageLoopProxy> main_loop_;
};

scoped_refptr<BrowserGpuChannelHostFactory::EstablishRequest>
BrowserGpuChannelHostFactory::EstablishRequest::Create(CauseForGpuLaunch cause,
                                                       int gpu_client_id,
                                                       int gpu_host_id) {
  scoped_refptr<EstablishRequest> establish_request =
      new EstablishRequest(cause, gpu_client_id, gpu_host_id);
  scoped_refptr<base::MessageLoopProxy> loop =
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
  // PostTask outside the constructor to ensure at least one reference exists.
  loop->PostTask(
      FROM_HERE,
      base::Bind(&BrowserGpuChannelHostFactory::EstablishRequest::EstablishOnIO,
                 establish_request));
  return establish_request;
}

BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest(
    CauseForGpuLaunch cause,
    int gpu_client_id,
    int gpu_host_id)
    : event_(false, false),
      cause_for_gpu_launch_(cause),
      gpu_client_id_(gpu_client_id),
      gpu_host_id_(gpu_host_id),
      reused_gpu_process_(false),
      finished_(false),
      main_loop_(base::MessageLoopProxy::current()) {
}

void BrowserGpuChannelHostFactory::EstablishRequest::EstablishOnIO() {
  GpuProcessHost* host = GpuProcessHost::FromID(gpu_host_id_);
  if (!host) {
    host = GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
                               cause_for_gpu_launch_);
    if (!host) {
      LOG(ERROR) << "Failed to launch GPU process.";
      FinishOnIO();
      return;
    }
    gpu_host_id_ = host->host_id();
    reused_gpu_process_ = false;
  } else {
    if (reused_gpu_process_) {
      // We come here if we retried to establish the channel because of a
      // failure in ChannelEstablishedOnIO, but we ended up with the same
      // process ID, meaning the failure was not because of a channel error,
      // but another reason. So fail now.
      LOG(ERROR) << "Failed to create channel.";
      FinishOnIO();
      return;
    }
    reused_gpu_process_ = true;
  }

  host->EstablishGpuChannel(
      gpu_client_id_,
      true,
      true,
      base::Bind(
          &BrowserGpuChannelHostFactory::EstablishRequest::OnEstablishedOnIO,
          this));
}

void BrowserGpuChannelHostFactory::EstablishRequest::OnEstablishedOnIO(
    const IPC::ChannelHandle& channel_handle,
    const gpu::GPUInfo& gpu_info) {
  if (channel_handle.name.empty() && reused_gpu_process_) {
    // We failed after re-using the GPU process, but it may have died in the
    // mean time. Retry to have a chance to create a fresh GPU process.
    DVLOG(1) << "Failed to create channel on existing GPU process. Trying to "
                "restart GPU process.";
    EstablishOnIO();
  } else {
    channel_handle_ = channel_handle;
    gpu_info_ = gpu_info;
    FinishOnIO();
  }
}

void BrowserGpuChannelHostFactory::EstablishRequest::FinishOnIO() {
  event_.Signal();
  main_loop_->PostTask(
      FROM_HERE,
      base::Bind(&BrowserGpuChannelHostFactory::EstablishRequest::FinishOnMain,
                 this));
}

void BrowserGpuChannelHostFactory::EstablishRequest::FinishOnMain() {
  if (!finished_) {
    BrowserGpuChannelHostFactory* factory =
        BrowserGpuChannelHostFactory::instance();
    factory->GpuChannelEstablished();
    finished_ = true;
  }
}

void BrowserGpuChannelHostFactory::EstablishRequest::Wait() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  {
    // TODO(vadimt): Remove ScopedTracker below once crbug.com/125248 is fixed.
    tracked_objects::ScopedTracker tracking_profile(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "125248 BrowserGpuChannelHostFactory::EstablishRequest::Wait"));

    // We're blocking the UI thread, which is generally undesirable.
    // In this case we need to wait for this before we can show any UI
    // /anyway/, so it won't cause additional jank.
    // TODO(piman): Make this asynchronous (http://crbug.com/125248).
    TRACE_EVENT0("browser",
                 "BrowserGpuChannelHostFactory::EstablishGpuChannelSync");
    base::ThreadRestrictions::ScopedAllowWait allow_wait;
    event_.Wait();
  }
  FinishOnMain();
}

void BrowserGpuChannelHostFactory::EstablishRequest::Cancel() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  finished_ = true;
}

bool BrowserGpuChannelHostFactory::CanUseForTesting() {
  return GpuDataManager::GetInstance()->GpuAccessAllowed(NULL);
}

void BrowserGpuChannelHostFactory::Initialize(bool establish_gpu_channel) {
  DCHECK(!instance_);
  instance_ = new BrowserGpuChannelHostFactory();
  if (establish_gpu_channel) {
    instance_->EstablishGpuChannel(CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP,
                                   base::Closure());
  }
}

void BrowserGpuChannelHostFactory::Terminate() {
  DCHECK(instance_);
  delete instance_;
  instance_ = NULL;
}

// static
void BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
    gfx::GpuMemoryBuffer::Usage usage) {
  g_enabled_gpu_memory_buffer_usages.Get().insert(usage);
}

// static
bool BrowserGpuChannelHostFactory::IsGpuMemoryBufferFactoryUsageEnabled(
    gfx::GpuMemoryBuffer::Usage usage) {
  return g_enabled_gpu_memory_buffer_usages.Get().count(usage) != 0;
}

BrowserGpuChannelHostFactory::BrowserGpuChannelHostFactory()
    : gpu_client_id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
      shutdown_event_(new base::WaitableEvent(true, false)),
      gpu_memory_buffer_manager_(
          new BrowserGpuMemoryBufferManager(this, gpu_client_id_)),
      gpu_host_id_(0),
      next_create_gpu_memory_buffer_request_id_(0) {
}

BrowserGpuChannelHostFactory::~BrowserGpuChannelHostFactory() {
  DCHECK(IsMainThread());
  if (pending_request_.get())
    pending_request_->Cancel();
  for (size_t n = 0; n < established_callbacks_.size(); n++)
    established_callbacks_[n].Run();
  shutdown_event_->Signal();
}

bool BrowserGpuChannelHostFactory::IsMainThread() {
  return BrowserThread::CurrentlyOn(BrowserThread::UI);
}

base::MessageLoop* BrowserGpuChannelHostFactory::GetMainLoop() {
  return BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::UI);
}

scoped_refptr<base::MessageLoopProxy>
BrowserGpuChannelHostFactory::GetIOLoopProxy() {
  return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}

scoped_ptr<base::SharedMemory>
BrowserGpuChannelHostFactory::AllocateSharedMemory(size_t size) {
  scoped_ptr<base::SharedMemory> shm(new base::SharedMemory());
  if (!shm->CreateAnonymous(size))
    return scoped_ptr<base::SharedMemory>();
  return shm.Pass();
}

void BrowserGpuChannelHostFactory::CreateViewCommandBufferOnIO(
    CreateRequest* request,
    int32 surface_id,
    const GPUCreateCommandBufferConfig& init_params) {
  GpuProcessHost* host = GpuProcessHost::FromID(gpu_host_id_);
  if (!host) {
    request->event.Signal();
    return;
  }

  gfx::GLSurfaceHandle surface =
      GpuSurfaceTracker::Get()->GetSurfaceHandle(surface_id);

  host->CreateViewCommandBuffer(
      surface,
      surface_id,
      gpu_client_id_,
      init_params,
      request->route_id,
      base::Bind(&BrowserGpuChannelHostFactory::CommandBufferCreatedOnIO,
                 request));
}

// static
void BrowserGpuChannelHostFactory::CommandBufferCreatedOnIO(
    CreateRequest* request, CreateCommandBufferResult result) {
  request->result = result;
  request->event.Signal();
}

CreateCommandBufferResult BrowserGpuChannelHostFactory::CreateViewCommandBuffer(
      int32 surface_id,
      const GPUCreateCommandBufferConfig& init_params,
      int32 route_id) {
  CreateRequest request(route_id);
  GetIOLoopProxy()->PostTask(FROM_HERE, base::Bind(
        &BrowserGpuChannelHostFactory::CreateViewCommandBufferOnIO,
        base::Unretained(this),
        &request,
        surface_id,
        init_params));
  // TODO(vadimt): Remove ScopedTracker below once crbug.com/125248 is fixed.
  tracked_objects::ScopedTracker tracking_profile(
      FROM_HERE_WITH_EXPLICIT_FUNCTION(
          "125248 BrowserGpuChannelHostFactory::CreateViewCommandBuffer"));

  // We're blocking the UI thread, which is generally undesirable.
  // In this case we need to wait for this before we can show any UI /anyway/,
  // so it won't cause additional jank.
  // TODO(piman): Make this asynchronous (http://crbug.com/125248).
  TRACE_EVENT0("browser",
               "BrowserGpuChannelHostFactory::CreateViewCommandBuffer");
  base::ThreadRestrictions::ScopedAllowWait allow_wait;
  request.event.Wait();
  return request.result;
}

// Blocking the UI thread to open a GPU channel is not supported on Android.
// (Opening the initial channel to a child process involves handling a reply
// task on the UI thread first, so we cannot block here.)
#if !defined(OS_ANDROID)
GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync(
    CauseForGpuLaunch cause_for_gpu_launch) {
  EstablishGpuChannel(cause_for_gpu_launch, base::Closure());

  if (pending_request_.get())
    pending_request_->Wait();

  return gpu_channel_.get();
}
#endif

void BrowserGpuChannelHostFactory::EstablishGpuChannel(
    CauseForGpuLaunch cause_for_gpu_launch,
    const base::Closure& callback) {
  if (gpu_channel_.get() && gpu_channel_->IsLost()) {
    DCHECK(!pending_request_.get());
    // Recreate the channel if it has been lost.
    gpu_channel_ = NULL;
  }

  if (!gpu_channel_.get() && !pending_request_.get()) {
    // We should only get here if the context was lost.
    pending_request_ = EstablishRequest::Create(
        cause_for_gpu_launch, gpu_client_id_, gpu_host_id_);
  }

  if (!callback.is_null()) {
    if (gpu_channel_.get())
      callback.Run();
    else
      established_callbacks_.push_back(callback);
  }
}

GpuChannelHost* BrowserGpuChannelHostFactory::GetGpuChannel() {
  if (gpu_channel_.get() && !gpu_channel_->IsLost())
    return gpu_channel_.get();

  return NULL;
}

void BrowserGpuChannelHostFactory::GpuChannelEstablished() {
  DCHECK(IsMainThread());
  DCHECK(pending_request_.get());
  if (pending_request_->channel_handle().name.empty()) {
    DCHECK(!gpu_channel_.get());
  } else {
    GetContentClient()->SetGpuInfo(pending_request_->gpu_info());
    gpu_channel_ =
        GpuChannelHost::Create(this,
                               pending_request_->gpu_info(),
                               pending_request_->channel_handle(),
                               shutdown_event_.get(),
                               BrowserGpuMemoryBufferManager::current());
  }
  gpu_host_id_ = pending_request_->gpu_host_id();
  pending_request_ = NULL;

  for (size_t n = 0; n < established_callbacks_.size(); n++)
    established_callbacks_[n].Run();

  established_callbacks_.clear();
}

// static
void BrowserGpuChannelHostFactory::AddFilterOnIO(
    int host_id,
    scoped_refptr<IPC::MessageFilter> filter) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  GpuProcessHost* host = GpuProcessHost::FromID(host_id);
  if (host)
    host->AddFilter(filter.get());
}

bool BrowserGpuChannelHostFactory::IsGpuMemoryBufferConfigurationSupported(
    gfx::GpuMemoryBuffer::Format format,
    gfx::GpuMemoryBuffer::Usage usage) {
  // Return early if usage is not enabled.
  if (!IsGpuMemoryBufferFactoryUsageEnabled(usage))
    return false;

  // Preferred type is always used by factory.
  std::vector<gfx::GpuMemoryBufferType> supported_types;
  GpuMemoryBufferFactory::GetSupportedTypes(&supported_types);
  DCHECK(!supported_types.empty());
  switch (supported_types[0]) {
    case gfx::SHARED_MEMORY_BUFFER:
      // Shared memory buffers must be created in-process.
      return false;
#if defined(OS_MACOSX)
    case gfx::IO_SURFACE_BUFFER:
      return GpuMemoryBufferFactoryIOSurface::
          IsGpuMemoryBufferConfigurationSupported(format, usage);
#endif
#if defined(OS_ANDROID)
    case gfx::SURFACE_TEXTURE_BUFFER:
      return GpuMemoryBufferFactorySurfaceTexture::
          IsGpuMemoryBufferConfigurationSupported(format, usage);
#endif
#if defined(USE_OZONE)
    case gfx::OZONE_NATIVE_BUFFER:
      return GpuMemoryBufferFactoryOzoneNativeBuffer::
          IsGpuMemoryBufferConfigurationSupported(format, usage);
#endif
    default:
      NOTREACHED();
      return false;
  }
}

void BrowserGpuChannelHostFactory::CreateGpuMemoryBuffer(
    gfx::GpuMemoryBufferId id,
    const gfx::Size& size,
    gfx::GpuMemoryBuffer::Format format,
    gfx::GpuMemoryBuffer::Usage usage,
    int client_id,
    int32 surface_id,
    const CreateGpuMemoryBufferCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  GpuProcessHost* host = GpuProcessHost::FromID(gpu_host_id_);
  if (!host) {
    callback.Run(gfx::GpuMemoryBufferHandle());
    return;
  }

  uint32 request_id = next_create_gpu_memory_buffer_request_id_++;
  create_gpu_memory_buffer_requests_[request_id] = callback;

  host->CreateGpuMemoryBuffer(
      id, size, format, usage, client_id, surface_id,
      base::Bind(&BrowserGpuChannelHostFactory::OnGpuMemoryBufferCreated,
                 base::Unretained(this), request_id));
}

void BrowserGpuChannelHostFactory::DestroyGpuMemoryBuffer(
    gfx::GpuMemoryBufferId id,
    int client_id,
    int32 sync_point) {
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&BrowserGpuChannelHostFactory::DestroyGpuMemoryBufferOnIO,
                 base::Unretained(this),
                 id,
                 client_id,
                 sync_point));
}

void BrowserGpuChannelHostFactory::DestroyGpuMemoryBufferOnIO(
    gfx::GpuMemoryBufferId id,
    int client_id,
    int32 sync_point) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  GpuProcessHost* host = GpuProcessHost::FromID(gpu_host_id_);
  if (!host)
    return;

  host->DestroyGpuMemoryBuffer(id, client_id, sync_point);
}

void BrowserGpuChannelHostFactory::OnGpuMemoryBufferCreated(
    uint32 request_id,
    const gfx::GpuMemoryBufferHandle& handle) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  CreateGpuMemoryBufferCallbackMap::iterator iter =
      create_gpu_memory_buffer_requests_.find(request_id);
  DCHECK(iter != create_gpu_memory_buffer_requests_.end());
  iter->second.Run(handle);
  create_gpu_memory_buffer_requests_.erase(iter);
}

}  // namespace content


text:
<!DOCTYPE html>

Read files placed here will contribute to a single assembly.

Paired read library

Read File 1 & 2

            Many paired read libraries are given as file pairs, with each file containing half of each read pair. Paired read files are expected to be sorted such that each read in a pair occurs in the same Nth position as its mate in their respective files. These files are specified as READ FILE 1 and READ FILE 2. For a given file pair, the selection of which file is READ 1 and which is READ 2 does not matter.

Advanced Parameters

File 1 Interleaved

            Some paired libaries are available in a single file where each read in a pair occurs in succession. To specify such a file set this parameter to 'True'.

Mean Insert Size

            This refers to the mean insert size between paired reads. If you have this information you may provide it. If not the assembly algorithm will make an attempt to determine this value.

Std. Insert Size

            This refers to the standard deviation of the insert size between paired reads. If you have this information you may provide it. If not the assembly algorithm will make an attempt to determine this value.

Mate Paired

            Defines the orientation of read pairs. Setting Mate Paired to true indicates that the sequencing direction of the two reads in each pair is outward facing.

Platform

            The sequencing platform used for each library.

            "infer": Infer sequencing platform from read files; "illumina": Illumina short reads; "pacbio": PacBio long reads; "nanopore": MinION long reads

Output Folder

The workspace folder where results will be placed.

Output Name

Name used to uniquely identify results.

Genome Group Name

Name used to create genome group with identified genomes.


text:
import numpy as np
from keras import applications
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.preprocessing import image
#import matplotlib.pyplot as plt
#import matplotlib.image as mpimg

# build the VGG16 network
model = applications.VGG16(weights='imagenet')
img = image.load_img('pexels-photo-280207.jpeg', target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
all_results = decode_predictions(preds)
for results in all_results:
    for result in results:
        print('Probability %0.2f%% => [%s]' % (100*result[2], result[1]))
        #result_text= 'Probability %0.2f%% => [%s]' % (100*result[2], result[1])
        #break
#plt.figure(num=1,figsize=(8, 6), dpi=80)
#plt.imshow(img)
#plt.text(120,100,result_text,horizontalalignment='center', verticalalignment='center',fontsize=16,color='black')
#plt.axis('off')
#plt.show()


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nspr_symbian_defs_h___
#define nspr_symbian_defs_h___

#include "prthread.h"

/*
 * Internal configuration macros
 */

#define _PR_SI_SYSNAME  "SYMBIAN"
#if defined(__WINS__)
#define _PR_SI_ARCHITECTURE "i386"
#elif defined(__arm__)
#define _PR_SI_ARCHITECTURE "arm"
#else
#error "Unknown CPU architecture"
#endif
#define PR_DLL_SUFFIX		".dll"

#undef	HAVE_STACK_GROWING_UP

#ifdef DYNAMIC_LIBRARY
#define HAVE_DLL
#define USE_DLFCN
#endif

#define _PR_STAT_HAS_ONLY_ST_ATIME
#define _PR_NO_LARGE_FILES
#define _PR_HAVE_SYSV_SEMAPHORES
#define PR_HAVE_SYSV_NAMED_SHARED_MEMORY

#ifndef _PR_PTHREADS
#error "Classic NSPR is not implemented"
#endif

extern void _MD_EarlyInit(void);

#define _MD_EARLY_INIT                  _MD_EarlyInit
#define _MD_FINAL_INIT                  _PR_UnixInit
#define _MD_INTERVAL_USE_GTOD

/* For writev() */
#include <sys/uio.h>

#endif /* nspr_symbian_defs_h___ */


text:
.class Lcom/android/server/desktopmode/UiManager$3;
.super Lcom/samsung/android/desktopmode/IDesktopModeUiServiceCallback$Stub;
.source "UiManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/desktopmode/UiManager;->showDialog(ILcom/android/server/desktopmode/UiManager$InternalDialogCallback;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/desktopmode/UiManager;

.field final synthetic val$dialogType:I

# direct methods
.method constructor <init>(Lcom/android/server/desktopmode/UiManager;I)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/desktopmode/UiManager$3;->this$0:Lcom/android/server/desktopmode/UiManager;

    iput p2, p0, Lcom/android/server/desktopmode/UiManager$3;->val$dialogType:I

    invoke-direct {p0}, Lcom/samsung/android/desktopmode/IDesktopModeUiServiceCallback$Stub;-><init>()V

    return-void
.end method

# virtual methods
.method public onClickButtonNegative()V
    .locals 0
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    return-void
.end method

.method public onClickButtonPositive()V
    .locals 3
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    iget-object v0, p0, Lcom/android/server/desktopmode/UiManager$3;->this$0:Lcom/android/server/desktopmode/UiManager;

    invoke-static {v0}, Lcom/android/server/desktopmode/UiManager;->-get4(Lcom/android/server/desktopmode/UiManager;)Landroid/content/ContentResolver;

    move-result-object v1

    iget v0, p0, Lcom/android/server/desktopmode/UiManager$3;->val$dialogType:I

    const/4 v2, 0x4

    if-ne v0, v2, :cond_0

    const-string/jumbo v0, "1st_mouse"

    :goto_0
    const/4 v2, 0x0

    invoke-static {v1, v0, v2}, Lcom/android/server/desktopmode/DesktopModeSettings;->setSettings(Landroid/content/ContentResolver;Ljava/lang/String;Z)V

    return-void

    :cond_0
    const-string/jumbo v0, "1st_dock"

    goto :goto_0
.end method

.method public onDismiss()V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    iget-object v0, p0, Lcom/android/server/desktopmode/UiManager$3;->this$0:Lcom/android/server/desktopmode/UiManager;

    invoke-static {v0}, Lcom/android/server/desktopmode/UiManager;->-wrap1(Lcom/android/server/desktopmode/UiManager;)V

    return-void
.end method

.method public onShow()V
    .locals 0
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    return-void
.end method