text:
// =========================================================================== //
//                                                                             //
// Copyright 2011 Jesse Doherty and McGill University.                         //
//                                                                             //
//   Licensed under the Apache License, Version 2.0 (the "License");           //
//   you may not use this file except in compliance with the License.          //
//   You may obtain a copy of the License at                                   //
//                                                                             //
//       http://www.apache.org/licenses/LICENSE-2.0                            //
//                                                                             //
//   Unless required by applicable law or agreed to in writing, software       //
//   distributed under the License is distributed on an "AS IS" BASIS,         //
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  //
//   See the License for the specific language governing permissions and       //
//  limitations under the License.                                             //
//                                                                             //
// =========================================================================== //

package nodecases.natlab;

import ast.*;

/**
 * A collection of cases to match each node type in the AST. This can
 * be used to create visitors.
 */
public interface NatlabNodeCaseHandler
{
    public void caseASTNode(ASTNode node);
    public void caseList(List node);
    public void caseProgram(Program node);
    public void caseBody(Body node);
    public void caseFunctionOrSignatureOrPropertyAccessOrStmt(FunctionOrSignatureOrPropertyAccessOrStmt node);
    public void caseHelpComment(HelpComment node);
    public void caseExpr(Expr node);
    public void caseCompilationUnits(CompilationUnits node);
    public void caseAttribute(Attribute node);
    public void caseSuperClass(SuperClass node);
    public void caseProperty(Property node);
    public void caseEvent(Event node);
    public void caseName(Name node);
    public void caseSwitchCaseBlock(SwitchCaseBlock node);
    public void caseDefaultCaseBlock(DefaultCaseBlock node);
    public void caseIfBlock(IfBlock node);
    public void caseElseBlock(ElseBlock node);
    public void caseRow(Row node);
    public void caseClassBody(ClassBody node);
    public void caseStmt(Stmt node);
    public void caseLValueExpr(LValueExpr node);
    public void caseLiteralExpr(LiteralExpr node);
    public void caseUnaryExpr(UnaryExpr node);
    public void caseBinaryExpr(BinaryExpr node);
    public void caseScript(Script node);
    public void caseFunctionList(FunctionList node);
    public void caseEmptyProgram(EmptyProgram node);
    public void caseClassDef(ClassDef node);
    public void caseProperties(Properties node);
    public void caseMethods(Methods node);
    public void caseSignature(Signature node);
    public void casePropertyAccess(PropertyAccess node);
    public void caseClassEvents(ClassEvents node);
    public void caseFunction(Function node);
    public void caseOneLineHelpComment(OneLineHelpComment node);
    public void caseMultiLineHelpComment(MultiLineHelpComment node);
    public void caseExprStmt(ExprStmt node);
    public void caseAssignStmt(AssignStmt node);
    public void caseGlobalStmt(GlobalStmt node);
    public void casePersistentStmt(PersistentStmt node);
    public void caseShellCommandStmt(ShellCommandStmt node);
    public void caseBreakStmt(BreakStmt node);
    public void caseContinueStmt(ContinueStmt node);
    public void caseReturnStmt(ReturnStmt node);
    public void caseEmptyStmt(EmptyStmt node);
    public void caseForStmt(ForStmt node);
    /**
     * A case for for loops that are known to loop over simple ranges.
     */
    public void caseRangeForStmt(ForStmt node);
    public void caseWhileStmt(WhileStmt node);
    public void caseTryStmt(TryStmt node);
    public void caseSwitchStmt(SwitchStmt node);
    public void caseIfStmt(IfStmt node);
    public void caseRangeExpr(RangeExpr node);
    public void caseColonExpr(ColonExpr node);
    public void caseEndExpr(EndExpr node);
    public void caseNameExpr(NameExpr node);
    public void caseParameterizedExpr(ParameterizedExpr node);
    public void caseCellIndexExpr(CellIndexExpr node);
    public void caseDotExpr(DotExpr node);
    public void caseMatrixExpr(MatrixExpr node);
    public void caseCellArrayExpr(CellArrayExpr node);
    public void caseSuperClassMethodExpr(SuperClassMethodExpr node);
    public void caseIntLiteralExpr(IntLiteralExpr node);
    public void caseFPLiteralExpr(FPLiteralExpr node);
    public void caseStringLiteralExpr(StringLiteralExpr node);
    public void caseUMinusExpr(UMinusExpr node);
    public void caseUPlusExpr(UPlusExpr node);
    public void caseNotExpr(NotExpr node);
    public void caseMTransposeExpr(MTransposeExpr node);
    public void caseArrayTransposeExpr(ArrayTransposeExpr node);
    public void casePlusExpr(PlusExpr node);
    public void caseMinusExpr(MinusExpr node);
    public void caseMTimesExpr(MTimesExpr node);
    public void caseMDivExpr(MDivExpr node);
    public void caseMLDivExpr(MLDivExpr node);
    public void caseMPowExpr(MPowExpr node);
    public void caseETimesExpr(ETimesExpr node);
    public void caseEDivExpr(EDivExpr node);
    public void caseELDivExpr(ELDivExpr node);
    public void caseEPowExpr(EPowExpr node);
    public void caseAndExpr(AndExpr node);
    public void caseOrExpr(OrExpr node);
    public void caseShortCircuitAndExpr(ShortCircuitAndExpr node);
    public void caseShortCircuitOrExpr(ShortCircuitOrExpr node);
    public void caseLTExpr(LTExpr node);
    public void caseGTExpr(GTExpr node);
    public void caseLEExpr(LEExpr node);
    public void caseGEExpr(GEExpr node);
    public void caseEQExpr(EQExpr node);
    public void caseNEExpr(NEExpr node);
    public void caseFunctionHandleExpr(FunctionHandleExpr node);
    public void caseLambdaExpr(LambdaExpr node);
    public void caseType(Type node);
    public void caseBaseType(BaseType node);
    public void casePrimitiveType(PrimitiveType node);
    public void caseIntType(IntType node);
    public void caseFloatType(FloatType node);
    public void caseShape(Shape node);
    public void caseRank(Rank node);
    public void caseExtents(Extents node);
    public void caseFieldEntry(FieldEntry node);
    public void caseUnionType(UnionType node);
    public void caseIntersectionType(IntersectionType node);
    public void caseArrowType(ArrowType node);
    public void caseArgTupleType(ArgTupleType node);
    public void caseUnitType(UnitType node);
    public void caseVarArgType(VarArgType node);
    public void caseTupleType(TupleType node);
    public void caseCellArrayType(CellArrayType node);
    public void caseMatrixType(MatrixType node);
    public void caseTypeVarType(TypeVarType node);
    public void caseHandleType(HandleType node);
    public void caseUnknownType(UnknownType node);
    public void caseStructType(StructType node);
    public void caseInt8(Int8 node);
    public void caseInt16(Int16 node);
    public void caseInt32(Int32 node);
    public void caseInt64(Int64 node);
    public void caseFloat32(Float32 node);
    public void caseFloat64(Float64 node);
    public void caseCharType(CharType node);
    public void caseBoolType(BoolType node);
    public void caseKnownExtentsShape(KnownExtentsShape node);
    public void caseKnownRank(KnownRank node);
    public void caseKnownExtents(KnownExtents node);
    public void caseCSLExpr(CSLExpr node);
    public void caseEndCallExpr(EndCallExpr node);
    public void caseCheckScalarStmt(CheckScalarStmt node);
}


text:
from django.conf.urls.defaults import *
#from django.contrib.sites.models import Site
from django.utils.translation import ugettext as _
# Methodmint
from methods.models import Method
from methods.forms import MethodForm
from methods.feeds import *
# External
#from haystack.forms import SearchForm
#from haystack.views import SearchView
#from haystack.query import SearchQuerySet
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^$', 'methods.views.method_list', {
                'template_name':'methods/method_list.html',
                'paginate_by':20,
            },
            name='method-list'),

    # Methods
    url(r'^(?P<method_id>\d+)/$', 'methods.views.method_noslug', name='method' ),
    url(r'^(?P<method_id>\d+)/edit/$', 'methods.views.method_edit', name='method-edit' ),

    url(r'^rss/$', LatestMethodsFeed(), name='method-rss-latest'),

#    url(r'^create/$', 'methods.views.method_create', name='method-create' ),
#    url(r'^request/$', 'methods.views.method_request', name='method-request' ),

    # Revisions
#   url(r'^(?P<method_id>\d+)/history/$', 'methods.views.method_history', name='method-history' ),

    # Searching/finding
    url(r'^tagged/(?P<slug>[^/]+)/$', 'core.views.objects_tagged', {'Model': Method, 'template_name':'methods/method_list.html',}, name='method-tagged',),

#    url(r'^search/$', 'methods.views.search', name='method-search'),

#    url(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$', 'voting.views.vote_on_object', {
#        'model': Method,
#        'template_object_name': 'method',
#        'allow_xmlhttprequest': 'true',
#        },
#        name='method-voting'),

#    url(r'^ajax/parse-duration/$', 'methods.views.parse_duration_ajax' ),

    # this is potentially buggy if the slug is anything listed above, oh dear
    url(r'^(?P<method_id>\d+)/(?P<method_slug>.+)/$', 'methods.views.method', name='method' ),

)

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <title>mySynth</title>

    <input id="play" onclick="toggleSound(this)" type="button" value="Play random sound" />

    Highpass:
    <input id="highpass" onchange="sliderChange(this)" type="range" min="0" max="1024" step="1" value="512" />
    Pan:
    <input id="pan" onchange="sliderChange(this)" type="range" min="-3" max="3" step="0.01" value="0" />
    Volume:
    <input id="volume" onchange="sliderChange(this)" type="range" min="0" max="1" step="0.01" value="1" />

    <canvas width="300" height="200"></canvas>


text:
package org.elasticsearch.index.mapper;

import org.elasticsearch.common.geo.GeometryFormat;
import org.elasticsearch.common.geo.GeometryParser;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.support.MapXContentParser;
import org.elasticsearch.geometry.Geometry;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.text.ParseException;
import java.util.Collections;

public class GeoShapeParser extends AbstractGeometryFieldMapper.Parser<Geometry> {
    private final GeometryParser geometryParser;

    public GeoShapeParser(GeometryParser geometryParser) {
        this.geometryParser = geometryParser;
    }

    @Override
    public Geometry parse(XContentParser parser, AbstractGeometryFieldMapper mapper) throws IOException, ParseException {
        return geometryParser.parse(parser);
    }

    @Override
    public Object format(Geometry value, String format) {
        return geometryParser.geometryFormat(format).toXContentAsObject(value);
    }

    @Override
    public Object parseAndFormatObject(Object value, AbstractGeometryFieldMapper mapper, String format) {
        try (XContentParser parser = new MapXContentParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE,
            Collections.singletonMap("dummy_field", value), XContentType.JSON)) {
            parser.nextToken(); // start object
            parser.nextToken(); // field name
            parser.nextToken(); // field value

            GeometryFormat<Geometry> geometryFormat = geometryParser.geometryFormat(parser);
            if (geometryFormat.name().equals(format)) {
                return value;
            }

            Geometry geometry = geometryFormat.fromXContent(parser);
            return format(geometry, format);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
namespace blink {

namespace {

// Token payloads can be at most 4KB in size, as a guard against trying to parse
// excessively large tokens (see crbug.com/802377). The origin is the only part
// of the payload that is user-supplied. The 4KB payload limit allows for the
// origin to be ~3900 chars. In some cases, 2KB is suggested as the practical
// limit for URLs, e.g.:
// https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
// This means tokens can contain origins that are nearly twice as long as any
// expected to be seen in the wild.
const size_t kMaxPayloadSize = 4096;
// Encoded tokens can be at most 6KB in size. Based on the 4KB payload limit,
// this allows for the payload, signature, and other format bits, plus the
// Base64 encoding overhead (~4/3 of the input).
const size_t kMaxTokenSize = 6144;

// Version is a 1-byte field at offset 0.
const size_t kVersionOffset = 0;
const size_t kVersionSize = 1;

// These constants define the Version 2 field sizes and offsets.
const size_t kSignatureOffset = kVersionOffset + kVersionSize;
const size_t kSignatureSize = 64;
const size_t kPayloadLengthOffset = kSignatureOffset + kSignatureSize;
const size_t kPayloadLengthSize = 4;
const size_t kPayloadOffset = kPayloadLengthOffset + kPayloadLengthSize;

// Version 3 introduced support to match tokens against third party origins (see
// design doc
// https://docs.google.com/document/d/1xALH9W7rWmX0FpjudhDeS2TNTEOXuPn4Tlc9VmuPdHA
// for more details).
const uint8_t kVersion3 = 3;
// Version 2 is also currently supported. Version 1 was
// introduced in Chrome M50, and removed in M51. There were no experiments
// enabled in the stable M50 release which would have used those tokens.
const uint8_t kVersion2 = 2;

const char* kUsageSubset = "subset";

}  // namespace

TrialToken::~TrialToken() = default;

// static
std::unique_ptr<TrialToken> TrialToken::From(
    base::StringPiece token_text,
    const OriginTrialPublicKey& public_key,
    OriginTrialTokenStatus* out_status) {
  DCHECK(out_status);
  std::string token_payload;
  std::string token_signature;
  uint8_t token_version;
  *out_status = Extract(token_text, public_key, &token_payload,
                        &token_signature, &token_version);
  if (*out_status != OriginTrialTokenStatus::kSuccess) {
    DVLOG(2) << "Malformed origin trial token found (unable to extract)";
    return nullptr;
  }
  std::unique_ptr<TrialToken> token = Parse(token_payload, token_version);
  if (token) {
    token->signature_ = token_signature;
    *out_status = OriginTrialTokenStatus::kSuccess;
    DVLOG(2) << "Well-formed origin trial token found for feature "
             << token->feature_name();
  } else {
    DVLOG(2) << "Malformed origin trial token found (unable to parse)";
    *out_status = OriginTrialTokenStatus::kMalformed;
  }
  return token;
}

OriginTrialTokenStatus TrialToken::IsValid(const url::Origin& origin,
                                           const base::Time& now) const {
  // The order of these checks is intentional. For example, will only report a
  // token as expired if it is valid for the origin.
  if (!ValidateOrigin(origin)) {
    DVLOG(2) << "Origin trial token from different origin";
    return OriginTrialTokenStatus::kWrongOrigin;
  }
  if (!ValidateDate(now)) {
    DVLOG(2) << "Origin trial token expired";
    return OriginTrialTokenStatus::kExpired;
  }
  return OriginTrialTokenStatus::kSuccess;
}

// static
OriginTrialTokenStatus TrialToken::Extract(
    base::StringPiece token_text,
    const OriginTrialPublicKey& public_key,
    std::string* out_token_payload,
    std::string* out_token_signature,
    uint8_t* out_token_version) {
  if (token_text.empty()) {
    return OriginTrialTokenStatus::kMalformed;
  }

  // Protect against attempting to extract arbitrarily large tokens.
  // See crbug.com/802377.
  if (token_text.length() > kMaxTokenSize) {
    return OriginTrialTokenStatus::kMalformed;
  }

  // Token is base64-encoded; decode first.
  std::string token_contents;
  if (!base::Base64Decode(token_text, &token_contents)) {
    return OriginTrialTokenStatus::kMalformed;
  }

  // Only version 2 and 3 currently supported.
  if (token_contents.length() < (kVersionOffset + kVersionSize)) {
    return OriginTrialTokenStatus::kMalformed;
  }
  uint8_t version = token_contents[kVersionOffset];
  if (version != kVersion2 && version != kVersion3) {
    return OriginTrialTokenStatus::kWrongVersion;
  }

  // Token must be large enough to contain a version, signature, and payload
  // length.
  if (token_contents.length() < (kPayloadLengthOffset + kPayloadLengthSize)) {
    return OriginTrialTokenStatus::kMalformed;
  }

  // Extract the length of the signed data (Big-endian).
  uint32_t payload_length;
  base::ReadBigEndian(
      reinterpret_cast<const uint8_t*>(&(token_contents[kPayloadLengthOffset])),
      &payload_length);

  // Validate that the stated length matches the actual payload length.
  if (payload_length != token_contents.length() - kPayloadOffset) {
    return OriginTrialTokenStatus::kMalformed;
  }

  // Extract the version-specific contents of the token.
  const char* token_bytes = token_contents.data();
  base::StringPiece version_piece(token_bytes + kVersionOffset, kVersionSize);
  base::StringPiece signature(token_bytes + kSignatureOffset, kSignatureSize);
  base::StringPiece payload_piece(token_bytes + kPayloadLengthOffset,
                                  kPayloadLengthSize + payload_length);

  // The data which is covered by the signature is (version + length + payload).
  std::string signed_data = base::StrCat({version_piece, payload_piece});

  // Validate the signature on the data before proceeding.
  if (!TrialToken::ValidateSignature(signature, signed_data, public_key)) {
    return OriginTrialTokenStatus::kInvalidSignature;
  }

  // Return the payload and signature, as new strings.
  *out_token_version = version;
  *out_token_payload = token_contents.substr(kPayloadOffset, payload_length);
  *out_token_signature = std::string(signature);
  return OriginTrialTokenStatus::kSuccess;
}

// static
std::unique_ptr<TrialToken> TrialToken::Parse(const std::string& token_payload,
                                              const uint8_t version) {
  // Protect against attempting to parse arbitrarily large tokens. This check is
  // required here because the fuzzer calls Parse() directly, bypassing the size
  // check in Extract().
  // See crbug.com/802377.
  if (token_payload.length() > kMaxPayloadSize) {
    return nullptr;
  }

  absl::optional<base::Value> datadict = base::JSONReader::Read(token_payload);
  if (!datadict || !datadict->is_dict()) {
    return nullptr;
  }

  // Ensure that the origin is a valid (non-opaque) origin URL.
  std::string* origin_string = datadict->FindStringKey("origin");
  if (!origin_string) {
    return nullptr;
  }
  url::Origin origin = url::Origin::Create(GURL(*origin_string));
  if (origin.opaque()) {
    return nullptr;
  }

  // The |isSubdomain| flag is optional. If found, ensure it is a valid boolean.
  bool is_subdomain = false;
  base::Value* is_subdomain_value = datadict->FindKey("isSubdomain");
  if (is_subdomain_value) {
    if (!is_subdomain_value->is_bool()) {
      return nullptr;
    }
    is_subdomain = is_subdomain_value->GetBool();
  }

  // Ensure that the feature name is a valid string.
  std::string* feature_name = datadict->FindStringKey("feature");
  if (!feature_name || feature_name->empty()) {
    return nullptr;
  }

  // Ensure that the expiry timestamp is a valid (positive) integer.
  int expiry_timestamp = datadict->FindIntKey("expiry").value_or(0);
  if (expiry_timestamp <= 0) {
    return nullptr;
  }

  // Initialize optional version 3 fields to default values.
  bool is_third_party = false;
  UsageRestriction usage = UsageRestriction::kNone;

  if (version == kVersion3) {
    // The |isThirdParty| flag is optional. If found, ensure it is a valid
    // boolean.
    base::Value* is_third_party_value = datadict->FindKey("isThirdParty");
    if (is_third_party_value) {
      if (!is_third_party_value->is_bool()) {
        return nullptr;
      }
      is_third_party = is_third_party_value->GetBool();
    }

    // The |usage| field is optional. If found, ensure its value is either empty
    // or "subset".
    std::string* usage_value = datadict->FindStringKey("usage");
    if (usage_value) {
      if (usage_value->empty()) {
        usage = UsageRestriction::kNone;
      } else if (*usage_value == kUsageSubset) {
        usage = UsageRestriction::kSubset;
      } else {
        return nullptr;
      }
    }
  }

  return base::WrapUnique(new TrialToken(
      origin, is_subdomain, *feature_name,
      base::Time::FromDoubleT(expiry_timestamp), is_third_party, usage));
}

bool TrialToken::ValidateOrigin(const url::Origin& origin) const {
  if (match_subdomains_) {
    return origin.scheme() == origin_.scheme() &&
           origin.DomainIs(origin_.host()) && origin.port() == origin_.port();
  }
  return origin == origin_;
}

bool TrialToken::ValidateFeatureName(base::StringPiece feature_name) const {
  return feature_name == feature_name_;
}

bool TrialToken::ValidateDate(const base::Time& now) const {
  return expiry_time_ > now;
}

// static
bool TrialToken::ValidateSignature(base::StringPiece signature,
                                   const std::string& data,
                                   const OriginTrialPublicKey& public_key) {
  // Signature must be 64 bytes long.
  if (signature.length() != 64) {
    return false;
  }

  int result = ED25519_verify(
      reinterpret_cast<const uint8_t*>(data.data()), data.length(),
      reinterpret_cast<const uint8_t*>(signature.data()), public_key.data());
  return (result != 0);
}

TrialToken::TrialToken(const url::Origin& origin,
                       bool match_subdomains,
                       const std::string& feature_name,
                       base::Time expiry_time,
                       bool is_third_party,
                       UsageRestriction usage_restriction)
    : origin_(origin),
      match_subdomains_(match_subdomains),
      feature_name_(feature_name),
      expiry_time_(expiry_time),
      is_third_party_(is_third_party),
      usage_restriction_(usage_restriction) {}

// static
std::unique_ptr<TrialToken> TrialToken::CreateTrialTokenForTesting(
    const url::Origin& origin,
    bool match_subdomains,
    const std::string& feature_name,
    base::Time expiry_time,
    bool is_third_party,
    UsageRestriction usage_restriction) {
  return base::WrapUnique(new TrialToken(origin, match_subdomains, feature_name,
                                         expiry_time, is_third_party,
                                         usage_restriction));
}

}  // namespace blink


text:
/** @file
    @brief Implementation

    @date 2017

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2017 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include "Resources.h"

// Library/third-party includes
// - none

// Standard includes
// - none

using namespace vr;

Resources::Resources() : m_logger(osvr::util::log::make_logger("Resources")) {}

uint32_t Resources::LoadSharedResource(const char *pchResourceName,
                                       char *pchBuffer, uint32_t unBufferLen) {
    m_logger->debug("LoadSharedResource(") << pchResourceName << ")";
    return 0;
}
uint32_t Resources::GetResourceFullPath(const char *pchResourceName,
                                        const char *pchResourceTypeDirectory,
                                        char *pchPathBuffer,
                                        uint32_t unBufferLen) {
    m_logger->debug("GetResourceFullPath(")
        << pchResourceName << ", " << pchResourceTypeDirectory << ")";
    return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Tao.OpenGl;
using Gaming.Graphics;
using Gaming.Core;

namespace Gaming.Graphics
{
    class ScreenGL
    {
        private static ScreenGL screenImage = new ScreenGL();

        protected class Renderer2DOpenGL : Renderer2D
        {
            BufferedImage m_LineImageCache;
            //
            public Renderer2DOpenGL()
            {

            }

            private void PushOrthoProjection()
            {
                Gl.glPushAttrib(Gl.GL_TRANSFORM_BIT);
                int[] viewport = new int[4];
                Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
                Gl.glMatrixMode(Gl.GL_PROJECTION);
                Gl.glPushMatrix();
                Gl.glLoadIdentity();
                Gl.glOrtho(viewport[0], viewport[2], viewport[1], viewport[3], 0, 1);
                Gl.glPopAttrib();
                viewport = null;
            }

            private void PopOrthoProjection()
            {
                Gl.glPushAttrib(Gl.GL_TRANSFORM_BIT);
                Gl.glMatrixMode(Gl.GL_PROJECTION);
                Gl.glPopMatrix();
                Gl.glPopAttrib();
            }

            public override void DrawLine(Vector2Df Start, Vector2Df End)
            {
                if(m_LineImageCache == null)
                {
                	//m_LineImageCache = new BufferedImage(4, 1, BufferedImage.PixelType.INT_ARGB);
                	//renderer.FillRect(1, 0, 1, 1);
                	m_LineImageCache = new BufferedImage(4, 4, BufferedImage.PixelType.INT_ARGB);
                	Renderer2D renderer = m_LineImageCache.GetRenderer2D;
                    renderer.Color.AlphaI = 0;
                    renderer.FillRect(0, 0, 4, 4);
                    renderer.Color.AlphaI = 255;
                    renderer.FillRect(1, 2, 1, 2);
#if false // Fill in the rest of the pixels for testing
                	renderer.Color.RedI = 0;
                	renderer.FillRect(0, 0, 4, 1);
                	renderer.FillRect(3, 0, 1, 4);
                	renderer.Color.BlueI = 0;
                	renderer.FillRect(0, 1, 1, 3);
                	renderer.FillRect(0, 1, 3, 1);
                	renderer.FillRect(2, 1, 1, 3);
#endif
                }

                ImageGLDisplayListPlugin GLBuffer = ImageGLDisplayListPlugin.GetImageGLDisplayListPlugin(m_LineImageCache);
                Gl.glEnable(Gl.GL_TEXTURE_2D);
                Gl.glEnable(Gl.GL_BLEND);
                Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
                Gl.glColor4f(m_Color.RedF, m_Color.GreenF, m_Color.BlueF, m_Color.AlphaF);

                Vector2Df Normal = (End - Start);
                Vector2Df PerpendicularNormal = Normal.GetPerpendicularNormal();
                float Width = 1;
                Vector2Df OffsetPos = PerpendicularNormal * Width;
                Vector2Df OffsetNeg = PerpendicularNormal * -(Width + 1);

                PushOrthoProjection();

                Gl.glBindTexture(Gl.GL_TEXTURE_2D, GLBuffer.GLTextureHandle);

                Gl.glBegin(Gl.GL_QUADS);
#if true
                Gl.glTexCoord2d(0, .75); Gl.glVertex2f(Start.x + OffsetPos.x, Start.y + OffsetPos.y);
                Gl.glTexCoord2d(0, 1); Gl.glVertex2f(End.x + OffsetPos.x, End.y + OffsetPos.y);
                Gl.glTexCoord2d(.75, 1); Gl.glVertex2f(End.x + OffsetNeg.x, End.y + OffsetNeg.y);
                Gl.glTexCoord2d(.75, .5); Gl.glVertex2f(Start.x + OffsetNeg.x, Start.y + OffsetNeg.y);
#else
                // draw the main line (without the tips)
                Gl.glTexCoord2d(0, .75); Gl.glVertex2f(Start.x + OffsetPos.x + Normal.x, Start.y + OffsetPos.y + Normal.y);
                Gl.glTexCoord2d(0, 1); Gl.glVertex2f(End.x + OffsetPos.x - Normal.x, End.y + OffsetPos.y - Normal.y);
                Gl.glTexCoord2d(.75, 1); Gl.glVertex2f(End.x + OffsetNeg.x - Normal.x, End.y + OffsetNeg.y - Normal.y);
                Gl.glTexCoord2d(.75, .5); Gl.glVertex2f(Start.x + OffsetNeg.x + Normal.x, Start.y + OffsetNeg.y + Normal.y);

                // draw the ending tip anti-aliased
                Gl.glTexCoord2d(0, 1); Gl.glVertex2f(End.x + OffsetPos.x - Normal.x, End.y + OffsetPos.y - Normal.y);
                Gl.glTexCoord2d(0, .25); Gl.glVertex2f(End.x + OffsetPos.x, End.y + OffsetPos.y);
                Gl.glTexCoord2d(.75, .25); Gl.glVertex2f(End.x + OffsetNeg.x, End.y + OffsetNeg.y);
                Gl.glTexCoord2d(.75, 1); Gl.glVertex2f(End.x + OffsetNeg.x - Normal.x, End.y + OffsetNeg.y - Normal.y);

                // draw the starting tip anti-aliased
                Gl.glTexCoord2d(0, .25); Gl.glVertex2f(Start.x + OffsetPos.x, Start.y + OffsetPos.y);
                Gl.glTexCoord2d(0, 1); Gl.glVertex2f(Start.x + OffsetPos.x + Normal.x, Start.y + OffsetPos.y + Normal.y);
                Gl.glTexCoord2d(.75, 1); Gl.glVertex2f(Start.x + OffsetNeg.x + Normal.x, Start.y + OffsetNeg.y + Normal.y);
                Gl.glTexCoord2d(.75, .25); Gl.glVertex2f(Start.x + OffsetNeg.x, Start.y + OffsetNeg.y);
#endif
                Gl.glColor4f(1, 1, 1, 1);
                Gl.glEnd();

                PopOrthoProjection();
            }

            public override void FillRect(float x, float y, float width, float height)
            {
                PushOrthoProjection();
                Gl.glDisable(Gl.GL_TEXTURE_2D);
                Gl.glEnable(Gl.GL_BLEND);
                Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
                Gl.glColor4f(m_Color.RedF, m_Color.GreenF, m_Color.BlueF, m_Color.AlphaF);

                Gl.glBegin(Gl.GL_QUADS);
                Gl.glVertex3d(x+width, y+height, 0);
                Gl.glVertex3d(x, y+height, 0);
                Gl.glVertex3d(x, y, 0);
                Gl.glVertex3d(x+width, y, 0);
                Gl.glEnd();

                Gl.glColor4f(1, 1, 1, 1);
                PopOrthoProjection();
            }

            public override void DrawString(String stringToPrint, float x, float y)
            {
                if (stringToPrint == null)
                {
                    return;
                }

                //Prepare openGL for rendering the font characters
                PushOrthoProjection();
                Gl.glPushAttrib(Gl.GL_LIST_BIT | Gl.GL_CURRENT_BIT | Gl.GL_ENABLE_BIT | Gl.GL_TRANSFORM_BIT);
                Gl.glMatrixMode(Gl.GL_MODELVIEW);
                Gl.glDisable(Gl.GL_LIGHTING);
                Gl.glEnable(Gl.GL_TEXTURE_2D);
                Gl.glDisable(Gl.GL_DEPTH_TEST);
                Gl.glEnable(Gl.GL_BLEND);
                Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
                float[] modelview_matrix = new float[16];
                Gl.glGetFloatv(Gl.GL_MODELVIEW_MATRIX, modelview_matrix);
                Gl.glPushMatrix();
                Gl.glLoadIdentity();
                Gl.glTranslatef(x, y, 0);
                Gl.glMultMatrixf(modelview_matrix);

                Gl.glColor4f(m_Color.RedF, m_Color.GreenF, m_Color.BlueF, m_Color.AlphaF);
                for (int i = 0; i < stringToPrint.Length; i++)
                {
                    int unicodeCharacter = stringToPrint[i];
                    Image characterImage = CurrentFont.GetCharacterImage(unicodeCharacter);
                    ImageGLDisplayListPlugin GLDisplayForImage = ImageGLDisplayListPlugin.GetImageGLDisplayListPlugin(characterImage);

                    Gl.glTranslatef(CurrentFont.GetCharacterLeftOffset(unicodeCharacter), 0, 0);
                    Gl.glPushMatrix();
                    Gl.glTranslatef(0, CurrentFont.GetCharacterTopOffset(unicodeCharacter) - characterImage.Height, 0);

                    Gl.glCallList(GLDisplayForImage.GLDisplayList);

                    Gl.glPopMatrix();
                    //Advance for the next character
                    Gl.glTranslatef(characterImage.Width, 0, 0);
                }
                Gl.glColor4f(1, 1, 1, 1);

                //Restore openGL state
                Gl.glPopMatrix();
                Gl.glPopAttrib();
                PopOrthoProjection();
            }
        };

        private ScreenGL() // you have to call the instance of this
        {

        }

        static public ScreenGL Instance()
        {
            return screenImage;
        }

        internal static int SmallestHardwareCompatibleTextureSize(int a)
        {
            // TODO: check if the hardware supports non-power 2 textures.
            int rval = 1;
            while (rval < a)
            {
                rval <<= 1;
            }

            return rval;
        }

        public override Renderer2D GetRenderer2D
        {
            get
            {
                return new Renderer2DOpenGL();
            }
        }

        public override int Width
        {
            get
            {
                int[] viewport = new int[4];
                Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
                if (viewport[0] != 0 || viewport[1] != 0)
                {
                    throw new Exception("The viewport x and y are not 0.");
                }
                return viewport[2];
            }
        }

        public override int Height
        {
            get
            {
                int[] viewport = new int[4];
                Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
                if(viewport[0] != 0 || viewport[1] != 0)
                {
                    throw new Exception("The viewport x and y are not 0.");
                }
                return viewport[3];
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
    <settings pass="windowsPE">
        <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
            <RunSynchronous>
                <RunSynchronousCommand wcm:action="add">
                    <Description>Start DaRT</Description>
                    <Order>1</Order>
                    <Path>wscript.exe X:\Deploy\Scripts\EnableDart.wsf /EventService:http://cm01:9800 /_SMSTSCurrentActionName:"Booted into WinPE"</Path>
                </RunSynchronousCommand>
            </RunSynchronous>
        </component>
    </settings>
</unattend>


text:
module SharingRelationshipInvitations
  module InstanceMethods
    module ReinstateCancelledDeclinedRelationshipInvitiationAsSender

      def reinstate_cancelled_declined_relationship_invitation_as_sender
        @relationship_invitation.status = 'declined'
        @relationship_invitation.save!
      end

    end
  end
end


text:
<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

		        Teaser Image

		    {% if site.logo %}
		      {{ site.title }}
		    {% endif %}

{{ site.title }}

{{ site.description }}

		    	  ·
		    	  ·
		    	  ·
 		    	  ·
		      	  ·
		      	Project Updates  ·
		      	Hack Education  ·
		      	About

        	{{ content }}

    {% include footer.html %}
    {% include javascripts.html %}


text: package goodbye


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="bower_components/angular/angular-csp.css">

Curso angular

{{"Hola Mundo"}}


text:
//
//  Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//   - May you do good and not evil.                                         -
//   - May you find forgiveness for yourself and forgive others.             -
//   - May you share freely, never taking more than you give.                -
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

using System;
using SharpNL.Tokenize;
using SharpNL.Utility;

namespace SharpNL.Formats.Ptb {
    /// <summary>
    /// Represents a Penn Treebank <see cref="TokenSample"/> stream. This class cannot be inherited.
    /// </summary>
    public sealed class PtbTokenSampleStream : PtbSampleStream<TokenSample> {

        private readonly IDetokenizer detokenizer;

        #region + Constructors .

        /// <summary>
        /// Initializes a new instance of the <see cref="PtbSampleStream{T}" /> using a specified Penn Treebank stream.
        /// </summary>
        /// <param name="stream">The Penn Treebank stream.</param>
        /// <param name="detokenizer">The detokenizer.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="detokenizer"/>
        /// or
        /// <paramref name="stream"/>
        /// </exception>
        public PtbTokenSampleStream(PtbStreamReader stream, IDetokenizer detokenizer) : base(stream) {
            if (detokenizer == null)
                throw new ArgumentNullException(nameof(detokenizer));

            this.detokenizer = detokenizer;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PtbTokenSampleStream"/> using a <see cref="T:IObjectStream{string}"/>.
        /// The function tags will be ignored using this constructor.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="lineStream">The line stream.</param>
        /// <param name="detokenizer">The detokenizer.</param>
        public PtbTokenSampleStream(string language, IObjectStream<string> lineStream, IDetokenizer detokenizer)
            : this(language, lineStream, detokenizer, null) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="PtbTokenSampleStream"/> using a <see cref="T:IObjectStream{string}"/> and a evaluation monitor.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="lineStream">The line stream.</param>
        /// <param name="detokenizer">The detokenizer.</param>
        /// <param name="monitor">The monitor.</param>
        public PtbTokenSampleStream(string language, IObjectStream<string> lineStream, IDetokenizer detokenizer, Monitor monitor)
            : base(new PtbStreamReader(language, lineStream, false, monitor)) {
            if (detokenizer == null)
                throw new ArgumentNullException(nameof(detokenizer));

            this.detokenizer = detokenizer;
        }
        #endregion

        #region . Read .
        /// <summary>
        /// Returns the next <see cref="TokenSample"/> object. Calling this method repeatedly until it returns,
        /// null will return each object from the underlying source exactly once.
        /// </summary>
        /// <returns>
        /// The next <see cref="TokenSample"/> object or <c>null</c> to signal that the stream is exhausted.
        /// </returns>
        public override TokenSample Read() {
            var node = Stream.Read();
            return node != null
                ? new TokenSample(detokenizer, node.Tokens)
                : null;
        }
        #endregion

    }
}


text:
package org.camunda.bpm.engine.test.history;

import static org.junit.Assert.assertEquals;

import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.util.PluggableProcessEngineTest;
import org.junit.Test;

/**
 * @author Frederik Heremans
 */
@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_ACTIVITY)
public class HistoricTaskInstanceUpdateTest extends PluggableProcessEngineTest {

  @Deployment
  @Test
  public void testHistoricTaskInstanceUpdate() {
    runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest").getId();

    Task task = taskService.createTaskQuery().singleResult();

    // Update and save the task's fields before it is finished
    task.setPriority(12345);
    task.setDescription("Updated description");
    task.setName("Updated name");
    task.setAssignee("gonzo");
    taskService.saveTask(task);

    taskService.complete(task.getId());
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().count());

    HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().singleResult();
    assertEquals("Updated name", historicTaskInstance.getName());
    assertEquals("Updated description", historicTaskInstance.getDescription());
    assertEquals("gonzo", historicTaskInstance.getAssignee());
    assertEquals("task", historicTaskInstance.getTaskDefinitionKey());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace KelpNet.Tools
{
    public class LabeledDataMaker
    {
        // TargetFolder
        // ├ CategoryA
        // │ ├ ImageA1.jpg
        // │ ├ ImageA2.jpg
        // │ └ ImageA3.jpg
        // ├ CategoryB
        // │ ├ ImageB1.jpg
        // │ ├ ImageB2.jpg
        // │ ├ ImageB3.jpg
        // │ └ ImageB4.jpg
        // └ CategoryC
        //    ├ ImageC1.jpg
        //    └ ImageC1.jpg

        public static LabeledDataSet<T> MakeFromFolder<T>(string foldersPath, int width = -1, int height = -1, bool eraseAlphaCh = true, bool makeValidData = false, bool makeTrainIndex = true) where T : unmanaged, IComparable<T>
        {
            List<T[]> data = new List<T[]>();
            List<int> dataLabel = new List<int>();
            List<string> labelName = new List<string>();

            string[] folders = Directory.GetDirectories(foldersPath);

            int bitcount = eraseAlphaCh ? 3 : -1;

            for (int i = 0; i < folders.Length; i++)
            {
                //クラス名称を保存
                labelName.Add(Path.GetFileName(folders[i]));

                string[] files = Directory.GetFiles(folders[i]);

                for (int j = 0; j < files.Length; j++)
                {
                    Bitmap baseBmp = new Bitmap(files[j]);

                    PixelFormat pixelFormat = baseBmp.PixelFormat;

                    //アルファチャンネルを削除する
                    if (eraseAlphaCh && Image.GetPixelFormatSize(baseBmp.PixelFormat) == 32)
                    {
                        pixelFormat = PixelFormat.Format24bppRgb;
                    }

                    if (width == -1)
                    {
                        width = baseBmp.Width;
                    }

                    if (height == -1)
                    {
                        height = baseBmp.Height;
                    }

                    //dataとdatalabelに水増ししつつ値をセット
                    SetAugmentatedBmp(data, dataLabel, baseBmp, width, height, pixelFormat, i);
                }
            }

            return new LabeledDataSet<T>(data.ToArray(), dataLabel.ToArray(), new[] { bitcount, height, width }, labelName.ToArray(), makeValidData, makeTrainIndex, 9);
        }

        static void SetResizedBmp<T>(List<T[]> data, List<int> label, Bitmap baseBmp, int width, int height, PixelFormat pixelFormat, int labelIndex) where T : unmanaged, IComparable<T>
        {
            Bitmap resultBmp = new Bitmap(width, height, pixelFormat);
            Graphics g = Graphics.FromImage(resultBmp);
            g.InterpolationMode = InterpolationMode.Bilinear;
            g.DrawImage(baseBmp, 0, 0, width, height);
            g.Dispose();

            data.Add(BitmapConverter.Image2RealArray<T>(resultBmp));
            label.Add(labelIndex);
        }

        //SizeRatioは100分率で指定 10を指定した場合10%縮めた範囲を9回切り抜いて出力する
        public static void SetAugmentatedBmp<T>(List<T[]> data, List<int> label, Bitmap baseBmp, int width, int height, PixelFormat pixelFormat, int labelIndex, int sizeRatio = 10) where T : unmanaged, IComparable<T>
        {
            Bitmap resultBmp = new Bitmap(width, height, pixelFormat);
            Rectangle desRect = new Rectangle(0, 0, width, height);

            int widthOffset = baseBmp.Width / sizeRatio;
            int heightOffset = baseBmp.Height / sizeRatio;

            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    Rectangle srcRect = new Rectangle(x * widthOffset / 2, y * heightOffset / 2, baseBmp.Width - widthOffset, baseBmp.Height - heightOffset);

                    Graphics g = Graphics.FromImage(resultBmp);
                    g.InterpolationMode = InterpolationMode.Bilinear;
                    g.DrawImage(baseBmp, desRect, srcRect, GraphicsUnit.Pixel);
                    g.Dispose();

                    data.Add(BitmapConverter.Image2RealArray<T>(resultBmp));
                    label.Add(labelIndex);
                }
            }
        }

        static void SetRotateImage<T>(List<T[]> data, List<int> label, Bitmap baseBmp, int labelIndex) where T : unmanaged, IComparable<T>
        {
            //90
            baseBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
            data.Add(BitmapConverter.Image2RealArray<T>(baseBmp));
            label.Add(labelIndex);

            //180
            baseBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
            data.Add(BitmapConverter.Image2RealArray<T>(baseBmp));
            label.Add(labelIndex);

            //270
            baseBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
            data.Add(BitmapConverter.Image2RealArray<T>(baseBmp));
            label.Add(labelIndex);

            //もとに戻す
            baseBmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
        }
    }
}


text:
package com.pivotal.gemfirexd.internal.impl.store.raw.data;

import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ClosedChannelException;

import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.store.raw.ContainerKey;
import com.pivotal.gemfirexd.internal.io.StorageRandomAccessFile;

/**
 * RAFContainer4 overrides a few methods in RAFContainer in an attempt to use
 * FileChannel from Java 1.4's New IO framework to issue multiple IO operations
 * to the same file concurrently instead of strictly serializing IO operations
 * using a mutex on the container object.
 *

 * Note that our requests for multiple concurrent IOs may be serialized further
 * down in the IO stack - this is entirely up to the JVM and OS. However, at
 * least in Linux on Sun's 1.4.2_09 JVM we see the desired behavior:
 * The FileChannel.read/write(ByteBuffer buf, long position) calls map to
 * pread/pwrite system calls, which enable efficient IO to the same file
 * descriptor by multiple threads.
 *

 * This whole class should be merged back into RAFContainer when Derby
 * officially stops supporting Java 1.3.
 *

 * Significant behavior changes from RAFContainer:
 *

 *
 Multiple concurrent IOs permitted.
 *
 State changes to the container (create, open, close) can now happen while
 *      IO is in progress due to the lack of locking. Closing a container while
 *      IO is in progress will cause IOExceptions in the thread calling readPage
 *      or writePage. If this happens something is probably amiss anyway.
 *      The iosInProgress variable is used in an attempt to detect this should it
 *      happen while running a debug build.
 *

 *
 * @see java.nio.channels.FileChannel
 */
class RAFContainer4 extends RAFContainer {

    /**
     * This channel will be retrieved from RAFContainer's fileData
     * member when fileData is set. We wrap a couple of RAFContainer's methods
     * to accomplish this.
     */
    private FileChannel ourChannel = null;

    /**
     * For debugging - will be incremented when an IO is started, decremented
     * when it is done. Should be == 0 when container state is changed.
     */
    private int iosInProgress = 0;

    public RAFContainer4(BaseDataFileFactory factory) {
        super(factory);
    }

    /**
     * Return the {@code FileChannel} for the specified
     * {@code StorageRandomAccessFile} if it is a {@code RandomAccessFile}.
     * Otherwise, return {@code null}.
     *
     * @param file the file to get the channel for
     * @return a {@code FileChannel} if {@code file} is an instance of
     * {@code RandomAccessFile}, {@code null} otherwise
     */
    private FileChannel getChannel(StorageRandomAccessFile file) {
        if (file instanceof RandomAccessFile) {
            /** XXX - this cast isn't testing friendly.
             * A testing class that implements StorageRandomAccessFile but isn't
             * a RandomAccessFile will be "worked around" by this class. An
             * example of such a class is
             * functionTests/util/corruptio/CorruptRandomAccessFile.java.
             * An interface rework may be necessary.
             */
            return ((RandomAccessFile) file).getChannel();
        }
        return null;
    }

    /**
     *

     * Return the file channel for the current value of the {@code fileData}
     * field. If {@code fileData} doesn't support file channels, return
     * {@code null}.
     *

     *
     *

     * Callers of this method must synchronize on the container object since
     * two shared fields ({@code fileData} and {@code ourChannel}) are
     * accessed.
     *

     *
     * @return a {@code FileChannel} object, if supported, or {@code null}
     */
    private FileChannel getChannel() {
        if (ourChannel == null) {
            ourChannel = getChannel(fileData);
        }
        return ourChannel;
    }

    /*
     * Wrapping methods that retrieve the FileChannel from RAFContainer's
     * fileData after calling the real methods in RAFContainer.
     */
    synchronized boolean openContainer(ContainerKey newIdentity)
        throws StandardException
    {
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(iosInProgress == 0,
                    "Container opened while IO operations are in progress. "
                    + "This should not happen.");
            SanityManager.ASSERT(fileData == null, "fileData isn't null");
            SanityManager.ASSERT(ourChannel == null, "ourChannel isn't null");
        }

        return super.openContainer(newIdentity);
    }

    synchronized void createContainer(ContainerKey newIdentity)
        throws StandardException
    {
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(iosInProgress == 0,
                    "Container created while IO operations are in progress. "
                    + "This should not happen.");
            SanityManager.ASSERT(fileData == null, "fileData isn't null");
            SanityManager.ASSERT(ourChannel == null, "ourChannel isn't null");
        }
        super.createContainer(newIdentity);
    }

    synchronized void closeContainer() {
        if (SanityManager.DEBUG) {
            // Any IOs in progress to a container being dropped will be
            // ignored, so we should not complain about starting a close
            // while there are IOs in progress if it is being dropped
            // anyway.
            SanityManager.ASSERT( (iosInProgress == 0)
                    || getCommittedDropState(),
                    "Container closed while IO operations are in progress. "
                    + " This should not happen.");
        }
        if(ourChannel != null) {
            try {
                ourChannel.close();
            } catch (IOException e) {
                // nevermind.
            } finally {
                ourChannel=null;
            }
        }
        super.closeContainer();
    }

    /**
     * These are the methods that were rewritten to use FileChannel.
     **/

    /**
     *  Read a page into the supplied array.
     *
     *
 MT - thread safe
     *  @exception IOException exception reading page
     *  @exception StandardException Standard Derby error policy
     */
    protected void readPage(long pageNumber, byte[] pageData)
         throws IOException, StandardException
    {
        // If this is the first alloc page, there may be another thread
        // accessing the container information in the borrowed space on the
        // same page. In that case, we synchronize the entire method call, just
        // like RAFContainer.readPage() does, in order to avoid conflicts. For
        // all other pages it is safe to skip the synchronization, since
        // concurrent threads will access different pages and therefore don't
        // interfere with each other.
        if (pageNumber == FIRST_ALLOC_PAGE_NUMBER) {
            synchronized (this) {
                readPage0(pageNumber, pageData);
            }
        } else {
            readPage0(pageNumber, pageData);
        }
    }

    private void readPage0(long pageNumber, byte[] pageData)
         throws IOException, StandardException
    {
        FileChannel ioChannel;
        synchronized (this) {
            if (SanityManager.DEBUG) {
                SanityManager.ASSERT(!getCommittedDropState());
            }
            ioChannel = getChannel();
        }

        if(ioChannel != null) {

            long pageOffset = pageNumber * pageSize;

            ByteBuffer pageBuf = ByteBuffer.wrap(pageData);

            // I hope the try/finally is optimized away by the
            // compiler/jvm when SanityManager.DEBUG == false?
            try {
                if (SanityManager.DEBUG) {
                    synchronized(this) {
                        iosInProgress++;
                    }
                }

                readFull(pageBuf, ioChannel, pageOffset);
            }
            finally {
                if (SanityManager.DEBUG) {
                    synchronized(this) {
                        iosInProgress--;
                    }
                }

            }

            if (dataFactory.databaseEncrypted() &&
                pageNumber != FIRST_ALLOC_PAGE_NUMBER)
            {
                decryptPage(pageData, pageSize);
            }
        }
        else
        { // iochannel was not initialized, fall back to original method.
            super.readPage(pageNumber, pageData);
        }
    }

    /**
     *  Write a page from the supplied array.
     *
     *
 MT - thread safe
     *
     *  @exception StandardException Standard Derby error policy
     *  @exception IOException IO error accessing page
     */
    protected void writePage(long pageNumber, byte[] pageData, boolean syncPage)
         throws IOException, StandardException
    {
        // If this is the first alloc page, there may be another thread
        // accessing the container information in the borrowed space on the
        // same page. In that case, we synchronize the entire method call, just
        // like RAFContainer.writePage() does, in order to avoid conflicts. For
        // all other pages it is safe to skip the synchronization, since
        // concurrent threads will access different pages and therefore don't
        // interfere with each other.
        if (pageNumber == FIRST_ALLOC_PAGE_NUMBER) {
            synchronized (this) {
                writePage0(pageNumber, pageData, syncPage);
            }
        } else {
            writePage0(pageNumber, pageData, syncPage);
        }
    }

    private void writePage0(long pageNumber, byte[] pageData, boolean syncPage)
         throws IOException, StandardException
    {
        FileChannel ioChannel;
        synchronized (this) {
            // committed and dropped, do nothing.
            // This file container may only be a stub
            if (getCommittedDropState())
                return;
            ioChannel = getChannel();
        }

        if(ioChannel != null) {
            ///////////////////////////////////////////////////
            //
            // RESOLVE: right now, no logical -> physical mapping.
            // We can calculate the offset.  In the future, we may need to
            // look at the allocation page or the in memory translation table
            // to figure out where the page should go
            //
            /////////////////////////////////////////////////

            long pageOffset = pageNumber * pageSize;

            byte[] encryptionBuf = null;
            // We only need to allocate the encryptionBuf if updatePageArray is
            // actually going to use it.
            if (dataFactory.databaseEncrypted()) {
                encryptionBuf = new byte[pageSize];
            }

            byte[] dataToWrite = updatePageArray(pageNumber,
                                                 pageData,
                                                 encryptionBuf,
                                                 false);

            if (SanityManager.DEBUG) {
                SanityManager.ASSERT(dataToWrite != null,
                        "RAFContainer4: dataToWrite is null after updatePageArray()");
            }

            ByteBuffer writeBuffer = ByteBuffer.wrap(dataToWrite);

            dataFactory.writeInProgress();
            try {
                if (SanityManager.DEBUG) {
                    synchronized(this) {
                        iosInProgress++;
                    }
                }

                writeFull(writeBuffer, ioChannel, pageOffset);
            } catch (ClosedChannelException ioe) {
                synchronized(this) {
                    /* If the write failed because the container has been closed
                     * for deletion between the start of this method and the
                     * write, we'll just ignore that, as this container is going
                     * away anyway.
                     * This could possibly happen if the Cache is cleaning this
                     * container while it is dropped - BaseDataFileFactory holds
                     * an exclusive lock on the container while dropping it to
                     * avoid other interference.
                     * See the getCommittedDropState() check at the top of this
                     * method.
                     */
                    if (getCommittedDropState()) {
                        if (SanityManager.DEBUG) {
                            SanityManager.DEBUG_PRINT("RAFContainer4",
                                "Write to a dropped and closed container discarded.");
                        }
                        return;
                    } else {
                        // This should not happen, better let the exception
                        // hurt where it's supposed to.
                        throw ioe;
                    }
                }
            } finally {
                if (SanityManager.DEBUG) {
                    synchronized(this) {
                        iosInProgress--;
                    }
                }

                dataFactory.writeFinished();
            }

            /* Note that the original "try {write} catch IOException { pad file,
             * write again }" in RAFContainer is removed here, because the
             * FileChannel Javadoc specifies that the file will be grown to
             * accommodate the new bytes.
             */

            if (syncPage) {
                dataFactory.writeInProgress();
                try{
                    if (SanityManager.DEBUG) {
                        synchronized(this) {
                            iosInProgress++;
                        }
                    }
                    if (!dataFactory.dataNotSyncedAtAllocation) {
                        ioChannel.force(false);
                    }
                } finally {
                    if (SanityManager.DEBUG) {
                        synchronized(this) {
                            iosInProgress--;
                        }
                    }
                    dataFactory.writeFinished();
                }
            } else {
                synchronized(this) {
                    needsSync = true;
                }
            }

        } else { // iochannel was not initialized, fall back to original method.
            super.writePage(pageNumber, pageData, syncPage);
        }
    }

    /**
     * Write a sequence of bytes at the given offset in a file.
     *
     * @param file the file to write to
     * @param bytes the bytes to write
     * @param offset the offset to start writing at
     * @throws IOException if an I/O error occurs while writing
     */
    void writeAtOffset(StorageRandomAccessFile file, byte[] bytes, long offset)
            throws IOException
    {
        FileChannel ioChannel = getChannel(file);
        if (ioChannel != null) {
            writeFull(ByteBuffer.wrap(bytes), ioChannel, offset);
        } else {
            super.writeAtOffset(file, bytes, offset);
        }
    }

    /**
     * Read an embryonic page (that is, a section of the first alloc page that
     * is so large that we know all the borrowed space is included in it) from
     * the specified offset in a {@code StorageRandomAccessFile}.
     *
     * @param file the file to read from
     * @param offset where to start reading (normally
     * {@code FileContainer.FIRST_ALLOC_PAGE_OFFSET})
     * @return a byte array containing the embryonic page
     * @throws IOException if an I/O error occurs while reading
     */
    byte[] getEmbryonicPage(StorageRandomAccessFile file, long offset)
            throws IOException
    {
        FileChannel ioChannel = getChannel(file);
        if (ioChannel != null) {
            ByteBuffer buffer =
                    ByteBuffer.allocate(AllocPage.MAX_BORROWED_SPACE);
            readFull(buffer, ioChannel, offset);
            return buffer.array();
        } else {
            return super.getEmbryonicPage(file, offset);
        }
    }

    /**
     * Attempts to fill buf completely from start until it's full.
     *

     * FileChannel has no readFull() method, so we roll our own.
     */
    private final void readFull(ByteBuffer dstBuffer,
                                FileChannel srcChannel,
                                long position)
        throws IOException
    {
        while(dstBuffer.remaining() > 0) {
            if( srcChannel.read(dstBuffer, position + dstBuffer.position())
                    == -1)
            {
                throw new EOFException(
                        "Reached end of file while attempting to read a "
                        + "whole page.");
            }
        }
    }

    /**
     * Attempts to write buf completely from start until end, at the given
     * position in the destination fileChannel.
     *

     * FileChannel has no writeFull() method, so we roll our own.
     */
    private final void writeFull(ByteBuffer srcBuffer,
                                 FileChannel dstChannel,
                                 long position)
        throws IOException
    {
        while(srcBuffer.remaining() > 0) {
            dstChannel.write(srcBuffer, position + srcBuffer.position());
        }
    }
}


text:
'use strict';

const Transform = require('stream').Transform;

class LastNewline extends Transform {
    constructor() {
        super();
        this.lastByte = false;
    }

    _transform(chunk, encoding, done) {
        if (chunk.length) {
            this.lastByte = chunk[chunk.length - 1];
        }

        this.push(chunk);
        done();
    }

    _flush(done) {
        if (this.lastByte === 0x0A) {
            return done();
        }
        if (this.lastByte === 0x0D) {
            this.push(Buffer.from('\n'));
            return done();
        }
        this.push(Buffer.from('\r\n'));
        return done();
    }
}

module.exports = LastNewline;


text:
package ru.lotnyk.start;

import java.util.List;

/**
 * abstract class Main.
 * @author Roman Lotnyk(romanlotnik@yandex.ru)
 * @version 1
 * @since 07.02.2017
 */

public abstract class BaseAction implements UserAction {

    /**
     * name action.
     */
    private String name;
    /**
     * array action.
     */
    private List<UserAction> actions;

    /**
     * Constructor.
     * @param name name
     */
    public BaseAction(String name,List<UserAction> actions) {
        this.name = name;
        this.actions = actions;
    }

    /**
     * method info name to action.
     * @return return
     */
    @Override
    public String info() {

        return String.format("%s" , this.name + "\n");
    }

    /**
     * abstract method execute.
     * @param input input
     * @param tracker tracker
     */
    public abstract void execute(Input input, Tracker tracker);

    /**
     * abstract method key.
     * @return return
     */
    public abstract int key();

}


text:
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const cbTypeError = /^TypeError: "callback" argument must be a function$/;
const callbackThrowValues = [null, true, false, 0, 1, 'foo', /foo/, [], {}];

const { sep } = require('path');
const warn = 'Calling an asynchronous function without callback is deprecated.';

common.refreshTmpDir();

function testMakeCallback(cb) {
  return function() {
    // fs.mkdtemp() calls makeCallback() on its third argument
    fs.mkdtemp(`${common.tmpDir}${sep}`, {}, cb);
  };
}

common.expectWarning('DeprecationWarning', warn);

// Passing undefined/nothing calls rethrow() internally, which emits a warning
assert.doesNotThrow(testMakeCallback());

function invalidCallbackThrowsTests() {
  callbackThrowValues.forEach((value) => {
    assert.throws(testMakeCallback(value), cbTypeError);
  });
}

invalidCallbackThrowsTests();


text:
__version__ = "1.1.0"

__all__ = ["Locus", "RefLoci", "Fasta", "Chromosome", "Loci", "Term", "Ontology"]

import logging

from .chromosome import Chromosome
from .fasta import Fasta

from .locus import Locus
from .loci import Loci

from .ontology.term import Term
from .ontology import Ontology

log = logging.getLogger("locuspocus")
# One of DEBUG, INFO, WARNING, ERROR, CRITICAL
log.setLevel(logging.INFO)
# Set up the console handler
ch = logging.StreamHandler()
formatter = logging.Formatter(
    "%(asctime)s | %(name)s | %(levelname)s - %(message)s", datefmt="%d-%b-%y %H:%M:%S"
)
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
log.addHandler(ch)


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Conference'
        db.create_table('conferences', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('unique_name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
            ('confer_name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
            ('title', self.gf('django.db.models.fields.TextField')()),
            ('subtitle', self.gf('django.db.models.fields.TextField')()),
            ('blurb', self.gf('django.db.models.fields.TextField')()),
            ('location', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('start_date', self.gf('django.db.models.fields.DateField')()),
            ('end_date', self.gf('django.db.models.fields.DateField')()),
        ))
        db.send_create_signal('server', ['Conference'])

        # Adding model 'User'
        db.create_table('users', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('email', self.gf('django.db.models.fields.CharField')(unique=True, max_length=100)),
            ('f_name', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('l_name', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('password', self.gf('django.db.models.fields.CharField')(max_length=500)),
        ))
        db.send_create_signal('server', ['User'])

        # Adding model 'Registration'
        db.create_table('registrations', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['server.User'])),
            ('conference', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['server.Conference'])),
        ))
        db.send_create_signal('server', ['Registration'])

        # Adding model 'Likes'
        db.create_table('likes', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('registration', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['server.Registration'])),
            ('likes', self.gf('django.db.models.fields.TextField')()),
        ))
        db.send_create_signal('server', ['Likes'])

        # Adding model 'Logs'
        db.create_table('logs', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('registration', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['server.Registration'])),
            ('action', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('data', self.gf('django.db.models.fields.TextField')()),
        ))
        db.send_create_signal('server', ['Logs'])

    def backwards(self, orm):
        # Deleting model 'Conference'
        db.delete_table('conferences')

        # Deleting model 'User'
        db.delete_table('users')

        # Deleting model 'Registration'
        db.delete_table('registrations')

        # Deleting model 'Likes'
        db.delete_table('likes')

        # Deleting model 'Logs'
        db.delete_table('logs')

    models = {
        'server.conference': {
            'Meta': {'ordering': "['-start_date']", 'object_name': 'Conference', 'db_table': "'conferences'"},
            'blurb': ('django.db.models.fields.TextField', [], {}),
            'confer_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'location': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'start_date': ('django.db.models.fields.DateField', [], {}),
            'subtitle': ('django.db.models.fields.TextField', [], {}),
            'title': ('django.db.models.fields.TextField', [], {}),
            'unique_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
        },
        'server.likes': {
            'Meta': {'object_name': 'Likes', 'db_table': "'likes'"},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'likes': ('django.db.models.fields.TextField', [], {}),
            'registration': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.Registration']"}),
            'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        },
        'server.logs': {
            'Meta': {'ordering': "['-timestamp']", 'object_name': 'Logs', 'db_table': "'logs'"},
            'action': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'data': ('django.db.models.fields.TextField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'registration': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.Registration']"}),
            'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        },
        'server.registration': {
            'Meta': {'object_name': 'Registration', 'db_table': "'registrations'"},
            'conference': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.Conference']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.User']"})
        },
        'server.user': {
            'Meta': {'object_name': 'User', 'db_table': "'users'"},
            'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
            'f_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'l_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
            'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['server']


text:
package com.tle.web.sections.equella.freemarker;

import com.tle.core.guice.Bind;
import com.tle.web.freemarker.SectionsTemplateModelProvider;
import com.tle.web.freemarker.methods.SectionsTemplateModel;
import com.tle.web.sections.SectionWriter;
import com.tle.web.sections.equella.render.DateRenderer;
import com.tle.web.sections.equella.render.DateRendererFactory;
import freemarker.template.TemplateDateModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;

/** @author Aaron */
@Bind
@Singleton
public class DateTemplateModelProvider implements SectionsTemplateModelProvider {
  @Inject private DateRendererFactory dateRendererFactory;

  @Override
  public SectionsTemplateModel getTemplateModel(Object object) {
    return new DateTemplateModel((Date) object, dateRendererFactory);
  }

  public static class DateTemplateModel extends SectionsTemplateModel
      implements TemplateScalarModel, TemplateMethodModelEx {
    private final Date date;
    private DateRendererFactory dateRendererFactory;

    public DateTemplateModel(Date date, DateRendererFactory dateRendererFactory) {
      this.date = date;
      this.dateRendererFactory = dateRendererFactory;
    }

    @Override
    public String getAsString() throws TemplateModelException {
      DateRenderer d = dateRendererFactory.createDateRenderer(date);

      SectionWriter context = getSectionWriter();
      d.preRender(context);

      try {
        StringWriter s = new StringWriter();
        SectionWriter n = new SectionWriter(s, context);
        d.realRender(n);
        return s.toString();
      } catch (IOException e) {
        throw new TemplateModelException(e);
      }
    }

    @Override
    public Object exec(List arguments) throws TemplateModelException {
      // You can use it as a function to prevent the time-ago ness
      return new TemplateDateModel() {
        @Override
        public Date getAsDate() throws TemplateModelException {
          return date;
        }

        @Override
        public int getDateType() {
          return TemplateDateModel.DATETIME;
        }
      };
    }
  }
}


text:
package com.dsi.authorization.model;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

/**
 * Created by sabbir on 1/25/17.
 */

@Entity
@Table(name = "dsi_user_context")
public class UserContext {

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid2")
    @Column(name = "user_context_id", length = 40)
    private String userContextId;

    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Column(columnDefinition = "TEXT")
    private String context;

    private int version;

    public String getUserContextId() {
        return userContextId;
    }

    public void setUserContextId(String userContextId) {
        this.userContextId = userContextId;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }
}


text:
package edu.usu.sdl.openstorefront.core.entity;

import edu.usu.sdl.openstorefront.common.util.OpenStorefrontConstant;
import edu.usu.sdl.openstorefront.core.annotation.APIDescription;
import edu.usu.sdl.openstorefront.core.annotation.ConsumeField;
import edu.usu.sdl.openstorefront.core.annotation.FK;
import edu.usu.sdl.openstorefront.core.annotation.PK;
import edu.usu.sdl.openstorefront.core.annotation.ValidValueType;
import edu.usu.sdl.openstorefront.validation.HTMLSanitizer;
import edu.usu.sdl.openstorefront.validation.Sanitize;
import edu.usu.sdl.openstorefront.validation.TextSanitizer;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@APIDescription("Hold a highlight for the homepage")
public class Highlight
		extends StandardEntity<Highlight>
{

	@PK(generated = true)
	@NotNull
	private String highlightId;

	@NotNull
	@ConsumeField
	@ValidValueType(value = {Highlight.TYPE_ARTICLE, Highlight.TYPE_COMPONENT, Highlight.TYPE_EXTERNAL_LINK}, lookupClass = HighlightType.class)
	@FK(HighlightType.class)
	private String highlightType;

	@NotNull
	@ConsumeField
	@Size(min = 1, max = OpenStorefrontConstant.FIELD_SIZE_GENERAL_TEXT)
	@Sanitize(TextSanitizer.class)
	private String title;

	@NotNull
	@ConsumeField
	@Size(min = 1, max = OpenStorefrontConstant.FIELD_SIZE_64K)
	@Sanitize(HTMLSanitizer.class)
	private String description;

	@ConsumeField
	@Size(min = 0, max = OpenStorefrontConstant.FIELD_SIZE_URL)
	@APIDescription("External URL link")
	private String link;

	@NotNull
	@ConsumeField
	@APIDescription("Position when ordered")
	private Integer orderingPosition;

	public static final String FIELD_TITLE = "title";
	public static final String TYPE_COMPONENT = "C";
	public static final String TYPE_ARTICLE = "A";
	public static final String TYPE_EXTERNAL_LINK = "EL";

	public Highlight()
	{
	}

	@Override
	public void updateFields(StandardEntity entity)
	{
		super.updateFields(entity);

		Highlight highlight = (Highlight) entity;

		this.setDescription(highlight.getDescription());
		this.setHighlightType(highlight.getHighlightType());
		this.setLink(highlight.getLink());
		this.setTitle(highlight.getTitle());
		this.setOrderingPosition(highlight.getOrderingPosition());

	}

	public String getHighlightId()
	{
		return highlightId;
	}

	public void setHighlightId(String highlightId)
	{
		this.highlightId = highlightId;
	}

	public String getHighlightType()
	{
		return highlightType;
	}

	public void setHighlightType(String highlightType)
	{
		this.highlightType = highlightType;
	}

	public String getTitle()
	{
		return title;
	}

	public void setTitle(String title)
	{
		this.title = title;
	}

	public String getDescription()
	{
		return description;
	}

	public void setDescription(String description)
	{
		this.description = description;
	}

	public String getLink()
	{
		return link;
	}

	public void setLink(String link)
	{
		this.link = link;
	}

	public Integer getOrderingPosition()
	{
		return orderingPosition;
	}

	public void setOrderingPosition(Integer orderingPosition)
	{
		this.orderingPosition = orderingPosition;
	}

}


text:
<?php

namespace AppBundle\Entity;

interface iPakliTemplate
{
    function __construct(int $csomagszam);
    public function EgyVeletlenLapotHuz():Lap;
}


text:
  - **v0.0.12** - Added compress key option support
  - **v0.0.11** - Added Worldcoin support
  - **v0.0.10** - Added Megacoin support
  - **v0.0.9** - Added Primecoin support
  - **v0.0.8** - Added Feathercoin support
  - **v0.0.7** - Added Namecoin support
  - **v0.0.6** - Dogecoin gets compressed wallet support
  - **v0.0.5** - Added Dogecoin address generation capabilities
  - **v0.0.4** - Added Peercoin address generation capabilities
  - **v0.0.3** - Added Litecoin address generation capabilities
  - **v0.0.2** - Readme and usage instructions
  - **v0.0.1** - Basic implementation for uncompressed addresses for Bitcoin


text:
/* global describe, it, beforeEach */
'use strict';

var expect = require('chai').expect;

var createMockActionContext = require('fluxible/utils').createMockActionContext;
var initAction = require('../../../actions/init');
var BackgroundStore = require('../../../stores/BackgroundStore');

describe('init action', function () {
  var context, params = {
    backgrounds: {
      serviceUrl: 'http://lorempixel.com',
      backgrounds: ['1', '2']
    }
  };

  // create the action context wired to BackgroundStore
  beforeEach(function () {
    context = createMockActionContext({
      stores: [ BackgroundStore ]
    });
  });

  it('should update the background store', function (done) {
    context.executeAction(initAction, params, function (err) {
      if (err) {
        return done(err);
      }

      var store = context.getStore(BackgroundStore);

      expect(store.getImageServiceUrl()).to.equal(params.backgrounds.serviceUrl);
      expect(Object.keys(store.backgroundUrls)).to.have.length(2);

      done();
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MaterialStyledDialogs Bibliothek (Beispiel)</string>
    <string name="app_description">Eine Bibliothek, die einen schönen und einstellbaren MaterialDialog mit Header und Animationen zeigt.</string>
    <string name="action_about">Über</string>

    <string name="section_style_1">Stil 1</string>
    <string name="section_style_2">Stil 2</string>

    <string name="btn_style_header_1">Header mit grüner Farbe, Icon, Titel, Beschreibung und Animationen</string>
    <string name="btn_style_header_2">Header mit grauer Farbe, Icon und Beschreibung</string>
    <string name="btn_style_header_3">Header mit Bild, Icon, Titel, Beschreibung und Animationen</string>
    <string name="btn_style_header_4">Header mit Bild, Titel und Beschreibung</string>
    <string name="btn_style_header_5">Header mit grüner Farbe, Icon, Titel, Beschreibung, Animationen und benutzerdefiniertem Layout</string>

    <string name="btn_style_header_6">Header mit grüner Farbe, Titel, Beschreibung und Animationen</string>
    <string name="btn_style_header_7">Header mit Bild, Titel und Beschreibung</string>
</resources>


text:
package org.lirazs.gbackbone.reflection.client.impl;

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

import org.lirazs.gbackbone.reflection.client.EnumConstant;
import org.lirazs.gbackbone.reflection.client.EnumType;
import org.lirazs.gbackbone.reflection.client.Field;

public class EnumTypeImpl<T> extends ClassTypeImpl<T> implements EnumType<T> {

	public EnumTypeImpl(final Class<T> declaringClass) {
		super(declaringClass);
	}

	public EnumType<?> isEnum() {
		return this;
	}

	public EnumConstant[] getEnumConstants() {
		if (lazyEnumConstants == null) {
      final List<EnumConstant> enumConstants = new ArrayList<EnumConstant>();
      for (final Field field : getFields()) {
        if (field.isEnumConstant() != null) {
          enumConstants.add(field.isEnumConstant());
        }
      }

      lazyEnumConstants = enumConstants.toArray(new EnumConstant[0]);
    }

    return lazyEnumConstants;
	}

	private EnumConstant[] lazyEnumConstants;

}


text:
using System.Runtime.Serialization;

namespace Org.Apache.REEF.Examples.MachineLearning.KMeans.Contracts
{
    [DataContract]
    public class PartialMeanContract
    {
        [DataMember]
        public DataVectorContract DataVectContract { get; set; }

        [DataMember]
        public int Size { get; set; }

        public static PartialMeanContract Create(PartialMean partialMean)
        {
            return new PartialMeanContract
            {
                DataVectContract = DataVectorContract.Create(partialMean.Mean),
                Size = partialMean.Size
            };
        }

        public PartialMean ToPartialMean()
        {
            DataVector dataVector = DataVectContract.ToDataVector();
            return new PartialMean(dataVector, Size);
        }
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Blobs.Listeners;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.Listeners;
using Microsoft.Azure.Storage.Blob;
using Xunit;

namespace Microsoft.Azure.WebJobs.Host.FunctionalTests.Blobs.Listeners
{
    public class ScanContainersStrategyTests
    {
        [Fact]
        public async Task TestBlobListener()
        {
            const string containerName = "container";
            var account = CreateFakeStorageAccount();
            var container = account.CreateCloudBlobClient().GetContainerReference(containerName);
            IBlobListenerStrategy product = new ScanContainersStrategy();
            LambdaBlobTriggerExecutor executor = new LambdaBlobTriggerExecutor();
            product.Register(container, executor);
            product.Start();

            executor.ExecuteLambda = (_) =>
            {
                throw new InvalidOperationException("shouldn't be any blobs in the container");
            };
            product.Execute();

            const string expectedBlobName = "foo1.csv";
            var blob = container.GetBlockBlobReference(expectedBlobName);
            await container.CreateIfNotExistsAsync();
            await blob.UploadTextAsync("ignore");

            int count = 0;
            executor.ExecuteLambda = (b) =>
            {
                count++;
                Assert.Equal(expectedBlobName, b.Name);
                return true;
            };
            product.Execute();
            Assert.Equal(1, count);

            // Now run again; shouldn't show up.
            executor.ExecuteLambda = (_) =>
            {
                throw new InvalidOperationException("shouldn't retrigger the same blob");
            };
            product.Execute();
        }

        private static StorageAccount CreateFakeStorageAccount()
        {
            return new FakeStorageAccount();
        }

        private class LambdaBlobTriggerExecutor : ITriggerExecutor<BlobTriggerExecutorContext>
        {
            public Func<ICloudBlob, bool> ExecuteLambda { get; set; }

            public Task<FunctionResult> ExecuteAsync(BlobTriggerExecutorContext value, CancellationToken cancellationToken)
            {
                bool succeeded = ExecuteLambda.Invoke(value.Blob);
                FunctionResult result = new FunctionResult(succeeded);
                return Task.FromResult(result);
            }
        }
    }
}


text:
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.junit.Assert;
import org.junit.Test;

import static org.apache.jena.rdf.model.ResourceFactory.createProperty;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
import static org.apache.jena.rdf.model.ResourceFactory.createStatement;
import static org.apache.jena.rdf.model.ResourceFactory.createStringLiteral;

/**
 * @author awoods
 * @since 2020-04-01
 */
public class AdditionsAndRetractionsTest {

    @Test
    public void testToString() {
        Model additions = ModelFactory.createDefaultModel();
        additions.add(createStatement(
                createResource("test:add"),
                createProperty("test:prop"),
                createStringLiteral("new")));

        Model retractions = ModelFactory.createDefaultModel();
        retractions.add(createStatement(
                createResource("test:retract"),
                createProperty("test:prop"),
                createStringLiteral("old")));
        AdditionsAndRetractions aar = new AdditionsAndRetractions(additions, retractions);

        final String s = aar.toString();
        Assert.assertNotNull(s);
        Assert.assertTrue(s.contains("test:add"));
        Assert.assertTrue(s.contains("test:retract"));
    }
}