text:
package org.mortbay.jetty.alpn.agent;

import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Map;

final class ReplacingClassFileTransformer implements ClassFileTransformer {
    private final Map<String, byte[]> classes;

    ReplacingClassFileTransformer(Map<String, byte[]> classes) {
        this.classes = classes;
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
        final byte[] content = classes.get(className);
        if (content == null || Arrays.equals(content, classfileBuffer)) {
            return null;
        }

        Util.debug("Replacing: " + className);
        return content.clone();
    }
}


text:
using std::string;
template <class T>
using sptr = std::shared_ptr<T>;

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))

include DataMapper::Query::Conditions

module ComparisonSpecHelpers

  def match(record)
    ComparisonMatcher.new(record)
  end

  class ComparisonMatcher

    def initialize(record)
      @record = record
    end

    def matches?(comparison)
      @comparison = comparison
      comparison.matches?(@record)
    end

    def failure_message
      "Expected #{@comparison.inspect} to match #{@record.inspect}"
    end

    def negative_failure_message
      "Expected #{@comparison.inspect} to NOT match #{@record.inspect}"
    end

  end

end

describe DataMapper::Query::Conditions do

  include ComparisonSpecHelpers

  before :all do
    class ::Heffalump
      include DataMapper::Resource

      property :id,        Serial
      property :color,     String
      property :num_spots, Integer
      property :striped,   Boolean
    end

    @heff1 = Heffalump.new(:num_spots => 1, :color => 'green')
    @heff2 = Heffalump.new(:num_spots => 2, :color => 'green')
    @heff3 = Heffalump.new(:num_spots => 3, :color => 'blue')

  end

  describe "Operations" do
    before do
      @comp1 = Comparison.new(:eql, Heffalump.num_spots, 1)
      @comp2 = Comparison.new(:eql, Heffalump.color, 'green')
    end

    it 'should initialize an AbstractOperation object' do
      op = Operation.new(:and)
      op.should be_kind_of(AbstractOperation)
    end

    {
      :and => AndOperation,
      :or  => OrOperation,
      :not => NotOperation
    }.each do |operand, klass|
      it "should initialize as #{klass} for the #{operand} operator" do
        op = Operation.new(operand)
        op.should be_kind_of(klass)
      end
    end

    it 'should set the remaining args in @operands' do
      op = Operation.new(:and, @comp1, @comp2)
      op.operands.should == [@comp1, @comp2]
    end

    it 'should have operands be empty of no operands are provided' do
      op = Operation.new(:and)
      op.operands.should == []
    end

    describe 'NotOperation' do
      before do
        @op = Operation.new(:not, @comp1)
      end

      it 'should not allow more than one operand' do
        lambda {
          Operation.new(:not, @comp1, @comp2)
        }.should raise_error(InvalidOperation)
      end

      it 'should negate the comparison' do
        @comp1.should match(@heff1)
        @op.should_not match(@heff1)
      end
    end

    describe 'AndOperation' do
      before do
        @op = Operation.new(:and, @comp1, @comp2)
      end

      it 'should match if all comparisons match' do
        @comp1.should match(@heff1)
        @comp2.should match(@heff1)

        @op.should match(@heff1)
      end

      it 'should not match of any of the comparisons does not match' do
        @comp1.should_not match(@heff2)

        @op.should_not match(@heff2)
      end
    end

    describe 'OrOperation' do
      before do
        @op = Operation.new(:or, @comp1, @comp2)
      end

      it 'should match if any of the comparisons match' do
        @comp1.should_not match(@heff2)
        @comp2.should match(@heff2)

        @op.should match(@heff2)
      end

      it 'should not match if none of the comparisons match' do
        @comp1.should_not match(@heff3)
        @comp2.should_not match(@heff3)

        @op.should_not match(@heff3)
      end
    end
  end

  describe "Comparisons" do
    it 'should initialize an AbstractComparison object' do
      comp = Comparison.new(:eql, Heffalump.num_spots, 1)
      comp.should be_kind_of(AbstractComparison)
    end

    {
      :eql    => EqualToComparison,
      :gt     => GreaterThanComparison,
      :gte    => GreaterThanOrEqualToComparison,
      :lt     => LessThanComparison,
      :lte    => LessThanOrEqualToComparison,
      :regexp => RegexpComparison
    }.each do |slug, klass|
      it "should initialize as #{klass} for the #{slug} comparator" do
        comp = Comparison.new(slug, Heffalump.num_spots, 2)
        comp.should be_kind_of(klass)
      end
    end

    it "should initialize as InclusionComparison for the :in comparator" do
      comp = Comparison.new(:in, Heffalump.num_spots, [ 2 ])
      comp.should be_kind_of(InclusionComparison)
    end

    describe "EqualToComparison" do
      before do
        @comp = Comparison.new(:eql, Heffalump.num_spots, 1)
      end

      it "should match records that equal the given value" do
        @comp.should match(@heff1)
      end

      it "should not match records that do not equal the given value" do
        @comp.should_not match(@heff2)
      end
    end

    describe "InclusionComparison" do
      before do
        @comp = Comparison.new(:in, Heffalump.num_spots, 1..2)
      end

      it "should match records that equal the given value" do
        @comp.should match(@heff1)
        @comp.should match(@heff2)
      end

      it "should not match records that do not equal the given value" do
        @comp.should_not match(@heff3)
      end
    end

    describe "GreaterThanComparison" do
      before do
        @comp = Comparison.new(:gt, Heffalump.num_spots, 2)
      end

      it "should match records that are greater than the given value" do
        @comp.should match(@heff3)
      end

      it "should not match records that are not greater than the given value" do
        @comp.should_not match(@heff1)
        @comp.should_not match(@heff2)
      end
    end

    describe "GreaterThanOrEqualToComparison" do
      before do
        @comp = Comparison.new(:gte, Heffalump.num_spots, 2)
      end

      it "should match records that are greater than or equal to the given value" do
        @comp.should match(@heff2)
        @comp.should match(@heff3)
      end

      it "should not match records that are not greater than or equal to the given value" do
        @comp.should_not match(@heff1)
      end
    end

    describe "LessThanComparison" do
      before do
        @comp = Comparison.new(:lt, Heffalump.num_spots, 2)
      end

      it "should match records that are less than the given value" do
        @comp.should match(@heff1)
      end

      it "should not match records that are not less than the given value" do
        @comp.should_not match(@heff2)
        @comp.should_not match(@heff3)
      end
    end

    describe "LessThanOrEqualToComparison" do
      before do
        @comp = Comparison.new(:lte, Heffalump.num_spots, 2)
      end

      it "should match records that are less than or equal to the given value" do
        @comp.should match(@heff1)
        @comp.should match(@heff2)
      end

      it "should not match records that are not less than or equal to the given value" do
        @comp.should_not match(@heff3)
      end
    end

    describe "RegexpComparison" do
      before do
        @comp = Comparison.new(:regexp, Heffalump.color, /green/)
        @heff2.color = 'forest green'
      end

      it "should match records that match the regexp" do
        @comp.should match(@heff1)
        @comp.should match(@heff2)
      end

      it "should not match records that don't match the regexp" do
        @comp.should_not match(@heff3)
      end

    end

  end

end


text:
@implementation Module1

+ (instancetype)sharedInstence {
    static id sharedInstence = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedInstence = [[self alloc] init];
    });
    return sharedInstence;
}

+ (void)load {
    [[SFModularization sharedInstence] registerModule:[self sharedInstence] protocols:@[@protocol(Module1Protocol)]];
    [[SFModularization sharedInstence] addListener:[self sharedInstence] toEvent:ModuleEvent];
}

- (void)receiveEvent:(NSString *)event params:(NSDictionary *)params {
    NSLog(@"%@ receieve event:%@ params:%@", NSStringFromClass([self class]), event, params);
}
@end


text:
package lila.team

import lila.memo.{ MixedCache, AsyncCache }
import scala.concurrent.duration._

private[team] final class Cached {

  private val nameCache = MixedCache[String, Option[String]](TeamRepo.name,
    timeToLive = 6 hours,
    default = _ => none)

  def name(id: String) = nameCache get id

  private[team] val teamIdsCache = MixedCache[String, List[String]](MemberRepo.teamIdsByUser,
    timeToLive = 2 hours,
    default = _ => Nil)

  def teamIds(userId: String) = teamIdsCache get userId

  val nbRequests = AsyncCache(
    (userId: String) => TeamRepo teamIdsByCreator userId flatMap RequestRepo.countByTeams,
    maxCapacity = 8192)
}


text:
<?php

namespace Magento\Review\Test\Constraint;

use Magento\Catalog\Test\Fixture\CatalogProductSimple;
use Magento\Catalog\Test\Page\Product\CatalogProductView;
use Magento\Review\Test\Fixture\Rating;
use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\Constraint\AbstractConstraint;

/**
 * Class AssertProductRatingNotInProductPage
 */
class AssertProductRatingNotInProductPage extends AbstractConstraint
{
    /**
     * Assert that product rating is not displayed on frontend on product review
     *
     * @param CatalogProductView $catalogProductView
     * @param CatalogProductSimple $product
     * @param Rating $productRating
     * @param BrowserInterface $browser
     * @return void
     */
    public function processAssert(
        CatalogProductView $catalogProductView,
        CatalogProductSimple $product,
        Rating $productRating,
        BrowserInterface $browser
    ) {
        $browser->open($_ENV['app_frontend_url'] . $product->getUrlKey() . '.html');
        $catalogProductView->getReviewSummary()->getAddReviewLink()->click();

        $reviewForm = $catalogProductView->getReviewFormBlock();
        \PHPUnit_Framework_Assert::assertFalse(
            $reviewForm->isVisibleRating($productRating),
            'Product rating "' . $productRating->getRatingCode() . '" is displayed.'
        );
    }

    /**
     * Text success product rating is not displayed
     *
     * @return string
     */
    public function toString()
    {
        return 'Product rating is not displayed.';
    }
}


text:
package cucumber.contrib.formatter.model;

import gherkin.formatter.model.Comment;
import gherkin.formatter.model.Scenario;
import gherkin.formatter.model.Step;
import org.junit.Test;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static org.fest.assertions.Assertions.assertThat;

public class ScenarioWrapperTest {

    @Test
    public void with_Scenario_comment_should_escape_double_sharp_lines() throws Exception {
        ScenarioWrapper scenarioWrapper = new ScenarioWrapper(new Scenario(null, null, null, null, null, null, null));
        List<Comment> comments = newArrayList(new Comment("## foo", 42));
        scenarioWrapper.step(new Step(comments, null, null, null, null, null));

        assertThat(scenarioWrapper.getDescription()).isEmpty();
    }
}


text:
class Option < ActiveRecord::Base
  has_one :user
  has_one :user_transaction

end


text: angular.module('dashboard.app', ['common.app']);


text:
author: angad
categories:
  - Events
  - Featured
  - Headline
  - News
  - Slides
comments: true
date: 2010-10-10T00:00:00.000Z
title: 'Workshop #5 PHP and CodeIgniter'
url: /2010/10/workshop-5-php-and-codeigniter-2/
aliases:
  - /2010/10/10/workshop-5-php-and-codeigniter-2/
---

The fifth workshop in the Hack Workshop Series was the introduction to web programming language PHP and its light-weight framework - CodeIgniter.

The slides for the workshop are available here : //linuxnus.org/hack/files/PHP_CI.pdf

The notes application example that was shown during the workshop //angad.sg/ci/

Source Code for it : //angad.sg/ci/notes.tar.gz github //github.com/angad/Notes-webapp

Do email at angad (d0t) singh (at) linuxnus (dot) org if you find any bugs. If you want to take this project further with AJAX, search and what-not features, go ahead.

The Hack Workshop Series, sponsored by IDA Singapore, equips geeks/non-geeks with a good base in development and idea execution.

It is co-organized with NES, Garag3, e27, Hackerspace and NOC Alumni.


text:
package com.sequenceiq.distrox.api.v1.distrox.endpoint;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.springframework.validation.annotation.Validated;

import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.osupgrade.OrderedOSUpgradeSetRequest;
import com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;
import com.sequenceiq.cloudbreak.jerseyclient.RetryAndMetrics;
import com.sequenceiq.cloudbreak.validation.ValidCrn;
import com.sequenceiq.distrox.api.v1.distrox.model.upgrade.DistroXCcmUpgradeV1Response;
import com.sequenceiq.distrox.api.v1.distrox.model.upgrade.DistroXUpgradeV1Request;
import com.sequenceiq.distrox.api.v1.distrox.model.upgrade.DistroXUpgradeV1Response;
import com.sequenceiq.distrox.api.v1.distrox.model.upgrade.rds.DistroXRdsUpgradeV1Request;
import com.sequenceiq.distrox.api.v1.distrox.model.upgrade.rds.DistroXRdsUpgradeV1Response;
import com.sequenceiq.flow.api.model.FlowIdentifier;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Validated
@Path("/v1/distrox")
@RetryAndMetrics
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/v1/distrox", protocols = "http,https", consumes = MediaType.APPLICATION_JSON)
public interface DistroXUpgradeV1Endpoint {

    @PUT
    @Path("{name}/rds_upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the external database of the distrox cluster", nickname = "upgradeDistroXRdsByName")
    DistroXRdsUpgradeV1Response upgradeRdsByName(@PathParam("name") String clusterName, @Valid DistroXRdsUpgradeV1Request distroxRdsUpgradeRequest);

    @PUT
    @Path("/crn/{crn}/rds_upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the external database of the distrox cluster", nickname = "upgradeDistroXRdsByCrn")
    DistroXRdsUpgradeV1Response upgradeRdsByCrn(@ValidCrn(resource = CrnResourceDescriptor.DATAHUB) @PathParam("crn") String clusterCrn,
            @Valid DistroXRdsUpgradeV1Request distroxRdsUpgradeRequest);

    @POST
    @Path("{name}/upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the distrox cluster", nickname = "upgradeDistroxCluster")
    DistroXUpgradeV1Response upgradeClusterByName(@PathParam("name") String name, @Valid DistroXUpgradeV1Request distroxUpgradeRequest);

    @POST
    @Path("/crn/{crn}/upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the distrox cluster", nickname = "upgradeDistroxClusterByCrn")
    DistroXUpgradeV1Response upgradeClusterByCrn(@ValidCrn(resource = CrnResourceDescriptor.DATAHUB) @PathParam("crn") String crn,
            @Valid DistroXUpgradeV1Request distroxUpgradeRequest);

    @POST
    @Path("{name}/prepare_upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "prepares the distrox cluster for upgrade", nickname = "prepareDistroxClusterUpgrade")
    DistroXUpgradeV1Response prepareClusterUpgradeByName(@PathParam("name") String name, @Valid DistroXUpgradeV1Request distroxUpgradeRequest);

    @POST
    @Path("/crn/{crn}/prepare_upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "prepares the distrox cluster for upgrade", nickname = "prepareDistroxClusterUpgradeByCrn")
    DistroXUpgradeV1Response prepareClusterUpgradeByCrn(@ValidCrn(resource = CrnResourceDescriptor.DATAHUB) @PathParam("crn") String crn,
            @Valid DistroXUpgradeV1Request distroxUpgradeRequest);

    @POST
    @Path("internal/{name}/upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the distrox cluster internal", nickname = "upgradeDistroxClusterInternal")
    DistroXUpgradeV1Response upgradeClusterByNameInternal(@PathParam("name") String name, @Valid DistroXUpgradeV1Request distroxUpgradeRequest,
            @QueryParam("initiatorUserCrn") String initiatorUserCrn, @QueryParam("rollingUpgradeEnabled") Boolean rollingUpgradeEnabled);

    @POST
    @Path("internal/crn/{crn}/upgrade")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades the distrox cluster internal", nickname = "upgradeDistroxClusterByCrnInternal")
    DistroXUpgradeV1Response upgradeClusterByCrnInternal(@ValidCrn(resource = CrnResourceDescriptor.DATAHUB) @PathParam("crn") String crn,
            @Valid DistroXUpgradeV1Request distroxUpgradeRequest,
            @QueryParam("initiatorUserCrn") String initiatorUserCrn, @QueryParam("rollingUpgradeEnabled") Boolean rollingUpgradeEnabled);

    @PUT
    @Path("internal/crn/{crn}/upgrade_ccm")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Initiates the CCM tunnel type upgrade to the latest available version", nickname = "upgradeCcmByDatahubCrnInternal")
    DistroXCcmUpgradeV1Response upgradeCcmByCrnInternal(@NotEmpty @ValidCrn(resource = CrnResourceDescriptor.DATAHUB) @PathParam("crn") String crn,
            @ValidCrn(resource = { CrnResourceDescriptor.USER, CrnResourceDescriptor.MACHINE_USER })
            @NotEmpty @QueryParam("initiatorUserCrn") String initiatorUserCrn);

    @POST
    @Path("internal/{crn}/os_upgrade_by_upgrade_sets")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Upgrades distrox cluster OS by name and upgrades sets internal", nickname = "osUpgradeByUpgradeSetsInternal")
    FlowIdentifier osUpgradeByUpgradeSetsInternal(@PathParam("crn") String crn, OrderedOSUpgradeSetRequest orderedOsUpgradeSetRequest);

}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable enable

using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Input.Events;
using osu.Framework.Platform;
using osu.Game.Input.Bindings;
using osuTK.Input;
using osu.Framework.Input.Bindings;
using osu.Game.Overlays;

namespace osu.Game.Graphics.UserInterface
{
    /// <summary>
    /// A textbox which holds focus eagerly.
    /// </summary>
    public class FocusedTextBox : OsuTextBox, IKeyBindingHandler<GlobalAction>
    {
        private bool focus;

        private bool allowImmediateFocus => host?.OnScreenKeyboardOverlapsGameWindow != true;

        public void TakeFocus()
        {
            if (!allowImmediateFocus)
                return;

            Scheduler.Add(() => GetContainingInputManager().ChangeFocus(this), false);
        }

        public new void KillFocus() => base.KillFocus();

        public bool HoldFocus
        {
            get => allowImmediateFocus && focus;
            set
            {
                focus = value;
                if (!focus && HasFocus)
                    base.KillFocus();
            }
        }

        [Resolved]
        private GameHost? host { get; set; }

        [BackgroundDependencyLoader(true)]
        private void load(OverlayColourProvider? colourProvider)
        {
            BackgroundUnfocused = colourProvider?.Background5 ?? new Color4(10, 10, 10, 255);
            BackgroundFocused = colourProvider?.Background5 ?? new Color4(10, 10, 10, 255);
        }

        // We may not be focused yet, but we need to handle keyboard input to be able to request focus
        public override bool HandleNonPositionalInput => HoldFocus || base.HandleNonPositionalInput;

        protected override void OnFocus(FocusEvent e)
        {
            base.OnFocus(e);
            BorderThickness = 0;
        }

        protected override bool OnKeyDown(KeyDownEvent e)
        {
            if (!HasFocus) return false;

            if (e.Key == Key.Escape)
                return false; // disable the framework-level handling of escape key for conformity (we use GlobalAction.Back).

            return base.OnKeyDown(e);
        }

        public virtual bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
        {
            if (e.Repeat)
                return false;

            if (!HasFocus) return false;

            if (e.Action == GlobalAction.Back)
            {
                if (Text.Length > 0)
                {
                    Text = string.Empty;
                    return true;
                }
            }

            return false;
        }

        public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
        {
        }

        public override bool RequestsFocus => HoldFocus;
    }
}


text:
layout: post
title: IITK New York Office Internship Day 12 - Clipper Plugin Template
---
##### *May 26, 2016*

Design the template of clipper plugin using Photoshop. Also, tried to install angular material 2.

![Clipper](https://raw.githubusercontent.com/subhamg/subhamg.github.io/master/images/CLIPPER.jpg)

![Clipper 2](https://raw.githubusercontent.com/subhamg/subhamg.github.io/master/images/Clipper%202.jpg)


text:
Currently this depends on an outdated version of the osrg/gobgp
library -- the commit ID 1b84b8145418398e7e68b81cdce506dcf81eec14
seems to work.


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

__author__ = 'Ryan McGrath <ryan@rymc.io>'
__version__ = '3.9.1'

packages = [
    'twython',
    'twython.streaming'
]

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

setup(
    name='twython',
    version=__version__,
    install_requires=['requests>=2.1.0', 'requests_oauthlib>=0.4.0'],
    python_requires='>=3.5',
    author='Ryan McGrath',
    author_email='ryan@rymc.io',
    license='MIT',
    url='https://github.com/ryanmcgrath/twython/tree/master',
    keywords='twitter search api tweet twython stream',
    description='Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs',
    long_description=open('README.md', encoding='utf-8').read() + '\n\n' +open('HISTORY.md', encoding='utf-8').read(),
    long_description_content_type='text/markdown',
    include_package_data=True,
    packages=packages,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Communications :: Chat',
        'Topic :: Internet',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ]
)


text:
<!DOCTYPE html>

    <title>Chapter 1 | The Red Badge of Courage | Stephen Crane | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      The Red Badge of Courage

      by Stephen Crane

      Chapter 1

        Additional Information

            Year Published:
            1895

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Crane, S. (1895)  The Red Badge of Courage  New York: Charles Scribner's Sons

            Readability:

                Flesch–Kincaid Level:
                5.9

            Word Count:
            4,033

            Genre:
            Realism

            Keywords:
            19th century literature, american literature

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

            APA

            MLA

            Chicago

            Crane, S. (1895). Chapter 1. The Red Badge of Courage (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/176/the-red-badge-of-courage/3196/chapter-1/

            Crane, Stephen. "Chapter 1." The Red Badge of Courage. Lit2Go Edition. 1895. Web. <http://etc.usf.edu/lit2go/176/the-red-badge-of-courage/3196/chapter-1/>. February 15, 2016.

            Stephen Crane, "Chapter 1," The Red Badge of Courage, Lit2Go Edition, (1895), accessed February 15, 2016, http://etc.usf.edu/lit2go/176/the-red-badge-of-courage/3196/chapter-1/.

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/the-red-badge-of-courage-001-chapter-1.3196.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/the-red-badge-of-courage-001-chapter-1.3196.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	The cold passed reluctantly from the earth, and the retiring fogs revealed an army stretched out on the hills, resting. As the landscape changed from brown to green, the army awakened, and began to tremble with eagerness at the noise of rumors. It cast its eyes upon the roads, which were growing from long troughs of liquid mud to proper thoroughfares. A river, amber-tinted in the shadow of its banks, purled at the army’s feet; and at night, when the stream had become of a sorrowful blackness, one could see across it the red, eyelike gleam of hostile camp-fires set in the low brows of distant hills.

	Once a certain tall soldier developed virtues and went resolutely to wash a shirt. He came flying back from a brook waving his garment bannerlike. He was swelled with a tale he had heard from a reliable friend, who had heard it from a truthful cavalryman, who had heard it from his trustworthy brother, one of the orderlies at division headquarters. He adopted the important air of a herald in red and gold.

	“We’re goin’ t’ move t’morrah—sure,” he said pompously to a group in the company street. “We’re goin’ ‘way up the river, cut across, an’ come around in behint ‘em.”

	To his attentive audience he drew a loud and elaborate plan of a very brilliant campaign. When he had finished, the blue-clothed men scattered into small arguing groups between the rows of squat brown huts. A negro teamster who had been dancing upon a cracker box with the hilarious encouragement of twoscore soldiers was deserted. He sat mournfully down. Smoke drifted lazily from a multitude of quaint chimneys.

	“It’s a lie! that’s all it is—a thunderin’ lie!” said another private loudly. His smooth face was flushed, and his hands were thrust sulkily into his trouser’s pockets. He took the matter as an affront to him. “I don’t believe the derned old army’s ever going to move. We’re set. I’ve got ready to move eight times in the last two weeks, and we ain’t moved yet.”

	The tall soldier felT called upon to defend the truth of a rumor he himself had introduced. He and the loud one came near to fighting over it.

	A corporal began to swear before the assemblage. He had just put a costly board floor in his house, he said. During the early spring he had refrained from adding extensively to the comfort of his environment because he had felt that the army might start on the march at any moment. Of late, however, he had been impressed that they were in a sort of eternal camp.

	Many of the men engaged in a spirited debate. One outlined in a peculiarly lucid manner all the plans of the commanding general. He was opposed by men who advocated that there were other plans of campaign. They clamored at each other, numbers making futile bids for the popular attention. Meanwhile, the soldier who had fetched the rumor bustled about with much importance. He was continually assailed by questions.

	“What’s up, Jim?”

	“Th’army’s goin’ t’ move.”

	“Ah, what yeh talkin’ about? How yeh know it is?”

	“Well, yeh kin b’lieve me er not, jest as yeh like. I don’t care a hang.”

	There was much food for thought in the manner in which he replied. He came near to convincing them by disdaining to produce proofs. They grew much excited over it.

	There was a youthful private who listened with eager ears to the words of the tall soldier and to the varied comments of his comrades. After receiving a fill of discussions concerning marches and attacks, he went to his hut and crawled through an intricate hole that served it as a door. He wished to be alone with some new thoughts that had lately come to him.

	He lay down on a wide bunk that stretched across the end of the room. In the other end, cracker boxes were made to serve as furniture. They were grouped about the fireplace. A picture from an illustrated weekly was upon the log walls, and three rifles were paralleled on pegs. Equipments hung on handy projections, and some tin dishes lay upon a small pile of firewood. A folded tent was serving as a roof. The sunlight, without, beating upon it, made it glow a light yellow shade. A small window shot an oblique square of whiter light upon the cluttered floor. The smoke from the fire at times neglected the clay chimney and wreathed into the room, and this flimsy chimney of clay and sticks made endless threats to set ablaze the whole establishment.

	The youth was in a little trance of astonishment. So they were at last going to fight. On the morrow, perhaps, there would be a battle, and he would be in it. For a time he was obliged to labor to make himself believe. He could not accept with assurance an omen that he was about to mingle in one of those great affairs of the earth.

	He had, of course, dreamed of battles all his life—of vague and bloody conflicts that had thrilled him with their sweep and fire. In visions he had seen himself in many struggles. He had imagined peoples secure in the shadow of his eagle-eyed prowess. But awake he had regarded battles as crimson blotches on the pages of the past. He had put them as things of the bygone with his thought-images of heavy crowns and high castles. There was a portion of the world’s history which he had regarded as the time of wars, but it, he thought, had been long gone over the horizon and had disappeared forever.

	From his home his youthful eyes had looked upon the war in his own country with distrust. It must be some sort of a play affair. He had long despaired of witnessing a Greeklike struggle. Such would be no more, he had said. Men were better, or more timid. Secular and religious education had effaced the throat-grappling instinct, or else firm finance held in check the passions.

	He had burned several times to enlist. Tales of great movements shook the land. They might not be distinctly Homeric, but there seemed to be much glory in them. He had read of marches, sieges, conflicts, and he had longed to see it all. His busy mind had drawn for him large pictures extravagant in color, lurid with breathless deeds.

	But his mother had discouraged him. She had affected to look with some contempt upon the quality of his war ardor and patriotism. She could calmly seat herself and with no apparent difficulty give him many hundreds of reasons why he was of vastly more importance on the farm than on the field of battle. She had had certain ways of expression that told him that her statements on the subject came from a deep conviction. Moreover, on her side, was his belief that her ethical motive in the argument was impregnable.

	At last, however, he had made firm rebellion against this yellow light thrown upon the color of his ambitions. The newspapers, the gossip of the village, his own picturings, had aroused him to an uncheckable degree. They were in truth fighting finely down there. Almost every day the newspaper printed accounts of a decisive victory.

	One night, as he lay in bed, the winds had carried to him the clangoring of the church bell as some enthusiast jerked the rope frantically to tell the twisted news of a great battle. This voice of the people rejoicing in the night had made him shiver in a prolonged ecstasy of excitement. Later, he had gone down to his mother’s room and had spoken thus: “Ma, I’m going to enlist.”

	“Henry, don’t you be a fool,” his mother had replied. She had then covered her face with the quilt. There was an end to the matter for that night.

	Nevertheless, the next morning he had gone to a town that was near his mother’s farm and had enlisted in a company that was forming there. When he had returned home his mother was milking the brindle cow. Four others stood waiting. “Ma, I’ve enlisted,” he had said to her diffidently. There was a short silence. “The Lord’s will be done, Henry,” she had finally replied, and had then continued to milk the brindle cow.

	When he had stood in the doorway with his soldier’s clothes on his back, and with the light of excitement and expectancy in his eyes almost defeating the glow of regret for the home bonds, he had seen two tears leaving their trails on his mother’s scarred cheeks.

	Still, she had disappointed him by saying nothing whatever about returning with his shield or on it. He had privately primed himself for a beautiful scene. He had prepared certain sentences which he thought could be used with touching effect. But her words destroyed his plans. She had doggedly peeled potatoes and addressed him as follows: “You watch out, Henry, an’ take good care of yerself in this here fighting business—you watch, an’ take good care of yerself. Don’t go a-thinkin’ you can lick the hull rebel army at the start, because yeh can’t. Yer jest one little feller amongst a hull lot of others, and yeh’ve got to keep quiet an’ do what they tell yeh. I know how you are, Henry.

	“I’ve knet yeh eight pair of socks, Henry, and I’ve put in all yer best shirts, because I want my boy to be jest as warm and comf’able as anybody in the army. Whenever they get holes in ‘em, I want yeh to send ‘em right-away back to me, so’s I kin dern ‘em.

	“An’ allus be careful an’ choose yer comp’ny. There’s lots of bad men in the army, Henry. The army makes ‘em wild, and they like nothing better than the job of leading off a young feller like you, as ain’t never been away from home much and has allus had a mother, an’ a-learning ‘em to drink and swear. Keep clear of them folks, Henry. I don’t want yeh to ever do anything, Henry, that yeh would be ‘shamed to let me know about. Jest think as if I was a-watchin’ yeh. If yeh keep that in yer mind allus, I guess yeh’ll come out about right.

	“Yeh must allus remember yer father, too, child, an’ remember he never drunk a drop of licker in his life, and seldom swore a cross oath.

	“I don’t know what else to tell yeh, Henry, excepting that yeh must never do no shirking, child, on my account. If so be a time comes when yeh have to be kilt of do a mean thing, why, Henry, don’t think of anything ‘cept what’s right, because there’s many a woman has to bear up ‘ginst sech things these times, and the Lord ‘ll take keer of us all.

	“Don’t forgit about the socks and the shirts, child; and I’ve put a cup of blackberry jam with yer bundle, because I know yeh like it above all things. Good-by, Henry. Watch out, and be a good boy.”

	He had, of course, been impatient under the ordeal of this speech. It had not been quite what he expected, and he had borne it with an air of irritation. He departed feeling vague relief.

	Still, when he had looked back from the gate, he had seen his mother kneeling among the potato parings. Her brown face, upraised, was stained with tears, and her spare form was quivering. He bowed his head and went on, feeling suddenly ashamed of his purposes.

	From his home he had gone to the seminary to bid adieu to many schoolmates. They had thronged about him with wonder and admiration. He had felt the gulf now between them and had swelled with calm pride. He and some of his fellows who had donned blue were quite overwhelmed with privileges for all of one afternoon, and it had been a very delicious thing. They had strutted.

	A certain light-haired girl had made vivacious fun at his martial spirit, but there was another and darker girl whom he had gazed at steadfastly, and he thought she grew demure and sad at sight of his blue and brass. As he had walked down the path between the rows of oaks, he had turned his head and detected her at a window watching his departure. As he perceived her, she had immediately begun to stare up through the high tree branches at the sky. He had seen a good deal of flurry and haste in her movement as she changed her attitude. He often thought of it.

	On the way to Washington his spirit had soared. The regiment was fed and caressed at station after station until the youth had believed that he must be a hero. There was a lavish expenditure of bread and cold meats, coffee, and pickles and cheese. As he basked in the smiles of the girls and was patted and complimented by the old men, he had felt growing within him the strength to do mighty deeds of arms.

	After complicated journeyings with many pauses, there had come months of monotonous life in a camp. He had had the belief that real war was a series of death struggles with small time in between for sleep and meals; but since his regiment had come to the field the army had done little but sit still and try to keep warm.

	He was brought then gradually back to his old ideas. Greeklike struggles would be no more. Men were better, or more timid. Secular and religious education had effaced the throat-grappling instinct, or else firm finance held in check the passions.

	He had grown to regard himself merely as a part of a vast blue demonstration. His province was to look out, as far as he could, for his personal comfort. For recreation he could twiddle his thumbs and speculate on the thoughts which must agitate the minds of the generals. Also, he was drilled and drilled and reviewed, and drilled and drilled and reviewed.

	The only foes he had seen were some pickets along the river bank. They were a sun-tanned, philosophical lot, who sometimes shot reflectively at the blue pickets. When reproached for this afterward, they usually expressed sorrow, and swore by their gods that the guns had exploded without their permission. The youth, on guard duty one night, conversed across the stream with one of them. He was a slightly ragged man, who spat skillfully between his shoes and possessed a great fund of bland and infantile assurance. The youth liked him personally.

	“Yank,” the other had informed him, “yer a right dum good feller.” This sentiment, floating to him upon the still air, had made him temporarily regret war.

	Various veterans had told him tales. Some talked of gray, bewhiskered hordes who were advancing with relentless curses and chewing tobacco with unspeakable valor; tremendous bodies of fierce soldiery who were sweeping along like the Huns. Others spoke of tattered and eternally hungry men who fired despondent powders. “They’ll charge through hell’s fire an’ brimstone t’ git a holt on a haversack, an’ sech stomachs ain’t a’lastin’ long,” he was told. From the stories, the youth imagined the red, live bones sticking out through slits in the faded uniforms.

	Still, he could not put a whole faith in veteran’s tales, for recruits were their prey. They talked much of smoke, fire, and blood, but he could not tell how much might be lies. They persistently yelled “Fresh fish!” at him, and were in no wise to be trusted.

	However, he perceived now that it did not greatly matter what kind of soldiers he was going to fight, so long as they fought, which fact no one disputed. There was a more serious problem. He lay in his bunk pondering upon it. He tried to mathematically prove to himself that he would not run from a battle.

	Previously he had never felt obliged to wrestle too seriously with this question. In his life he had taken certain things for granted, never challenging his belief in ultimate success, and bothering little about means and roads. But here he was confronted with a thing of moment. It had suddenly appeared to him that perhaps in a battle he might run. He was forced to admit that as far as war was concerned he knew nothing of himself.

	A sufficient time before he would have allowed the problem to kick its heels at the outer portals of his mind, but now he felt compelled to give serious attention to it.

	A little panic-fear grew in his mind. As his imagination went forward to a fight, he saw hideous possibilities. He contemplated the lurking menaces of the future, and failed in an effort to see himself standing stoutly in the midst of them. He recalled his visions of broken-bladed glory, but in the shadow of the impending tumult he suspected them to be impossible pictures.

	He sprang from the bunk and began to pace nervously to and fro. “Good Lord, what’s th’ matter with me?” he said aloud.

	He felt that in this crisis his laws of life were useless. Whatever he had learned of himself was here of no avail. He was an unknown quantity. He saw that he would again be obliged to experiment as he had in early youth. He must accumulate information of himself, and meanwhile he resolved to remain close upon his guard lest those qualities of which he knew nothing should everlastingly disgrace him. “Good Lord!” he repeated in dismay.

	After a time the tall soldier slid dexterously through the hole. The loud private followed. They were wrangling.

	“That’s all right,” said the tall soldier as he entered. He waved his hand expressively. “You can believe me or not, jest as you like. All you got to do is sit down and wait as quiet as you can. Then pretty soon you’ll find out I was right.”

	His comrade grunted stubbornly. For a moment he seemed to be searching for a formidable reply. Finally he said: “Well, you don’t know everything in the world, do you?”

	“Didn’t say I knew everything in the world,” retorted the other sharply. He began to stow various articles snugly into his knapsack.

	The youth, pausing in his nervous walk, looked down at the busy figure. “Going to be a battle, sure, is there, Jim?” he asked.

	“Of course there is,” replied the tall soldier. “Of course there is. You jest wait ‘til to-morrow, and you’ll see one of the biggest battles ever was. You jest wait.”

	“Thunder!” said the youth.

	“Oh, you’ll see fighting this time, my boy, what’ll be regular out-and-out fighting,” added the tall soldier, with the air of a man who is about to exhibit a battle for the benefit of his friends.

	“Huh!” said the loud one from a corner.

	“Well,” remarked the youth, “like as not this story’ll turn out jest like them others did.”

	“Not much it won’t,” replied the tall soldier, exasperated. “Not much it won’t. Didn’t the cavalry all start this morning?” He glared about him. No one denied his statement. “The cavalry started this morning,” he continued. “They say there ain’t hardly any cavalry left in camp. They’re going to Richmond, or some place, while we fight all the Johnnies. It’s some dodge like that. The regiment’s got orders, too. A feller what seen ‘em go to headquarters told me a little while ago. And they’re raising blazes all over camp—anybody can see that.”

	“Shucks!” said the loud one.

	The youth remained silent for a time. At last he spoke to the tall soldier. “Jim!”

	“What?”

	“How do you think the reg’ment ‘ll do?”

	“Oh, they’ll fight all right, I guess, after they once get into it,” said the other with cold judgment. He made a fine use of the third person. “There’s been heaps of fun poked at ‘em because they’re new, of course, and all that; but they’ll fight all right, I guess.”

	“Think any of the boys ‘ll run?” persisted the youth.

	“Oh, there may be a few of ‘em run, but there’s them kind in every regiment, ‘specially when they first goes under fire,” said the other in a tolerant way. “Of course it might happen that the hull kit-and-boodle might start and run, if some big fighting came first-off, and then again they might stay and fight like fun. But you can’t bet on nothing. Of course they ain’t never been under fire yet, and it ain’t likely they’ll lick the hull rebel army all-to-oncet the first time; but I think they’ll fight better than some, if worse than others. That’s the way I figger. They call the reg’ment ‘Fresh fish’ and everything; but the boys come of good stock, and most of ‘em ‘ll fight like sin after they oncet git shootin’,” he added, with a mighty emphasis on the last four words.

	“Oh, you think you know—” began the loud soldier with scorn.

	The other turned savagely upon him. They had a rapid altercation, in which they fastened upon each other various strange epithets.

	The youth at last interrupted them. “Did you ever think you might run yourself, Jim?” he asked. On concluding the sentence he laughed as if he had meant to aim a joke. The loud soldier also giggled.

	The tall private waved his hand. “Well”, said he profoundly, “I’ve thought it might get too hot for Jim Conklin in some of them scrimmages, and if a whole lot of boys started and run, why, I s’pose I’d start and run. And if I once started to run, I’d run like the devil, and no mistake. But if everybody was a-standing and a-fighting, why, I’d stand and fight. Be jiminey, I would. I’ll bet on it.”

	“Huh!” said the loud one.

	The youth of this tale felt gratitude for these words of his comrade. He had feared that all of the untried men possessed great and correct confidence. He now was in a measure reassured.

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/176/the-red-badge-of-courage/3196/chapter-1/.

Lit2Go: The Red Badge of Courage

Chapter 1


text:
package org.apache.avro.protobuf;

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Map;
import java.util.IdentityHashMap;
import java.util.concurrent.ConcurrentHashMap;

import java.io.IOException;
import java.io.File;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.generic.GenericData;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.DescriptorProtos.FileOptions;

import org.apache.avro.util.ClassUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;

/** Utilities for serializing Protobuf data in Avro format. */
public class ProtobufData extends GenericData {
  private static final String PROTOBUF_TYPE = "protobuf";

  private static final ProtobufData INSTANCE = new ProtobufData();

  protected ProtobufData() {}

  /** Return the singleton instance. */
  public static ProtobufData get() { return INSTANCE; }

  @Override
  public DatumReader createDatumReader(Schema schema) {
    return new ProtobufDatumReader(schema, schema, this);
  }

  @Override
  public DatumWriter createDatumWriter(Schema schema) {
    return new ProtobufDatumWriter(schema, this);
  }

  @Override
  public void setField(Object r, String n, int pos, Object o) {
    setField(r, n, pos, o, getRecordState(r, getSchema(r.getClass())));
  }

  @Override
  public Object getField(Object r, String name, int pos) {
    return getField(r, name, pos, getRecordState(r, getSchema(r.getClass())));
  }

  @Override
  protected void setField(Object r, String n, int pos, Object o, Object state) {
    Builder b = (Builder)r;
    FieldDescriptor f = ((FieldDescriptor[])state)[pos];
    switch (f.getType()) {
    case MESSAGE:
      if (o == null) {
        b.clearField(f);
        break;
      }
    default:
      b.setField(f, o);
    }
  }

  @Override
  protected Object getField(Object record, String name, int pos, Object state) {
    Message m = (Message)record;
    FieldDescriptor f = ((FieldDescriptor[])state)[pos];
    switch (f.getType()) {
    case MESSAGE:
      if (!f.isRepeated() && !m.hasField(f))
        return null;
    default:
      return m.getField(f);
    }
  }

  private final Map<Descriptor,FieldDescriptor[]> fieldCache =
    new ConcurrentHashMap<Descriptor,FieldDescriptor[]>();

  @Override
  protected Object getRecordState(Object r, Schema s) {
    Descriptor d = ((MessageOrBuilder)r).getDescriptorForType();
    FieldDescriptor[] fields = fieldCache.get(d);
    if (fields == null) {                         // cache miss
      fields = new FieldDescriptor[s.getFields().size()];
      for (Field f : s.getFields())
        fields[f.pos()] = d.findFieldByName(f.name());
      fieldCache.put(d, fields);                  // update cache
    }
    return fields;
  }

  @Override
  protected boolean isRecord(Object datum) {
    return datum instanceof Message;
  }

  @Override
  public Object newRecord(Object old, Schema schema) {
    try {
      Class c = ClassUtils.forName(SpecificData.getClassName(schema));
      if (c == null)
        return newRecord(old, schema);            // punt to generic
      if (c.isInstance(old))
        return old;                               // reuse instance
      return c.getMethod("newBuilder").invoke(null);

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  protected boolean isArray(Object datum) {
    return datum instanceof List;
  }

  @Override
  protected boolean isBytes(Object datum) {
    return datum instanceof ByteString;
  }

  @Override
  protected Schema getRecordSchema(Object record) {
    return getSchema(((Message)record).getDescriptorForType());
  }

  private final Map<Class,Schema> schemaCache
    = new ConcurrentHashMap<Class,Schema>();

  /** Return a record schema given a protobuf message class. */
  public Schema getSchema(Class c) {
    Schema schema = schemaCache.get(c);

    if (schema == null) {                         // cache miss
      try {
        Object descriptor = c.getMethod("getDescriptor").invoke(null);
        if (c.isEnum())
          schema = getSchema((EnumDescriptor)descriptor);
        else
          schema = getSchema((Descriptor)descriptor);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      schemaCache.put(c, schema);                 // update cache
    }
    return schema;
  }

  private static final ThreadLocal<Map<Descriptor,Schema>> SEEN
    = new ThreadLocal<Map<Descriptor,Schema>>() {
    protected Map<Descriptor,Schema> initialValue() {
      return new IdentityHashMap<Descriptor,Schema>();
    }
  };

  private Schema getSchema(Descriptor descriptor) {
    Map<Descriptor,Schema> seen = SEEN.get();
    if (seen.containsKey(descriptor))             // stop recursion
      return seen.get(descriptor);
    boolean first = seen.isEmpty();
    try {
      Schema result =
        Schema.createRecord(descriptor.getName(), null,
                            getNamespace(descriptor.getFile(),
                                         descriptor.getContainingType()),
                            false);

      seen.put(descriptor, result);

      List<Field> fields = new ArrayList<Field>();
      for (FieldDescriptor f : descriptor.getFields())
        fields.add(new Field(f.getName(), getSchema(f), null, getDefault(f)));
      result.setFields(fields);
      return result;

    } finally {
      if (first)
        seen.clear();
    }
  }

  private String getNamespace(FileDescriptor fd, Descriptor containing) {
    FileOptions o = fd.getOptions();
    String p = o.hasJavaPackage()
      ? o.getJavaPackage()
      : fd.getPackage();
    String outer;
    if (o.hasJavaOuterClassname()) {
      outer = o.getJavaOuterClassname();
    } else {
      outer = new File(fd.getName()).getName();
      outer = outer.substring(0, outer.lastIndexOf('.'));
      outer = toCamelCase(outer);
    }
    String inner = "";
    while (containing != null) {
      inner = containing.getName() + "$" + inner;
      containing = containing.getContainingType();
    }
    return p + "." + outer + "$" + inner;
  }

  private static String toCamelCase(String s){
    String[] parts = s.split("_");
    String camelCaseString = "";
    for (String part : parts) {
      camelCaseString = camelCaseString + cap(part);
    }
    return camelCaseString;
  }

  private static String cap(String s) {
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
  }

  private static final Schema NULL = Schema.create(Schema.Type.NULL);

  private Schema getSchema(FieldDescriptor f) {
    Schema s = getNonRepeatedSchema(f);
    if (f.isRepeated())
      s = Schema.createArray(s);
    return s;
  }

  private Schema getNonRepeatedSchema(FieldDescriptor f) {
    Schema result;
    switch (f.getType()) {
    case BOOL:
      return Schema.create(Schema.Type.BOOLEAN);
    case FLOAT:
      return Schema.create(Schema.Type.FLOAT);
    case DOUBLE:
      return Schema.create(Schema.Type.DOUBLE);
    case STRING:
      Schema s = Schema.create(Schema.Type.STRING);
      GenericData.setStringType(s, GenericData.StringType.String);
      return s;
    case BYTES:
      return Schema.create(Schema.Type.BYTES);
    case INT32: case UINT32: case SINT32: case FIXED32: case SFIXED32:
      return Schema.create(Schema.Type.INT);
    case INT64: case UINT64: case SINT64: case FIXED64: case SFIXED64:
      return Schema.create(Schema.Type.LONG);
    case ENUM:
      return getSchema(f.getEnumType());
    case MESSAGE:
      result = getSchema(f.getMessageType());
      if (f.isOptional())
        // wrap optional record fields in a union with null
        result = Schema.createUnion(Arrays.asList(new Schema[] {NULL, result}));
      return result;
    case GROUP:                                   // groups are deprecated
    default:
      throw new RuntimeException("Unexpected type: "+f.getType());
    }
  }

  private Schema getSchema(EnumDescriptor d) {
    List<String> symbols = new ArrayList<String>();
    for (EnumValueDescriptor e : d.getValues()) {
      symbols.add(e.getName());
    }
    return Schema.createEnum(d.getName(), null,
                             getNamespace(d.getFile(), d.getContainingType()),
                             symbols);
  }

  private static final JsonFactory FACTORY = new JsonFactory();
  private static final ObjectMapper MAPPER = new ObjectMapper(FACTORY);
  private static final JsonNodeFactory NODES = JsonNodeFactory.instance;

  private JsonNode getDefault(FieldDescriptor f) {
    if (f.isRequired() || f.isRepeated())         // no default
      return null;

    if (f.hasDefaultValue()) {                    // parse spec'd default value
      Object value = f.getDefaultValue();
      switch (f.getType()) {
      case ENUM:
        value = ((EnumValueDescriptor)value).getName();
        break;
      }
      String json = toString(value);
      try {
        return MAPPER.readTree(FACTORY.createJsonParser(json));
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }

    switch (f.getType()) {                        // generate default for type
    case BOOL:
      return NODES.booleanNode(false);
    case FLOAT: case DOUBLE:
    case INT32: case UINT32: case SINT32: case FIXED32: case SFIXED32:
    case INT64: case UINT64: case SINT64: case FIXED64: case SFIXED64:
      return NODES.numberNode(0);
    case STRING: case BYTES:
      return NODES.textNode("");
    case ENUM:
      return NODES.textNode(f.getEnumType().getValues().get(0).getName());
    case MESSAGE:
      return NODES.nullNode();
    case GROUP:                                   // groups are deprecated
    default:
      throw new RuntimeException("Unexpected type: "+f.getType());
    }

  }

}


text:
package com.epam.parso.date;

import com.epam.parso.Column;
import com.epam.parso.SasFileReader;
import com.epam.parso.impl.SasFileReaderImpl;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import static org.assertj.core.api.Assertions.assertThat;

public class SasDateFormatTest {
    private static final Logger logger = LoggerFactory.getLogger(SasDateFormatTest.class);

    /**
     * Validate the "dataset.sas7bdat" file against the "dataset.tsv" file
     * checking both trimmed and not-trimmed dates.
     */
    private static void assertSasDateFormat(String dataset) throws Exception {
        assertSasDateFormat(dataset, true, false);
        assertSasDateFormat(dataset, false, false);
    }

    private static void assertSasDateFormatIgnoreSasRoundingBugs(String dataset) throws Exception {
        assertSasDateFormat(dataset, true, true);
        assertSasDateFormat(dataset, false, true);
    }

    private static void assertSasDateFormat(String dataset, boolean trim, boolean ignoreSasRoundingBugs) throws Exception {
        try (InputStream sasInputStream = new FileInputStream(
                "src/test/resources/dates/sas7bdat/" + dataset + ".sas7bdat");
             BufferedReader tsvReader = new BufferedReader(new FileReader(
                     "src/test/resources/dates/tsv/" + dataset + ".tsv"))
        ) {
            SasFileReader sasReader = new SasFileReaderImpl(sasInputStream, null,
                    trim ? OutputDateType.SAS_FORMAT_TRIM_EXPERIMENTAL : OutputDateType.SAS_FORMAT_EXPERIMENTAL);
            List<Column> columns = sasReader.getColumns();
            int row = 0;
            String line;
            int sasRoundingBugsCount = 0;
            while ((line = tsvReader.readLine()) != null) {
                row++;
                Object[] sasRow = sasReader.readNext();
                String[] tsvRow = line.split("\t", -1);
                assertThat(sasRow).withFailMessage("Same amount of columns").hasSameSizeAs(tsvRow);
                for (int col = 0; col < tsvRow.length; col++) {
                    final int row1 = row;
                    String expected = trim ? tsvRow[col].trim() : tsvRow[col];
                    String actual = Objects.toString(sasRow[col]);
                    Column column = columns.get(col);

                    if (!expected.equals(actual)) {
                        if (ignoreSasRoundingBugs) {
                            int expectedIntegralIndex = expected.lastIndexOf(':');
                            int expectedFractionIndex = expected.lastIndexOf('.');
                            String expectedIntegral = expectedIntegralIndex > 0 ?
                                    expected.substring(0, expectedIntegralIndex) : "0";
                            double expectedFraction = Double.parseDouble(
                                    expected.substring(expectedIntegralIndex + 1));

                            int actualIntegralIndex = actual.lastIndexOf(':');
                            int actualFractionIndex = actual.lastIndexOf('.');
                            String actualIntegral = actualIntegralIndex > 0 ?
                                    actual.substring(0, actualIntegralIndex) : "0";
                            double actualFraction = Double.parseDouble(
                                    actual.substring(actualIntegralIndex + 1));

                            int bugPosition = Math.max(
                                    expectedFractionIndex == -1 ? 0 : expected.length() - expectedFractionIndex - 1,
                                    actualFractionIndex == -1 ? 0 : actual.length() - actualFractionIndex - 1
                            );
                            if (expected.length() == actual.length()
                                    && expectedIntegral.equals(actualIntegral)
                                    && BigDecimal.valueOf(expectedFraction)
                                    .subtract(BigDecimal.valueOf(actualFraction))
                                    .abs()
                                    .movePointRight(bugPosition)
                                    .compareTo(BigDecimal.ONE) == 0) {

                                sasRoundingBugsCount += 1;
                                logger.debug("Rounding bug ignored (fraction {} vs. {})\n"
                                                + "Row: {}, column: {}, format: {}\nexpected: {}\nactual: {}",
                                        expectedFraction, actualFraction,
                                        row1, column.getName(), column.getFormat(),
                                        expected, actual);
                                continue;
                            }
                        }

                        assertThat(actual).withFailMessage(() -> String.format(
                                "Row: #%d, column: [%s], format: [%s]\nexpected: [%s]\nactual: [%s]\n",
                                row1, column.getName(), column.getFormat(),
                                expected, actual)
                        ).isEqualTo(expected);
                    }
                }
            }
            if (sasRoundingBugsCount > 0) {
                logger.warn("Ignored [{}] ([{}%]) SAS rounding bugs for [{}]",
                        sasRoundingBugsCount,
                        Math.round(10000.0 * sasRoundingBugsCount / row / columns.size()) / 100.0,
                        dataset);
            }
            assertThat(sasReader.readNext()).withFailMessage("All rows are read").isNull();
        }
    }

    // Date formats
    @Test
    public void testDATE() throws Exception {
        assertSasDateFormat("date_format_date");
    }

    @Test
    public void testDDMMYY() throws Exception {
        assertSasDateFormat("date_format_ddmmyy");
    }

    @Test
    public void testMMDDYY() throws Exception {
        assertSasDateFormat("date_format_mmddyy");
    }

    @Test
    public void testYYMMDD() throws Exception {
        assertSasDateFormat("date_format_yymmdd");
    }

    @Test
    public void testMMYY() throws Exception {
        assertSasDateFormat("date_format_mmyy");
    }

    @Test
    public void testYYMM() throws Exception {
        assertSasDateFormat("date_format_yymm");
    }

    @Test
    public void testDAY() throws Exception {
        assertSasDateFormat("date_format_day");
    }

    @Test
    public void testJULDAY() throws Exception {
        assertSasDateFormat("date_format_julday");
    }

    @Test
    public void testJULIAN() throws Exception {
        assertSasDateFormat("date_format_julian");
    }

    @Test
    public void testMONTH() throws Exception {
        assertSasDateFormat("date_format_month");
    }

    @Test
    public void testYEAR() throws Exception {
        assertSasDateFormat("date_format_year");
    }

    @Test
    public void testMONYY() throws Exception {
        assertSasDateFormat("date_format_monyy");
    }

    @Test
    public void testYYMON() throws Exception {
        assertSasDateFormat("date_format_yymon");
    }

    @Test
    public void testB8601DA() throws Exception {
        assertSasDateFormat("date_format_b8601da");
    }

    @Test
    public void testE8601DA() throws Exception {
        assertSasDateFormat("date_format_e8601da");
    }

    @Test
    public void testMONNAME() throws Exception {
        assertSasDateFormat("date_format_monname");
    }

    @Test
    public void testWEEKDAY() throws Exception {
        assertSasDateFormat("date_format_weekday");
    }

    @Test
    public void testDOWNAME() throws Exception {
        assertSasDateFormat("date_format_downame");
    }

    @Test
    public void testWORDDATE() throws Exception {
        assertSasDateFormat("date_format_worddate");
    }

    @Test
    public void testWORDDATX() throws Exception {
        assertSasDateFormat("date_format_worddatx");
    }

    @Test
    public void testWEEKDATE() throws Exception {
        assertSasDateFormat("date_format_weekdate");
    }

    @Test
    public void testWEEKDATX() throws Exception {
        assertSasDateFormat("date_format_weekdatx");
    }

    @Test
    public void testDTDATE() throws Exception {
        assertSasDateFormat("date_format_dtdate");
    }

    @Test
    public void testDTMONYY() throws Exception {
        assertSasDateFormat("date_format_dtmonyy");
    }

    @Test
    public void testDTYEAR() throws Exception {
        assertSasDateFormat("date_format_dtyear");
    }

    @Test
    public void testE8601DN() throws Exception {
        assertSasDateFormat("date_format_e8601dn");
    }

    @Test
    public void testB8601DN() throws Exception {
        assertSasDateFormat("date_format_b8601dn");
    }

    @Test
    public void testQTR() {
        assertThat(SasDateFormat.QTR.getDatePattern(1, 0)).isNull();
        assertThat(SasDateFormat.QTR.getFormatFunction(1, 0, true).apply(0D))
                .isEqualTo("01JAN60");
    }

    // Date-time formats
    @Test
    public void testDATETIME() throws Exception {
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_datetime");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_datetime_loop");
    }

    @Test
    public void testB8601DT() {
        assertThat(SasDateTimeFormat.B8601DT.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.B8601DT.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testB8601DX() {
        assertThat(SasDateTimeFormat.B8601DX.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.B8601DX.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testB8601DZ() {
        assertThat(SasDateTimeFormat.B8601DZ.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.B8601DZ.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testB8601LX() {
        assertThat(SasDateTimeFormat.B8601LX.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.B8601LX.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testE8601DT() {
        assertThat(SasDateTimeFormat.E8601DT.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.E8601DT.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testE8601DX() {
        assertThat(SasDateTimeFormat.E8601DX.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.E8601DX.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testE8601DZ() {
        assertThat(SasDateTimeFormat.E8601DZ.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.E8601DZ.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testE8601LX() {
        assertThat(SasDateTimeFormat.E8601LX.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.E8601LX.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testDATEAMPM() {
        assertThat(SasDateTimeFormat.DATEAMPM.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.DATEAMPM.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testDTWKDATX() {
        assertThat(SasDateTimeFormat.DTWKDATX.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.DTWKDATX.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testMDYAMPM() {
        assertThat(SasDateTimeFormat.MDYAMPM.getDatePattern(1, 0)).isNull();
        assertThat(SasDateTimeFormat.MDYAMPM.getFormatFunction(1, 0, true).apply(1.1))
                .isEqualTo("01JAN60:00:00:01");
    }

    @Test
    public void testTOD() throws Exception {
        assertThat(SasDateTimeFormat.TOD.getDatePattern(1, 0)).isNull();
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_tod");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_tod_loop");
    }

    // Time formats
    @Test
    public void testE8601TM() throws Exception {
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_e8601tm");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_e8601tm_loop");
    }

    @Test
    public void testTIME() throws Exception {
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_time");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_time_loop");
    }

    @Test
    public void testHHMM() throws Exception {
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_hhmm");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_hhmm_loop");
    }

    @Test
    public void testMMSS() throws Exception {
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_mmss");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_mmss_loop");
    }

    @Test
    public void testHOUR() throws Exception {
        assertSasDateFormat("date_format_hour");
        assertSasDateFormatIgnoreSasRoundingBugs("date_format_hour_loop");
    }

    @Test
    public void testTIMEAMPM() {
        assertThat(SasTimeFormat.TIMEAMPM.getFormatFunction(1, 0, true).apply(0D))
                .isEqualTo("0:00:00");
    }

    @Test
    public void testE8601LZ() {
        assertThat(SasTimeFormat.E8601LZ.getFormatFunction(1, 0, true).apply(0D))
                .isEqualTo("0:00:00");
    }

    // Other tests
    @Test
    public void testLeapDays() throws Exception {
        assertSasDateFormat("date_leap_days");
    }

    /**
     * QTRR format not declared in date-time enums,
     * but there is a file with a such formatted value.
     * It is just used to check how app handles unknown format.
     */
    @Test(expected = AssertionError.class)
    public void testNotDeclaresFormat() throws Exception {
        assertSasDateFormat("date_format_qtrr");
    }

    @Test
    public void testNullDates() {
        assertThat(SasDateFormat.DATE.getFormatFunction(1, 0, true).apply(null)).isEqualTo(".");
        assertThat(SasDateTimeFormat.DATETIME.getFormatFunction(1, 0, true).apply(null)).isEqualTo(".");
        assertThat(SasTimeFormat.TIME.getFormatFunction(1, 0, true).apply(null)).isEqualTo(".");
    }
}


text:
from django.conf.urls.defaults import *
import views

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    (r'^$', views.index),
    (r'contour$', views.contour),
    (r'^js/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/home/brandon/projects/graphserver/apps/transitshed/frontend/transitshed/js'}),

    # Example:
    # (r'^transitshed/', include('transitshed.foo.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # (r'^admin/(.*)', admin.site.root),
)


text:
from roulette import roulette
from roulette.policy.shift import *

def person_on_duty(cands):
    ret = True
    rl = roulette.Roulette(shift_policy, cands)

    for index, guy in enumerate(cands):
        ret = False if guy != rl.lottery() else ret

    # Test for cycle
    for index, guy in enumerate(cands):
        ret = False if guy != rl.lottery() else ret

    return ret


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class s_Hud_Flickr : MonoBehaviour
{
  public float SwitchTime = 0.8f;
  private float _nextTime = 0;
  private bool _active = true;
  private Behaviour img;
	// Use this for initialization
	void Start ()
	{
    if (GetComponent<RawImage>() !=null)
	  img = GetComponent<RawImage>();
    if (GetComponent<Text>() != null)
      img = GetComponent<Text>();
	}

	// Update is called once per frame
	void Update () {
	  if (Time.time > _nextTime)
	  {
	    _nextTime = Time.time + SwitchTime;
	      _active = !_active;
	    img.enabled = _active;
	  }
	}
}


text:
	#include <stdio.h>

#define DICT_KEY_TYPE		char*
#define DICT_VALUE_TYPE		int
#include <dict.h>

static int dict_key_allocator_si(char* key, char** key_dup)
{
	*key_dup = strdup(key);
	return 0;
}

static int dict_value_allocator_si(int value, int* value_dup)
{
	*value_dup = value;
	return 0;
}

static int dict_key_deallocator_si(char* key)
{
	free(key);
	return 0;
}

static int dict_value_deallocator_si(int value)
{
	return 0;
}

static int dict_key_comparator_si(char* key_1, char* key_2)
{
	return strcmp(key_1, key_2);
}

static void dict_key_printor_si(char* key)
{
	printf("'%s'", key);
}

static void dict_value_printor_si(int value)
{
	printf("%d", value);
}

dict_context_si_t* dict_new_si(void)
{
	return dict_new_length_si(DICT_LENGTH_DEFAULT);
}

dict_context_si_t* dict_new_length_si(size_t length)
{
	return dict_new(length,
		dict_key_allocator_si, dict_value_allocator_si,
		dict_key_deallocator_si, dict_value_deallocator_si,
		dict_key_comparator_si,
		dict_key_printor_si, dict_value_printor_si);
}

void dict_delete_si(dict_context_si_t* context)
{
	dict_delete(context);
}

dict_context_si_t* dict_retain_si(dict_context_si_t* context)
{
	return dict_retain(context);
}

size_t dict_retain_count_si(dict_context_si_t* context)
{
	return dict_retain_count(context);
}

dict_context_si_t* dict_copy_si(dict_context_si_t* context)
{
	return dict_copy(context);
}

int dict_set_si(dict_context_si_t* context, char* key, int value)
{
	return dict_set(context, key, value);
}

int dict_get_si(dict_context_si_t* context, char* key, int* value)
{
	return dict_get(context, key, value);
}

int dict_remove_si(dict_context_si_t* context, char* key)
{
	return dict_remove(context, key);
}

int dict_clear_si(dict_context_si_t* context)
{
	return dict_clear(context);
}

int dict_has_key_si(dict_context_si_t* context, char* key)
{
	return dict_has_key(context, key);
}

size_t dict_count_si(dict_context_si_t* context)
{
	return dict_count(context);
}

dict_iter_si_t* dict_iter_new_si(dict_context_si_t* context)
{
	return dict_iter_new(context);
}

int dict_iter_get_si(dict_iter_si_t* iter, char** key, int* value)
{
	return dict_iter_get(iter, key, value);
}

void dict_iter_delete_si(dict_iter_si_t* iter)
{
	dict_iter_delete(iter);
}

void dict_print_si(dict_context_si_t* context)
{
	dict_print(context);
}


text:
layout: single
author_profile: false
---

If Deep Learning Toolbox Model for AlexNet Network support package is not installed, then the function provides a link to the required support package in the Add-On Explorer. To install the support package, click the link, and then click Install. Check that the installation is successful by typing alexnet at the command line.
[Details](https://www.mathworks.com/help/deeplearning/ref/alexnet.html#bvnyo6s)

Above instructions cannot be used in cluster environment. To install support packages from command line, one needs to
1. Download and run the file from the URL below [url](https://www.mathworks.com/support/install/support-software-downloader.html?s_tid=srchtitle) NOTE: I run this file from my Windows PC since it needs a GUI. Once the software starts, you can select the Support Package from the list.
1. Login to a MathWorks account when prompted
1. Select and Download the Support Software
1. Move the files to the target machine
1. Make sure X11 is working
1. <MATLAB root directory>/bin/glnxa64/SupportSoftwareInstaller -downloadfolder <pathtodownloadfolder> -inputFile <pathtoinputFile>/ssi_input.txt
Example:
```bash
[root@login.crane glnxa64]# ./install_supportsoftware.sh -matlabroot /util/opt/matlab/r2019b -archives /work/swanson/jingchao/matlab/resnet50/archives/
Starting Support Package Installation...
MATLAB is selecting SOFTWARE OPENGL rendering.
[1029/134627.838537:INFO:context.cpp(159)] Using multi-threaded message loop for Linux
Finished

```

Userful links:
[How do I silently install Support Packages in MATLAB R2018a or newer?](https://www.mathworks.com/matlabcentral/answers/389223-how-do-i-silently-install-support-packages-in-matlab-r2018a-or-newer)
[How do I download Hardware Support Packages and Optional Features for installation on a computer that is offline or that is behind a Proxy/Firewall?](https://www.mathworks.com/matlabcentral/answers/293235-how-do-i-download-hardware-support-packages-and-optional-features-for-installation-on-a-computer-tha)


text:
package org.apache.commons.vfs2.provider;

import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;

/**
 * A file name that represents a 'generic' URI, as per RFC 2396.  Consists of
 * a scheme, userinfo (typically username and password), hostname, port, and
 * path.
 *
 * @author Commons VFS team
 * @version $Revision$ $Date$
 */
public class GenericFileName extends AbstractFileName
{
    private static final char[] USERNAME_RESERVED = {':', '@', '/'};
    private static final char[] PASSWORD_RESERVED = {'@', '/', '?'};
    private final String userName;
    private final String hostName;
    private final int defaultPort;
    private final String password;
    private final int port;

    protected GenericFileName(final String scheme,
                              final String hostName,
                              final int port,
                              final int defaultPort,
                              final String userName,
                              final String password,
                              final String path,
                              final FileType type
    )
    {
        super(scheme, path, type);
        this.hostName = hostName;
        this.defaultPort = defaultPort;
        this.password = password;
        this.userName = userName;
        if (port > 0)
        {
            this.port = port;
        }
        else
        {
            this.port = getDefaultPort();
        }
    }

    /**
     * Returns the user name part of this name.
     * @return The user name.
     */
    public String getUserName()
    {
        return userName;
    }

    /**
     * Returns the password part of this name.
     * @return The password.
     */
    public String getPassword()
    {
        return password;
    }

    /**
     * Returns the host name part of this name.
     * @return The host name.
     */
    public String getHostName()
    {
        return hostName;
    }

    /**
     * Returns the port part of this name.
     * @return The port number.
     */
    public int getPort()
    {
        return port;
    }

    /**
     * Returns the default port for this file name.
     * @return The default port number.
     */
    public int getDefaultPort()
    {
        return defaultPort;
    }

    /**
     * Create a FileName.
     * @param absPath The absolute path.
     * @param type The FileType.
     * @return The created FileName.
     */
    @Override
    public FileName createName(String absPath, FileType type)
    {
        return new GenericFileName(
            getScheme(),
            hostName,
            port,
            defaultPort,
            userName,
            password,
            absPath,
            type);
    }

    /**
     * Builds the root URI for this file name.
     */
    @Override
    protected void appendRootUri(final StringBuilder buffer, boolean addPassword)
    {
        buffer.append(getScheme());
        buffer.append("://");
        appendCredentials(buffer, addPassword);
        buffer.append(hostName);
        if (port != getDefaultPort())
        {
            buffer.append(':');
            buffer.append(port);
        }
    }

    /**
     * append the user credentials
     */
    protected void appendCredentials(StringBuilder buffer, boolean addPassword)
    {
        if (userName != null && userName.length() != 0)
        {
            UriParser.appendEncoded(buffer, userName, USERNAME_RESERVED);
            if (password != null && password.length() != 0)
            {
                buffer.append(':');
                if (addPassword)
                {
                    UriParser.appendEncoded(buffer, password, PASSWORD_RESERVED);
                }
                else
                {
                    buffer.append("***");
                }
            }
            buffer.append('@');
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: mm
 * Date: 10/07/15
 * Time: 16:10
 */

namespace MM\ContentComponent\Serializer;

use MM\ContentComponent\Model;
use MM\Util\ClassUtil;

abstract class AbstractSerializer
{
    /**
     * @param array $options
     */
    public function __construct(array $options = null)
    {
        if ($options) {
            ClassUtil::setOptions($this, $options);
        }
        $this->_init();
    }

    /**
     *
     */
    protected function _init()
    {
    }

    /**
     * @param Model $model
     * @param array $options
     * @return mixed
     */
    abstract public function serialize(Model $model, array $options = array());

    /**
     * @param $data
     * @param array $options
     * @return mixed
     */
    abstract public function unserialize($data, array $options = array());
}


text:
layout: event
categories: eventolocale
title:  "Voltian experience talks 1"
CL: Pavia
locandina: /img/eventilocali/2017-PV-VET/locandina.jpg
gallery:
report:
facebook:
link:
---


text:
using System.Collections.Generic;
using Sanderling.Motor;
using BotEngine.Motor;
using Sanderling.Parse;

namespace Sanderling.ABot.Bot.Task
{
	public class EnableInfoPanelCurrentSystem : IBotTask
	{
		public IMemoryMeasurement MemoryMeasurement;

		public IEnumerable<IBotTask> Component => null;

		public MotionParam Motion
		{
			get
			{
				if (null != MemoryMeasurement?.InfoPanelCurrentSystem)
					return null;

				return MemoryMeasurement?.InfoPanelButtonCurrentSystem?.MouseClick(MouseButtonIdEnum.Left);
			}
		}
	}
}


text:
// Generated by CoffeeScript 1.9.3

var BETTER_TITLE, CLOSE_BROWSER, CLOSE_BROWSER_PATTERN, DEFAULT_TITLE, addCloseBrowserHook, closeBrowser, config, debug, deepMochaTimeouts, getBrowser, getRootSuite, injectBrowser, isCloseBrowserHook, path, setMochaTimeouts, takeScreenshotOnFailure;

path = require('path');

debug = require('debug')('testium:mocha');

config = require('../config');

getBrowser = require('../testium').getBrowser;

takeScreenshotOnFailure = require('./screenshot');

setMochaTimeouts = function(obj) {
  obj.timeout(+config.mocha.timeout);
  return obj.slow(+config.mocha.slow);
};

deepMochaTimeouts = function(suite) {
  setMochaTimeouts(suite);
  suite.suites.forEach(deepMochaTimeouts);
  suite.tests.forEach(setMochaTimeouts);
  suite._beforeEach.forEach(setMochaTimeouts);
  suite._beforeAll.forEach(setMochaTimeouts);
  suite._afterEach.forEach(setMochaTimeouts);
  return suite._afterAll.forEach(setMochaTimeouts);
};

closeBrowser = function(browser) {
  return function(done) {
    return browser.close(function(error) {
      if (error == null) {
        return done();
      }
      error.message = error.message + " (while closing browser)";
      return done(error);
    });
  };
};

CLOSE_BROWSER = 'closeBrowser';

CLOSE_BROWSER_PATTERN = /hook: closeBrowser$/;

isCloseBrowserHook = function(hook) {
  return CLOSE_BROWSER_PATTERN.test(hook.title);
};

addCloseBrowserHook = function(suite, browser) {
  if (suite._afterAll.some(isCloseBrowserHook)) {
    return;
  }
  return suite.afterAll(CLOSE_BROWSER, closeBrowser(browser));
};

getRootSuite = function(suite) {
  if (suite.parent) {
    return getRootSuite(suite.parent);
  } else {
    return suite;
  }
};

DEFAULT_TITLE = '"before all" hook';

BETTER_TITLE = '"before all" hook: Testium setup hook';

injectBrowser = function(options) {
  if (options == null) {
    options = {};
  }
  return function(done) {
    var initialTimeout, ref, reuseSession, suite;
    if (this._runnable.title === DEFAULT_TITLE) {
      this._runnable.title = BETTER_TITLE;
    }
    debug('Overriding mocha timeouts', config.mocha);
    suite = this._runnable.parent;
    deepMochaTimeouts(suite);
    initialTimeout = +((ref = config.app) != null ? ref.timeout : void 0) || 0;
    initialTimeout += +config.mocha.timeout;
    this.timeout(initialTimeout);
    reuseSession = options.reuseSession != null ? options.reuseSession : options.reuseSession = true;
    return getBrowser(options, (function(_this) {
      return function(err, browser1) {
        var afterEachHook, browserScopeSuite, screenshotDirectory;
        _this.browser = browser1;
        if (err != null) {
          return done(err);
        }
        screenshotDirectory = config.screenshotDirectory;
        if (screenshotDirectory) {
          screenshotDirectory = path.resolve(config.root, screenshotDirectory);
          afterEachHook = takeScreenshotOnFailure(screenshotDirectory);
          suite.afterEach('takeScreenshotOnFailure', afterEachHook);
        }
        browserScopeSuite = reuseSession ? getRootSuite(suite) : suite;
        addCloseBrowserHook(browserScopeSuite, _this.browser);
        return done();
      };
    })(this));
  };
};

module.exports = injectBrowser;


text:
<?php

namespace LucaDegasperi\OAuth2Server\Storage\Mongo;

use Illuminate\Support\ServiceProvider;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Storage\SessionInterface;

/**
 * This is the fluent storage service provider class.
 *
 * @author Luca Degasperi <packages@lucadegasperi.com>
 */
class FluentStorageServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerStorageBindings();
        $this->registerInterfaceBindings();
    }

    /**
     * Bind the storage implementations to the IoC container.
     *
     * @return void
     */
    public function registerStorageBindings()
    {
        $provider = $this;

        $this->app->bindShared(FluentAccessToken::class, function () use ($provider) {
            $storage = new FluentAccessToken($provider->app['db']);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });

        $this->app->bindShared(FluentAuthCode::class, function () use ($provider) {
            $storage = new FluentAuthCode($provider->app['db']);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });

        $this->app->bindShared(FluentClient::class, function ($app) use ($provider) {
            $limitClientsToGrants = $app['config']->get('oauth2.limit_clients_to_grants');
            $storage = new FluentClient($provider->app['db'], $limitClientsToGrants);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });

        $this->app->bindShared(FluentRefreshToken::class, function () use ($provider) {
            $storage = new FluentRefreshToken($provider->app['db']);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });

        $this->app->bindShared(FluentScope::class, function ($app) use ($provider) {
            $limitClientsToScopes = $app['config']->get('oauth2.limit_clients_to_scopes');
            $limitScopesToGrants = $app['config']->get('oauth2.limit_scopes_to_grants');
            $storage = new FluentScope($provider->app['db'], $limitClientsToScopes, $limitScopesToGrants);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });

        $this->app->bindShared(FluentSession::class, function () use ($provider) {
            $storage = new FluentSession($provider->app['db']);
            $storage->setConnectionName($provider->getConnectionName());

            return $storage;
        });
    }

    /**
     * Bind the interfaces to their implementations.
     *
     * @return void
     */
    public function registerInterfaceBindings()
    {
        $this->app->bind(ClientInterface::class, FluentClient::class);
        $this->app->bind(ScopeInterface::class, FluentScope::class);
        $this->app->bind(SessionInterface::class, FluentSession::class);
        $this->app->bind(AuthCodeInterface::class, FluentAuthCode::class);
        $this->app->bind(AccessTokenInterface::class, FluentAccessToken::class);
        $this->app->bind(RefreshTokenInterface::class, FluentRefreshToken::class);
    }

    /**
     * @return string
     */
    public function getConnectionName()
    {
        return ($this->app['config']->get('oauth2.database') !== 'default') ? $this->app['config']->get('oauth2.database') : null;
    }
}


text:
<?php

/**
 * API module for sending out RSD information
 * @ingroup API
 */
class ApiRsd extends ApiBase {

	public function execute() {
		$result = $this->getResult();

		$result->addValue( null, 'version', '1.0' );
		$result->addValue( null, 'xmlns', 'http://archipelago.phrasewise.com/rsd' );

		$service = array(
			'apis' => $this->formatRsdApiList(),
			'engineName' => 'MediaWiki',
			'engineLink' => 'https://www.mediawiki.org/',
			'homePageLink' => Title::newMainPage()->getCanonicalURL(),
		);

		ApiResult::setSubelementsList( $service, array( 'engineName', 'engineLink', 'homePageLink' ) );
		ApiResult::setIndexedTagName( $service['apis'], 'api' );

		$result->addValue( null, 'service', $service );
	}

	public function getCustomPrinter() {
		return new ApiFormatXmlRsd( $this->getMain(), 'xml' );
	}

	protected function getExamplesMessages() {
		return array(
			'action=rsd'
				=> 'apihelp-rsd-example-simple',
		);
	}

	public function isReadMode() {
		return false;
	}

	/**
	 * Builds an internal list of APIs to expose information about.
	 * Normally this only lists the MediaWiki API, with its base URL,
	 * link to documentation, and a marker as to available authentication
	 * (to aid in OAuth client apps switching to support in the future).
	 *
	 * Extensions can expose other APIs, such as WordPress or Twitter-
	 * compatible APIs, by hooking 'ApiRsdServiceApis' and adding more
	 * elements to the array.
	 *
	 * See http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html for
	 * the base RSD spec, and check WordPress and StatusNet sites for
	 * in-production examples listing several blogging and micrblogging
	 * APIs.
	 *
	 * @return array
	 */
	protected function getRsdApiList() {
		$apis = array(
			'MediaWiki' => array(
				// The API link is required for all RSD API entries.
				'apiLink' => wfExpandUrl( wfScript( 'api' ), PROTO_CURRENT ),

				// Docs link is optional, but recommended.
				'docs' => 'https://www.mediawiki.org/wiki/API',

				// Some APIs may need a blog ID, but it may be left blank.
				'blogID' => '',

				// Additional settings are optional.
				'settings' => array(
					// Change this to true in the future as an aid to
					// machine discovery of OAuth for API access.
					'OAuth' => false,
				)
			),
		);
		Hooks::run( 'ApiRsdServiceApis', array( &$apis ) );

		return $apis;
	}

	/**
	 * Formats the internal list of exposed APIs into an array suitable
	 * to pass to the API's XML formatter.
	 *
	 * @return array
	 */
	protected function formatRsdApiList() {
		$apis = $this->getRsdApiList();

		$outputData = array();
		foreach ( $apis as $name => $info ) {
			$data = array(
				'name' => $name,
				'preferred' => wfBoolToStr( $name == 'MediaWiki' ),
				'apiLink' => $info['apiLink'],
				'blogID' => isset( $info['blogID'] ) ? $info['blogID'] : '',
			);
			$settings = array();
			if ( isset( $info['docs'] ) ) {
				$settings['docs'] = $info['docs'];
				ApiResult::setSubelementsList( $settings, 'docs' );
			}
			if ( isset( $info['settings'] ) ) {
				foreach ( $info['settings'] as $setting => $val ) {
					if ( is_bool( $val ) ) {
						$xmlVal = wfBoolToStr( $val );
					} else {
						$xmlVal = $val;
					}
					$setting = array( 'name' => $setting );
					ApiResult::setContentValue( $setting, 'value', $xmlVal );
					$settings[] = $setting;
				}
			}
			if ( count( $settings ) ) {
				ApiResult::setIndexedTagName( $settings, 'setting' );
				$data['settings'] = $settings;
			}
			$outputData[] = $data;
		}

		return $outputData;
	}
}

class ApiFormatXmlRsd extends ApiFormatXml {
	public function __construct( ApiMain $main, $format ) {
		parent::__construct( $main, $format );
		$this->setRootElement( 'rsd' );
	}

	public function getMimeType() {
		return 'application/rsd+xml';
	}

	public static function recXmlPrint( $name, $value, $indent, $attributes = array() ) {
		unset( $attributes['_idx'] );
		return parent::recXmlPrint( $name, $value, $indent, $attributes );
	}
}


text:
window.onload = function(){ //on load event

var task1 = {
	render: function(){
		document.getElementById("screenX").textContent = window.screenX;
		document.getElementById("screenY").textContent = window.screenY;
		document.getElementById("screenWidth").textContent = window.innerWidth;
		document.getElementById("screenHeight").textContent = window.innerHeight;
		document.getElementById("location").textContent = window.location;

	},
	resize: function() {
		window.addEventListener("resize",this.render);
	}
};
task1.render();
task1.resize();
}; //end on load event


text:
package de.fzi.osh.wamp.device.battery;

/**
 * Request for battery state.
 *
 * @author K. Foerderer
 *
 */
public class GetBatteryStateRequest {
}


text:
GMap 1.x / Location 3.x Tester Checklist

Setup from scratch:

Enable modules

Visit admin/settings/gmap and configure API key.

Visit admin/settings/filters and set up a GMap filter.

Visit admin/content/types and (create if desired and) location-enable
        a content type.

Visit admin/settings/location/geocoding and configure
        geocoding for a country.

Visit admin/user/settings and configure the Location Fields section.

Visit admin/build/block and enable the Author Map and Location Map
        blocks.

Visit admin/build/block/configure/gmap_location/1
        and enable the Author block for the content type you location-enabled.

Tests 1 (GMap macros):

Visit map/macro, play with the controls and ensure map responds, play with map
        and ensure controls respond.

Doodle on the map, make sure drawing controls work as expected.

Copy macro, open another window/tab.

Create a node, set filter to GMap filter and paste macro.

Save node, compare display of map to macro in other window/tab.

Tests 2 (Location user):

Edit your user account. Add your location.

Ensure geocoding works.

Ensure the data is not lost when going back to edit.

Tests 3 (Location nodes):

Create a node with locative information.

Ensure Author Map and Location Map display as expected.

Advanced section - Stuff involving special setup or advanced knowledge

ADVANCED: Upgrade path:

Create test site on Location 2.7.

Perform tasks from "Setup from scratch" section.

Create or import test data.

Install Location 3.

Attempt to perform updates.

Ensure in database that data was properly split off into {location_instance}.

Ensure site settings are in a sane state (You should not get any misconfiguration-related warnings/errors.)

Visually inspect some locations on site.

ADVANCED: Nonstandard usage:

Disable gmap and create locative nodes. Ensure form continues to work in the absence of gmap.


text:
PHPUnit is the de facto standard unit test framework for PHP.

PHPUnit includes a native mocking framework yet offers also Prophecy mocking since version 4.5.

So how to choose between PHPUnit mocks and Prophecy mocks?


text:
noselector
==========

node selector