text:
package aop.aspect;

import org.springframework.stereotype.Component;

@Component
public class Calculator {
    public Integer add(Integer a, Integer b) {
        return a + b;
    }

    public Integer sub(Integer a, Integer b) {
        return a - b;
    }
}


text:
package org.compass.core.test.find.aliases1;

/**
 * @author kimchy
 */
public class A {

    private Long id;

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/** @module RETS */

module.exports = require('./lib/rets');


text:
module AsposeCellsCloud
  #
  class PdfSaveOptions < BaseObject
    attr_accessor :calculate_formula, :check_font_compatibility, :compliance, :default_font, :one_page_per_sheet, :printing_page_type, :desired_ppi, :jpeg_quality, :save_format, :cached_file_folder, :clear_data, :create_directory, :enable_http_compression, :refresh_chart_cache, :sort_names, :validate_merged_areas
    # attribute mapping from ruby-style variable name to JSON key
    def self.attribute_map
      {

        #
        :'calculate_formula' => :'CalculateFormula',

        #
        :'check_font_compatibility' => :'CheckFontCompatibility',

        #
        :'compliance' => :'Compliance',

        #
        :'default_font' => :'DefaultFont',

        #
        :'one_page_per_sheet' => :'OnePagePerSheet',

        #
        :'printing_page_type' => :'PrintingPageType',

        #
        :'desired_ppi' => :'desiredPPI',

        #
        :'jpeg_quality' => :'jpegQuality',

        #
        :'save_format' => :'SaveFormat',

        #
        :'cached_file_folder' => :'CachedFileFolder',

        #
        :'clear_data' => :'ClearData',

        #
        :'create_directory' => :'CreateDirectory',

        #
        :'enable_http_compression' => :'EnableHTTPCompression',

        #
        :'refresh_chart_cache' => :'RefreshChartCache',

        #
        :'sort_names' => :'SortNames',

        #
        :'validate_merged_areas' => :'ValidateMergedAreas'

      }
    end

    # attribute type
    def self.swagger_types
      {
        :'calculate_formula' => :'BOOLEAN',
        :'check_font_compatibility' => :'BOOLEAN',
        :'compliance' => :'String',
        :'default_font' => :'String',
        :'one_page_per_sheet' => :'BOOLEAN',
        :'printing_page_type' => :'String',
        :'desired_ppi' => :'String',
        :'jpeg_quality' => :'String',
        :'save_format' => :'String',
        :'cached_file_folder' => :'String',
        :'clear_data' => :'BOOLEAN',
        :'create_directory' => :'BOOLEAN',
        :'enable_http_compression' => :'BOOLEAN',
        :'refresh_chart_cache' => :'BOOLEAN',
        :'sort_names' => :'BOOLEAN',
        :'validate_merged_areas' => :'BOOLEAN'

      }
    end

    def initialize(attributes = {})
      return if !attributes.is_a?(Hash) || attributes.empty?

      # convert string to symbol for hash key
      attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

      if attributes[:'CalculateFormula']
        self.calculate_formula = attributes[:'CalculateFormula']
      end

      if attributes[:'CheckFontCompatibility']
        self.check_font_compatibility = attributes[:'CheckFontCompatibility']
      end

      if attributes[:'Compliance']
        self.compliance = attributes[:'Compliance']
      end

      if attributes[:'DefaultFont']
        self.default_font = attributes[:'DefaultFont']
      end

      if attributes[:'OnePagePerSheet']
        self.one_page_per_sheet = attributes[:'OnePagePerSheet']
      end

      if attributes[:'PrintingPageType']
        self.printing_page_type = attributes[:'PrintingPageType']
      end

      if attributes[:'desiredPPI']
        self.desired_ppi = attributes[:'desiredPPI']
      end

      if attributes[:'jpegQuality']
        self.jpeg_quality = attributes[:'jpegQuality']
      end

      if attributes[:'SaveFormat']
        self.save_format = attributes[:'SaveFormat']
      end

      if attributes[:'CachedFileFolder']
        self.cached_file_folder = attributes[:'CachedFileFolder']
      end

      if attributes[:'ClearData']
        self.clear_data = attributes[:'ClearData']
      end

      if attributes[:'CreateDirectory']
        self.create_directory = attributes[:'CreateDirectory']
      end

      if attributes[:'EnableHTTPCompression']
        self.enable_http_compression = attributes[:'EnableHTTPCompression']
      end

      if attributes[:'RefreshChartCache']
        self.refresh_chart_cache = attributes[:'RefreshChartCache']
      end

      if attributes[:'SortNames']
        self.sort_names = attributes[:'SortNames']
      end

      if attributes[:'ValidateMergedAreas']
        self.validate_merged_areas = attributes[:'ValidateMergedAreas']
      end

    end

  end
end


text:
package org.kie.workbench.common.dmn.backend.definition.v1_1;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import org.kie.workbench.common.dmn.api.definition.HasComponentWidths;
import org.kie.workbench.common.dmn.api.definition.v1_1.BusinessKnowledgeModel;
import org.kie.workbench.common.dmn.api.definition.v1_1.DRGElement;
import org.kie.workbench.common.dmn.api.definition.v1_1.Decision;
import org.kie.workbench.common.dmn.api.definition.v1_1.DecisionService;
import org.kie.workbench.common.dmn.api.definition.v1_1.Expression;
import org.kie.workbench.common.dmn.api.definition.v1_1.InformationItemPrimary;
import org.kie.workbench.common.dmn.api.definition.v1_1.InputData;
import org.kie.workbench.common.dmn.api.definition.v1_1.KnowledgeRequirement;
import org.kie.workbench.common.dmn.api.definition.v1_1.KnowledgeSource;
import org.kie.workbench.common.dmn.api.property.background.BackgroundSet;
import org.kie.workbench.common.dmn.api.property.dimensions.GeneralRectangleDimensionsSet;
import org.kie.workbench.common.dmn.api.property.dmn.AllowedAnswers;
import org.kie.workbench.common.dmn.api.property.dmn.Description;
import org.kie.workbench.common.dmn.api.property.dmn.Id;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.api.property.dmn.Question;
import org.kie.workbench.common.dmn.api.property.font.FontSet;
import org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ComponentWidths;
import org.kie.workbench.common.stunner.core.api.FactoryManager;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.relationship.Child;
import org.kie.workbench.common.stunner.core.graph.content.view.View;

public class DecisionConverter implements NodeConverter<org.kie.dmn.model.api.Decision, org.kie.workbench.common.dmn.api.definition.v1_1.Decision> {

    private FactoryManager factoryManager;

    public DecisionConverter(final FactoryManager factoryManager) {
        super();
        this.factoryManager = factoryManager;
    }

    @Override
    public Node<View<Decision>, ?> nodeFromDMN(final org.kie.dmn.model.api.Decision dmn,
                                               final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer) {
        @SuppressWarnings("unchecked")
        Node<View<Decision>, ?> node = (Node<View<Decision>, ?>) factoryManager.newElement(dmn.getId(),
                                                                                Decision.class).asNode();
        Id id = new Id(dmn.getId());
        Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription());
        Name name = new Name(dmn.getName());
        InformationItemPrimary informationItem = InformationItemPrimaryPropertyConverter.wbFromDMN(dmn.getVariable());
        Expression expression = ExpressionPropertyConverter.wbFromDMN(dmn.getExpression(),
                                                                      hasComponentWidthsConsumer);
        Decision decision = new Decision(id,
                                         description,
                                         name,
                                         new Question(),
                                         new AllowedAnswers(),
                                         informationItem,
                                         expression,
                                         new BackgroundSet(),
                                         new FontSet(),
                                         new GeneralRectangleDimensionsSet());
        decision.setQuestion(QuestionPropertyConverter.wbFromDMN(dmn.getQuestion()));
        decision.setAllowedAnswers(AllowedAnswersPropertyConverter.wbFromDMN(dmn.getAllowedAnswers()));
        node.getContent().setDefinition(decision);

        if (informationItem != null) {
            informationItem.setParent(decision);
        }
        if (expression != null) {
            expression.setParent(decision);
        }

        return node;
    }

    @Override
    public org.kie.dmn.model.api.Decision dmnFromNode(final Node<View<Decision>, ?> node,
                                                      final Consumer<ComponentWidths> componentWidthsConsumer) {
        Decision source = node.getContent().getDefinition();
        org.kie.dmn.model.api.Decision d = new org.kie.dmn.model.v1_2.TDecision();
        d.setId(source.getId().getValue());
        d.setDescription(DescriptionPropertyConverter.dmnFromWB(source.getDescription()));
        d.setName(source.getName().getValue());
        org.kie.dmn.model.api.InformationItem variable = InformationItemPrimaryPropertyConverter.dmnFromWB(source.getVariable());
        if (variable != null) {
            variable.setParent(d);
        }
        d.setVariable(variable);
        org.kie.dmn.model.api.Expression expression = ExpressionPropertyConverter.dmnFromWB(source.getExpression(),
                                                                                componentWidthsConsumer);
        if (expression != null) {
            expression.setParent(d);
        }
        d.setExpression(expression);
        d.setQuestion(QuestionPropertyConverter.dmnFromWB(source.getQuestion()));
        d.setAllowedAnswers(AllowedAnswersPropertyConverter.dmnFromWB(source.getAllowedAnswers()));
        // DMN spec table 2: Requirements connection rules
        List<Edge<?, ?>> inEdges = (List<Edge<?, ?>>) node.getInEdges();
        for (Edge<?, ?> e : inEdges) {
            Node<?, ?> sourceNode = e.getSourceNode();
            if (sourceNode.getContent() instanceof View<?>) {
                View<?> view = (View<?>) sourceNode.getContent();
                if (view.getDefinition() instanceof DRGElement) {
                    DRGElement drgElement = (DRGElement) view.getDefinition();
                    if (drgElement instanceof Decision) {
                        org.kie.dmn.model.api.InformationRequirement iReq = new org.kie.dmn.model.v1_2.TInformationRequirement();
                        iReq.setId(e.getUUID());
                        org.kie.dmn.model.api.DMNElementReference ri = new org.kie.dmn.model.v1_2.TDMNElementReference();
                        ri.setHref(new StringBuilder("#").append(drgElement.getId().getValue()).toString());
                        iReq.setRequiredDecision(ri);
                        d.getInformationRequirement().add(iReq);
                    } else if (drgElement instanceof BusinessKnowledgeModel) {
                        org.kie.dmn.model.api.KnowledgeRequirement iReq = new org.kie.dmn.model.v1_2.TKnowledgeRequirement();
                        iReq.setId(e.getUUID());
                        org.kie.dmn.model.api.DMNElementReference ri = new org.kie.dmn.model.v1_2.TDMNElementReference();
                        ri.setHref(new StringBuilder("#").append(drgElement.getId().getValue()).toString());
                        iReq.setRequiredKnowledge(ri);
                        d.getKnowledgeRequirement().add(iReq);
                    } else if (drgElement instanceof KnowledgeSource) {
                        org.kie.dmn.model.api.AuthorityRequirement iReq = new org.kie.dmn.model.v1_2.TAuthorityRequirement();
                        iReq.setId(e.getUUID());
                        org.kie.dmn.model.api.DMNElementReference ri = new org.kie.dmn.model.v1_2.TDMNElementReference();
                        ri.setHref(new StringBuilder("#").append(drgElement.getId().getValue()).toString());
                        iReq.setRequiredAuthority(ri);
                        d.getAuthorityRequirement().add(iReq);
                    } else if (drgElement instanceof InputData) {
                        org.kie.dmn.model.api.InformationRequirement iReq = new org.kie.dmn.model.v1_2.TInformationRequirement();
                        iReq.setId(e.getUUID());
                        org.kie.dmn.model.api.DMNElementReference ri = new org.kie.dmn.model.v1_2.TDMNElementReference();
                        ri.setHref(new StringBuilder("#").append(drgElement.getId().getValue()).toString());
                        iReq.setRequiredInput(ri);
                        d.getInformationRequirement().add(iReq);
                    } else if (drgElement instanceof DecisionService) {
                        if (e.getContent() instanceof Child) {
                            // Stunner relationship of this Decision be encapsulated by the DecisionService, not managed here.
                        } else if (e.getContent() instanceof View && ((View) e.getContent()).getDefinition() instanceof KnowledgeRequirement) {
                            org.kie.dmn.model.api.KnowledgeRequirement iReq = new org.kie.dmn.model.v1_2.TKnowledgeRequirement();
                            iReq.setId(e.getUUID());
                            org.kie.dmn.model.api.DMNElementReference ri = new org.kie.dmn.model.v1_2.TDMNElementReference();
                            ri.setHref(new StringBuilder("#").append(drgElement.getId().getValue()).toString());
                            iReq.setRequiredKnowledge(ri);
                            d.getKnowledgeRequirement().add(iReq);
                        } else {
                            throw new UnsupportedOperationException("wrong model definition.");
                        }
                    } else {
                        throw new UnsupportedOperationException("wrong model definition.");
                    }
                }
            }
        }
        return d;
    }
}


text:
namespace Fonet.Fo.Flow
{
    using Fonet.Layout;

    internal class FootnoteBody : FObj
    {
        private int align = 0;

        private int alignLast = 0;

        private int lineHeight = 0;

        private int startIndent = 0;

        private int endIndent = 0;

        private int textIndent = 0;

        new internal class Maker : FObj.Maker
        {
            public override FObj Make(FObj parent, PropertyList propertyList)
            {
                return new FootnoteBody(parent, propertyList);
            }
        }

        new public static FObj.Maker GetMaker()
        {
            return new Maker();
        }

        public FootnoteBody(FObj parent, PropertyList propertyList)
            : base(parent, propertyList)
        {
            this.name = "fo:footnote-body";
            this.areaClass = AreaClass.setAreaClass(AreaClass.XSL_FOOTNOTE);
        }

        public override Status Layout(Area area)
        {
            if (this.marker == MarkerStart)
            {
                this.marker = 0;
            }
            BlockArea blockArea =
                new BlockArea(propMgr.GetFontState(area.getFontInfo()),
                              area.getAllocationWidth(), area.spaceLeft(),
                              startIndent, endIndent, textIndent, align,
                              alignLast, lineHeight);
            blockArea.setGeneratedBy(this);
            blockArea.isFirst(true);
            blockArea.setParent(area);
            blockArea.setPage(area.getPage());
            blockArea.start();

            blockArea.setAbsoluteHeight(area.getAbsoluteHeight());
            blockArea.setIDReferences(area.getIDReferences());

            blockArea.setTableCellXOffset(area.getTableCellXOffset());

            int numChildren = this.children.Count;
            for (int i = this.marker; i < numChildren; i++)
            {
                FONode fo = (FONode)children[i];
                Status status;
                if ((status = fo.Layout(blockArea)).isIncomplete())
                {
                    this.ResetMarker();
                    return status;
                }
            }
            blockArea.end();
            area.addChild(blockArea);
            area.increaseHeight(blockArea.GetHeight());
            blockArea.isLast(true);
            return new Status(Status.OK);
        }
    }
}


text:
<?php

namespace Lifo\TypeaheadBundle\Twig\Extension;

use Assetic\Asset\AssetCollection;
use Assetic\Asset\StringAsset;
use Assetic\Filter\Yui\JsCompressorFilter;
use Lifo\TypeaheadBundle\Form\Type\TypeaheadType;

class TypeaheadTwigExtension extends \Twig_Extension
{
    public function getName()
    {
        return 'lifo_typeahead';
    }

    public function getFunctions()
    {
        return array(
            'lifo_typeahead_init' => new \Twig_Function_Method($this, 'initTypeaheadFunction', array('needs_environment' => true, 'is_safe' => array('html'))),
        );
    }

    public function initTypeaheadFunction(\Twig_Environment $env)
    {
        if (!TypeaheadType::$initialized) {
            TypeaheadType::$initialized = true;
            $url = $env->getExtension('assets')->getAssetUrl('bundles/lifotypeahead/js/typeaheadbundle.js');
            return "<script type=\"text/javascript\" src=\"$url\"></script>";
        }
        return '';
    }

}


text:
import './VTooltip.sass'

// Mixins
import Activatable from '../../mixins/activatable'
import Colorable from '../../mixins/colorable'
import Delayable from '../../mixins/delayable'
import Dependent from '../../mixins/dependent'
import Menuable from '../../mixins/menuable'

// Helpers
import { convertToUnit, keyCodes, getSlotType } from '../../util/helpers'
import { consoleError } from '../../util/console'

// Types
import { VNode } from 'vue'
import mixins from '../../util/mixins'

/* @vue/component */
export default mixins(Colorable, Delayable, Dependent, Menuable).extend({
  name: 'v-tooltip',

  props: {
    closeDelay: {
      type: [Number, String],
      default: 0,
    },
    disabled: Boolean,
    openDelay: {
      type: [Number, String],
      default: 0,
    },
    openOnHover: {
      type: Boolean,
      default: true,
    },
    openOnFocus: {
      type: Boolean,
      default: true,
    },
    tag: {
      type: String,
      default: 'span',
    },
    transition: String,
  },

  data: () => ({
    calculatedMinWidth: 0,
    closeDependents: false,
  }),

  computed: {
    calculatedLeft (): string {
      const { activator, content } = this.dimensions
      const unknown = !this.bottom && !this.left && !this.top && !this.right
      const activatorLeft = this.attach !== false ? activator.offsetLeft : activator.left
      let left = 0

      if (this.top || this.bottom || unknown) {
        left = (
          activatorLeft +
          (activator.width / 2) -
          (content.width / 2)
        )
      } else if (this.left || this.right) {
        left = (
          activatorLeft +
          (this.right ? activator.width : -content.width) +
          (this.right ? 10 : -10)
        )
      }

      if (this.nudgeLeft) left -= parseInt(this.nudgeLeft)
      if (this.nudgeRight) left += parseInt(this.nudgeRight)

      return `${this.calcXOverflow(left, this.dimensions.content.width)}px`
    },
    calculatedTop (): string {
      const { activator, content } = this.dimensions
      const activatorTop = this.attach !== false ? activator.offsetTop : activator.top
      let top = 0

      if (this.top || this.bottom) {
        top = (
          activatorTop +
          (this.bottom ? activator.height : -content.height) +
          (this.bottom ? 10 : -10)
        )
      } else if (this.left || this.right) {
        top = (
          activatorTop +
          (activator.height / 2) -
          (content.height / 2)
        )
      }

      if (this.nudgeTop) top -= parseInt(this.nudgeTop)
      if (this.nudgeBottom) top += parseInt(this.nudgeBottom)
      if (this.attach === false) top += this.pageYOffset

      return `${this.calcYOverflow(top)}px`
    },
    classes (): object {
      return {
        'v-tooltip--top': this.top,
        'v-tooltip--right': this.right,
        'v-tooltip--bottom': this.bottom,
        'v-tooltip--left': this.left,
        'v-tooltip--attached':
          this.attach === '' ||
          this.attach === true ||
          this.attach === 'attach',
      }
    },
    computedTransition (): string {
      if (this.transition) return this.transition

      return this.isActive ? 'scale-transition' : 'fade-transition'
    },
    offsetY (): boolean {
      return this.top || this.bottom
    },
    offsetX (): boolean {
      return this.left || this.right
    },
    styles (): object {
      return {
        left: this.calculatedLeft,
        maxWidth: convertToUnit(this.maxWidth),
        minWidth: convertToUnit(this.minWidth),
        top: this.calculatedTop,
        zIndex: this.zIndex || this.activeZIndex,
      }
    },
  },

  beforeMount () {
    this.$nextTick(() => {
      this.value && this.callActivate()
    })
  },

  mounted () {
    if (getSlotType(this, 'activator', true) === 'v-slot') {
      consoleError(`v-tooltip's activator slot must be bound, try '<template #activator="data"><v-btn v-on="data.on>'`, this)
    }
  },

  methods: {
    activate () {
      // Update coordinates and dimensions of menu
      // and its activator
      this.updateDimensions()
      // Start the transition
      requestAnimationFrame(this.startTransition)
    },
    deactivate () {
      this.runDelay('close')
    },
    genActivatorListeners () {
      const listeners = Activatable.options.methods.genActivatorListeners.call(this)

      if (this.openOnFocus) {
        listeners.focus = (e: Event) => {
          this.getActivator(e)
          this.runDelay('open')
        }
        listeners.blur = (e: Event) => {
          this.getActivator(e)
          this.runDelay('close')
        }
      }

      listeners.keydown = (e: KeyboardEvent) => {
        if (e.keyCode === keyCodes.esc) {
          this.getActivator(e)
          this.runDelay('close')
        }
      }

      return listeners
    },
    genActivatorAttributes () {
      return {
        'aria-haspopup': true,
        'aria-expanded': String(this.isActive),
      }
    },
    genTransition () {
      const content = this.genContent()

      if (!this.computedTransition) return content

      return this.$createElement('transition', {
        props: {
          name: this.computedTransition,
        },
      }, [content])
    },
    genContent () {
      return this.$createElement(
        'div',
        this.setBackgroundColor(this.color, {
          staticClass: 'v-tooltip__content',
          class: {
            [this.contentClass]: true,
            menuable__content__active: this.isActive,
            'v-tooltip__content--fixed': this.activatorFixed,
          },
          style: this.styles,
          attrs: this.getScopeIdAttrs(),
          directives: [{
            name: 'show',
            value: this.isContentActive,
          }],
          ref: 'content',
        }),
        this.getContentSlot()
      )
    },
  },

  render (h): VNode {
    return h(this.tag, {
      staticClass: 'v-tooltip',
      class: this.classes,
    }, [
      this.showLazyContent(() => [this.genTransition()]),
      this.genActivator(),
    ])
  },
})


text:
package java.nio;

/**
 * A typesafe enumeration for byte orders.
 *
 * @author Mark Reinhold
 * @author JSR-51 Expert Group
 * @version 1.14, 05/11/17
 * @since 1.4
 */

public final class ByteOrder {

    private String name;

    private ByteOrder(String name) {
	this.name = name;
    }

    /**
     * Constant denoting big-endian byte order.  In this order, the bytes of a
     * multibyte value are ordered from most significant to least significant.
     * </p>
     */
    public static final ByteOrder BIG_ENDIAN
	= new ByteOrder("BIG_ENDIAN");

    /**
     * Constant denoting little-endian byte order.  In this order, the bytes of
     * a multibyte value are ordered from least significant to most
     * significant.  </p>
     */
    public static final ByteOrder LITTLE_ENDIAN
	= new ByteOrder("LITTLE_ENDIAN");

    /**
     * Retrieves the native byte order of the underlying platform.
     *
     * <p> This method is defined so that performance-sensitive Java code can
     * allocate direct buffers with the same byte order as the hardware.
     * Native code libraries are often more efficient when such buffers are
     * used.  </p>
     *
     * @return  The native byte order of the hardware upon which this Java
     *          virtual machine is running
     */
    public static ByteOrder nativeOrder() {
	return Bits.byteOrder();
    }

    /**
     * Constructs a string describing this object.
     *
     * <p> This method returns the string <tt>"BIG_ENDIAN"</tt> for {@link
     * #BIG_ENDIAN} and <tt>"LITTLE_ENDIAN"</tt> for {@link #LITTLE_ENDIAN}.
     * </p>
     *
     * @return  The specified string
     */
    public String toString() {
	return name;
    }

}


text:
package test.factory;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

/**
 * Make sure that @Factory methods are not counted as @Test in the presence of a class-scoped @Test
 * annotation.
 */
@Test
public class TestClassAnnotationTest {

  private int count;

  @Factory
  public Object[] createFixture() {
    count++;
    return new Object[] {new Object[] {new Object()}};
  }

  public void testOne() {
    count++;
  }

  @AfterClass
  public void verify() {
    Assert.assertEquals(count, 2);
  }
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Test Animation</title>
	<script src='../../era/era-debug.js'></script>
<script>

var app = new Ui.App({
	content: {
		type: Ui.VBox,
		content: [{
			type: Ui.ToolBar,
			content: [{
				type: Ui.Button, text: 'begin',
				onPress: function() { clock.begin(); }
			}, {
				type: Ui.Button, text: 'pause',
				onPress: function() { clock.pause(); }
			}, {
				type: Ui.Button, text: 'resume',
				onPress: function() { clock.resume(); }
			}, {
				type: Ui.Button, text: 'stop',
				onPress: function() { clock.stop(); }
			}]
		}, {
			type: Ui.Rectangle, name: 'rect',
			width: 200, height: 100, fill: 'green',
			verticalAlign: 'center', horizontalAlign: 'center',
			'Ui.Box.resizable': true
		}]
	}
});

var clock = new Anim.ClockGroup({
	speed: 2, repeat: 2,
	content: [{
		type: Anim.Clock, duration: 4,
		ease: { type: Anim.ElasticEase, mode: 'out' },
		onTimeupdate: function(clock, progress) {
			app.rect.setTransform(Ui.Matrix.createRotate(progress * 360));
		}
	}, {
		type: Anim.Clock, beginTime: 1, duration: 2, autoReverse: true,
		onTimeupdate: function(clock, progress) {
			app.rect.setOpacity(1 - progress/2);
		}
	}]
});

</script>
	</head>
</html>


text:
package org.hoteia.qalingo.core.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

import org.hibernate.Hibernate;
import org.hoteia.qalingo.core.annotation.CacheEntityInformation;
import org.hoteia.qalingo.core.domain.impl.DomainEntity;

@Entity
@Table(name="TECO_ENGINE_SETTING")
@CacheEntityInformation(cacheName="web_cache_engine_setting")
public class EngineSetting extends AbstractEntity<EngineSetting> implements DomainEntity {

	/**
	 * Generated UID
	 */
	private static final long serialVersionUID = 1773804870039476505L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    private Long id;

    @Version
    @Column(name = "VERSION", nullable = false) // , columnDefinition = "int(11) default 1"
    private int version;

    @Column(name = "CODE", nullable = false)
    private String code;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DESCRIPTION")
    @Lob
    private String description;

    @Column(name = "DEFAULT_VALUE")
    private String defaultValue;

    @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
    @JoinColumn(name = "ENGINE_SETTING_ID")
    private Set<EngineSettingValue> engineSettingValues = new HashSet<EngineSettingValue>();

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DATE_CREATE")
    private Date dateCreate;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DATE_UPDATE")
    private Date dateUpdate;

    public EngineSetting() {
        this.dateCreate = new Date();
        this.dateUpdate = new Date();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getVersion() {
        return version;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

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

    public String getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }

    public Set<EngineSettingValue> getEngineSettingValues() {
        return engineSettingValues;
    }

    public void setEngineSettingValues(Set<EngineSettingValue> engineSettingValues) {
        this.engineSettingValues = engineSettingValues;
    }

	public EngineSettingValue getEngineSettingValue(String context) {
		if(engineSettingValues != null
		        && Hibernate.isInitialized(engineSettingValues)){
			for (Iterator<EngineSettingValue> iterator = engineSettingValues.iterator(); iterator.hasNext();) {
				EngineSettingValue engineSettingValue = (EngineSettingValue) iterator.next();
				if(engineSettingValue.getContext().equalsIgnoreCase(context)){
					return engineSettingValue;
				}
			}
		}
		return null;
	}

    public Date getDateCreate() {
        return dateCreate;
    }

    public void setDateCreate(Date dateCreate) {
        this.dateCreate = dateCreate;
    }

    public Date getDateUpdate() {
        return dateUpdate;
    }

    public void setDateUpdate(Date dateUpdate) {
        this.dateUpdate = dateUpdate;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        result = prime * result + ((dateCreate == null) ? 0 : dateCreate.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object sourceObj) {
        Object obj = deproxy(sourceObj);
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EngineSetting other = (EngineSetting) obj;
        if (code == null) {
            if (other.code != null)
                return false;
        } else if (!code.equals(other.code))
            return false;
        if (dateCreate == null) {
            if (other.dateCreate != null)
                return false;
        } else if (!dateCreate.equals(other.dateCreate))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "EngineSetting [id=" + id + ", version=" + version + ", name=" + name + ", description=" + description + ", code=" + code + ", defaultValue=" + defaultValue + ", dateCreate="
                + dateCreate + ", dateUpdate=" + dateUpdate + "]";
    }

}


text:
package com.karuslabs.typist;

import com.karuslabs.typist.Binding.Field;

import org.junit.jupiter.api.*;

import static com.karuslabs.typist.Binding.Pattern.EXECUTION;
import static com.karuslabs.typist.Identity.Type.*;
import static org.junit.jupiter.api.Assertions.*;

class CommandTest {

    Command tell = new Command(null, new Identity(LITERAL, "tell"), null);
    Command players = new Command(tell, new Identity(ARGUMENT, "players"), null);
    Command message = new Command(players, new Identity(ARGUMENT, "message"), null);
    Field field = new Field(null, EXECUTION);

    @Test
    void binding() {
        players.bind(field);

        assertEquals(field, players.binding(EXECUTION));
        assertEquals(field, players.groups().get(EXECUTION.group));

        assertNull(message.binding(EXECUTION));
    }

    @Test
    void path() {
        assertEquals("tell", tell.path());
        assertEquals("tell <players>", players.path());
        assertEquals("tell <players> <message>", message.path());
    }

    @Test
    void hashCode_() {
        var command = new Command(null, new Identity(LITERAL, "tell"), null);
        assertEquals(command.hashCode(), command.hashCode());
    }

    @Test
    void toString_() {
        tell.children().put(players.identity(), players);
        players.children().put(message.identity(), message);

        assertEquals("""
        { identity: tell, site: null, aliases: [], \
        children: {<players>={ identity: <players>, site: null, aliases: [], \
        children: {<message>={ identity: <message>, site: null, \
        aliases: [], children: {}}}}}}
        """.stripTrailing(), tell.toString());
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<project>

	<meta title="Away3D Intermediate Real-Time Env Map" package="away3d.samples.intermediaterealtimeenvmap" version="1.0.0" />
	<app main="Main" file="RealTimeEnvMap" path="Export" />

	<window background="0x000000" orientation="landscape" />
	<window width="1024" height="700" if="desktop" />

	<source path="Source" />

	<haxelib name="away3d" />

	<assets path="Assets" rename="assets" />

</project>


text:
package controllers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/eirka/eirka-libs/user"
)

// LogoutController deletes the user session
func LogoutController(c *gin.Context) {

	// unset the jwt cookie
	http.SetCookie(c.Writer, user.DeleteCookie())

	c.JSON(http.StatusOK, gin.H{"success_message": "Logout successful"})

}


text:
package com.moonlightpixels.jrpg.combat;

import lombok.Builder;
import lombok.Data;
import lombok.Singular;

import java.util.List;

@Data
public final class CombatActionInstance {
    private final Combatant combatant;
    private final CombatAction action;
    private final List<Combatant> targets;

    @Builder
    CombatActionInstance(final Combatant combatant,
                         final CombatAction action,
                         @Singular final List<Combatant> targets) {
        this.combatant = combatant;
        this.action = action;
        this.targets = targets;
    }

    int getDelayInTicks() {
        return action.getDelayInTicks(combatant);
    }

    CombatActionOutcome getOutcome() {
        return action.calculateOutcome(combatant, targets);
    }
}


text:
config.cache_classes = false

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true

# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs                         = true
config.action_controller.perform_caching             = false
config.action_mailer.default_url_options = { :host => "localhost:3000" }

# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false

config.after_initialize do
  ActiveMerchant::Billing::Base.mode = :test
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<link href="assets/reveal.js/css/reveal.min.css" rel="stylesheet">
<link href="assets/reveal.js/css/theme/default.css" rel="stylesheet">

“Get a peer”

About me

Developer (@vanakenm on GitHub, @martinvanaken on Twitter)

founder and C?O of 8th Color

write on 8th Color Blog

PullReview https://pullreview.com

My experience

I graduated in economy, with my most advanced IT course being on Excel

yet I’ve done all my career in programming

I started as a junior inside a programming team, and learned the craft with them

I met young, smart developers recently

but they are doing everything wrong

No one ever told them better

No one ever showed them better

I’m currently coaching teams in Agile

yet I never followed any Agile course

I worked with people practicing Agile

We started 8th color as a Ruby company two years ago

and none of us has ever used Ruby

We learned Ruby by building Sybil together with Christophe

I hired junior developers with no experience at all

Despite having done CS courses, they were unable to do the simplest tasks

They learned by working with our team

Why

Sparring partner

Bounce your ideas

Code reviews

Design sessions

Pair programming

Who

Someone who can read and write some Ruby

Someone who wants to work with you

Level is not important, willingness is

In learning, questions are as valuable as answers

You’ll probably look for answers on stackoverflow anyway

Action

Find an internship

Find a job

Start a project with a friend

Final words

The only required step is to start

Happy (social) coding!


text:
@class BugsnagConfiguration;

@interface BugsnagReactNative: NSObject<RCTBridgeModule>

- (void)configureAsync:(NSDictionary *)readableMap
               resolve:(RCTPromiseResolveBlock)resolve
                reject:(RCTPromiseRejectBlock)reject;

- (NSDictionary *)configure:(NSDictionary *)readableMap;

- (void)updateCodeBundleId:(NSString *)codeBundleId;

- (void)addMetadata:(NSString *)section
           withData:(NSDictionary *)data;

- (void)clearMetadata:(NSString *)section
              withKey:(NSDictionary *)key;

- (void)updateContext:(NSString *)context;

- (void)updateUser:(NSString *)userId
         withEmail:(NSString *)email
          withName:(NSString *)name;

- (void)startSession;
- (void)pauseSession;
- (void)resumeSession;

- (void)addFeatureFlags:(NSArray *)readableArray;
- (void)addFeatureFlag:(NSString *)name
           withVariant:(NSString *)variant;
- (void)clearFeatureFlag:(NSString *)name;
- (void)clearFeatureFlags;

- (void)dispatch:(NSDictionary *)payload
         resolve:(RCTPromiseResolveBlock)resolve
          reject:(RCTPromiseRejectBlock)reject;

- (void)getPayloadInfo:(NSDictionary *)payloadInfo
               resolve:(RCTPromiseResolveBlock)resolve
                reject:(RCTPromiseRejectBlock)reject;

- (void)leaveBreadcrumb:(NSDictionary *)options;

@end


text:
package com.example.android.viewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Fragment that displays "Monday".
 */
public class MondayFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_monday, container, false);
    }
}


text:
// On Mac, you can build this like so:
// xcrun clang++ -o LockSpeedTest Source/WTF/benchmarks/LockSpeedTest.cpp -O3 -W -ISource/WTF -ISource/WTF/icu -ISource/WTF/benchmarks -LWebKitBuild/Release -lWTF -framework Foundation -licucore -std=c++14 -fvisibility=hidden

#include "config.h"

#include "ToyLocks.h"
#include <thread>
#include <unistd.h>
#include <wtf/CurrentTime.h>
#include <wtf/DataLog.h>
#include <wtf/HashMap.h>
#include <wtf/Lock.h>
#include <wtf/ParkingLot.h>
#include <wtf/StdLibExtras.h>
#include <wtf/Threading.h>
#include <wtf/ThreadingPrimitives.h>
#include <wtf/Vector.h>
#include <wtf/WordLock.h>
#include <wtf/text/CString.h>

namespace {

unsigned numThreadGroups;
unsigned numThreadsPerGroup;
unsigned workPerCriticalSection;
unsigned workBetweenCriticalSections;
double secondsPerTest;

NO_RETURN void usage()
{
    printf("Usage: LockSpeedTest yieldspinlock|pausespinlock|wordlock|lock|barginglock|bargingwordlock|thunderlock|thunderwordlock|cascadelock|cascadewordlock|handofflock|unfairlock|mutex|all <num thread groups> <num threads per group> <work per critical section> <work between critical sections> <spin limit> <seconds per test>\n");
    exit(1);
}

template<typename Type>
struct WithPadding {
    Type value;
    char buf[300]; // It's best if this isn't perfect to avoid false sharing.
};

HashMap<CString, Vector<double>> results;

void reportResult(const char* name, double value)
{
    dataLogF("%s: %.3lf KHz\n", name, value);
    results.add(name, Vector<double>()).iterator->value.append(value);
}

struct Benchmark {
    template<typename LockType>
    static void run(const char* name)
    {
        std::unique_ptr<WithPadding<LockType>[]> locks = std::make_unique<WithPadding<LockType>[]>(numThreadGroups);
        std::unique_ptr<WithPadding<double>[]> words = std::make_unique<WithPadding<double>[]>(numThreadGroups);
        std::unique_ptr<RefPtr<Thread>[]> threads = std::make_unique<RefPtr<Thread>[]>(numThreadGroups * numThreadsPerGroup);

        volatile bool keepGoing = true;

        double before = monotonicallyIncreasingTime();

        Lock numIterationsLock;
        uint64_t numIterations = 0;

        for (unsigned threadGroupIndex = numThreadGroups; threadGroupIndex--;) {
            words[threadGroupIndex].value = 0;

            for (unsigned threadIndex = numThreadsPerGroup; threadIndex--;) {
                threads[threadGroupIndex * numThreadsPerGroup + threadIndex] = Thread::create(
                    "Benchmark thread",
                    [threadGroupIndex, &locks, &words, &keepGoing, &numIterationsLock, &numIterations] () {
                        double localWord = 0;
                        double value = 1;
                        unsigned myNumIterations = 0;
                        while (keepGoing) {
                            locks[threadGroupIndex].value.lock();
                            for (unsigned j = workPerCriticalSection; j--;) {
                                words[threadGroupIndex].value += value;
                                value = words[threadGroupIndex].value;
                            }
                            locks[threadGroupIndex].value.unlock();
                            for (unsigned j = workBetweenCriticalSections; j--;) {
                                localWord += value;
                                value = localWord;
                            }
                            myNumIterations++;
                        }
                        LockHolder locker(numIterationsLock);
                        numIterations += myNumIterations;
                    });
            }
        }

        sleep(secondsPerTest);
        keepGoing = false;

        for (unsigned threadIndex = numThreadGroups * numThreadsPerGroup; threadIndex--;)
            threads[threadIndex]->waitForCompletion();

        double after = monotonicallyIncreasingTime();

        reportResult(name, numIterations / (after - before) / 1000);
    }
};

unsigned rangeMin;
unsigned rangeMax;
unsigned rangeStep;
unsigned* rangeVariable;

bool parseValue(const char* string, unsigned* variable)
{
    unsigned myRangeMin;
    unsigned myRangeMax;
    unsigned myRangeStep;
    if (sscanf(string, "%u-%u:%u", &myRangeMin, &myRangeMax, &myRangeStep) == 3) {
        if (rangeVariable) {
            fprintf(stderr, "Can only have one variable with a range.\n");
            return false;
        }

        rangeMin = myRangeMin;
        rangeMax = myRangeMax;
        rangeStep = myRangeStep;
        rangeVariable = variable;
        return true;
    }

    if (sscanf(string, "%u", variable) == 1)
        return true;

    return false;
}

} // anonymous namespace

int main(int argc, char** argv)
{
    WTF::initializeThreading();

    if (argc != 8
        || !parseValue(argv[2], &numThreadGroups)
        || !parseValue(argv[3], &numThreadsPerGroup)
        || !parseValue(argv[4], &workPerCriticalSection)
        || !parseValue(argv[5], &workBetweenCriticalSections)
        || !parseValue(argv[6], &toyLockSpinLimit)
        || sscanf(argv[7], "%lf", &secondsPerTest) != 1)
        usage();

    if (rangeVariable) {
        dataLog("Running with rangeMin = ", rangeMin, ", rangeMax = ", rangeMax, ", rangeStep = ", rangeStep, "\n");
        for (unsigned value = rangeMin; value <= rangeMax; value += rangeStep) {
            dataLog("Running with value = ", value, "\n");
            *rangeVariable = value;
            runEverything<Benchmark>(argv[1]);
        }
    } else
        runEverything<Benchmark>(argv[1]);

    for (auto& entry : results) {
        printf("%s = {", entry.key.data());
        bool first = true;
        for (double value : entry.value) {
            if (first)
                first = false;
            else
                printf(", ");
            printf("%.3lf", value);
        }
        printf("};\n");
    }

    return 0;
}


text:
namespace mc
{
class domain
{
public:
    domain(const std::string& hostname,
           const unsigned short port,
           boost::system::error_code& ec);
    ~domain();

    boost::asio::ip::tcp::endpoint domain2endpoint(void);

protected:
    std::string m_hostname;
    std::string m_port;
    boost::system::error_code* m_ec;

};
}

#endif // !JINGJING_DOMAIN_HPP


text:
export class NodeCanvasFactory extends BaseCanvasFactory {
    /**
     * @ignore
     */
    _createCanvas(width: any, height: any): any;
}
export class NodeCMapReaderFactory extends BaseCMapReaderFactory {
    /**
     * @ignore
     */
    _fetchData(url: any, compressionType: any): Promise<{
        cMapData: any;
        compressionType: any;
    }>;
}
export class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
    /**
     * @ignore
     */
    _fetchData(url: any): Promise<any>;
}
import { BaseCanvasFactory } from "./base_factory.js";
import { BaseCMapReaderFactory } from "./base_factory.js";
import { BaseStandardFontDataFactory } from "./base_factory.js";


text:
var BaseAdmin = require('./BaseAdmin');
var util = require('util');

var UserAdmin = function (appName, modelName, model) {
    BaseAdmin.call(this, appName, modelName, model);
}

util.inherits(UserAdmin, BaseAdmin);

module.exports = UserAdmin;
var proto = UserAdmin.prototype;

proto.initHiddenColumns = function(model) {
    var columns = UserAdmin.super_.prototype.initHiddenColumns.call(this, model);
    var hiddenColumns = ['_id', 'password', 'resetPasswordToken', 'resetPasswordExpires',
        'avatar', 'roles.account'];
    hiddenColumns.forEach(function(c){
        columns.push(c);
    });
    return columns;
}


text:
#import <DVTFoundation/DVTSimpleSerializer.h>

@class NSMutableArray;

@interface DVTSimplePlainTextSerializer : DVTSimpleSerializer
{
    NSMutableArray *_knownClasses;
}

- (void).cxx_destruct;
- (void)encodeObjectList:(id)arg1;
- (void)encodeObject:(id)arg1;
- (void)encodeString:(id)arg1;
- (void)encodeDouble:(double)arg1;
- (void)encodeFloat:(float)arg1;
- (void)encodeInteger:(unsigned long long)arg1;
- (id)init;

@end


text:
package com.miao.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.miao.R;
import com.miao.bean.CourseInfo;
import com.miao.bean.GlobalInfo;
import com.miao.common.Utility;
import com.miao.db.dao.GlobalInfoDao;
import com.miao.db.dao.UserCourseDao;

/**
 * Created by miao on 2017/3/21.
 */

public class CourseDetailInfoActivity extends FragmentActivity{

    /**
     *  静态成员变量
     */
    private static Context context;

    /**
     * UI相关成员变量
     */
    private ProgressDialog progressDialog;

    /**
     * View相关成员变量
     */
    protected View backView;
    protected TextView titleView;

    protected TextView courseNameView;//课程名
    protected TextView courseTeacherView;//任课老师
    protected TextView courseTimeView;//上课时间
    protected TextView courseWeekView;//上课周数
    protected TextView courseSpaceView;//上课地点

    protected Button deleteButton;//删除课程

    //Dao成员变量
    GlobalInfoDao gInfoDao;
    UserCourseDao uCourseDao;

    //数据模型变量
    GlobalInfo gInfo;//需要isFirstUse和activeUserUid

    //数据存储变量
    CourseInfo cInfo;

    //临时变量
    private int uid,cid;

    /**
     * Activity回调函数
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // 继承父类方法,绑定View
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);

        // 初始化context
        context = getApplicationContext();

        // 初始化Dao成员变量
        gInfoDao = new GlobalInfoDao(context);
        uCourseDao = new UserCourseDao(context);

        // 初始化数据模型变量
        gInfo = gInfoDao.query();
        uid = gInfo.getActiveUserUid();
        cInfo = new CourseInfo();
        cInfo = (CourseInfo) getIntent().getSerializableExtra("courseInfo");//从Intent中取回Serializable的course_info内容
        cid = cInfo.getCid();

        // 初始化临时变量

        // 自定义函数
        initView();//初始化CourseActivity界面
        initListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        backView = findViewById(R.id.Btn_Course_Back);
        //设置标题栏
        titleView = (TextView) findViewById(R.id.Text_Course_Title);
        titleView.setTextSize(20);
        titleView.setPadding(15, 2, 15, 2);

        courseNameView = (TextView) findViewById(R.id.Detail_Course_Name);
        courseTeacherView = (TextView) findViewById(R.id.Detail_Course_Teacher);
        courseTimeView = (TextView) findViewById(R.id.Detail_Course_Time);
        courseWeekView = (TextView) findViewById(R.id.Detail_Course_Week);
        courseSpaceView = (TextView) findViewById(R.id.Detail_Course_Space);

        courseNameView.setText("课程名:" + cInfo.getCoursename());
        courseTeacherView.setText("任课教师:" + cInfo.getTeacher());
        courseTimeView.setText("时间:星期" + Utility.getDayStr(cInfo.getDay()) + " 第" + cInfo.getLessonfrom() + "节 - 第" + cInfo.getLessonto() + "节");
        if(cInfo.getWeektype()==1) {
            courseWeekView.setText("周数:第" +  cInfo.getWeekfrom() + "周 - 第" + cInfo.getWeekto() + "周");
        }else if(cInfo.getWeektype()==2) {
            courseWeekView.setText("周数:第" +  cInfo.getWeekfrom() + "节 - 第" + cInfo.getWeekto()+ "周 单周");
        }else if(cInfo.getWeektype()==3) {
            courseWeekView.setText("周数:第" +  cInfo.getWeekfrom() + "节 - 第" + cInfo.getWeekto()+ "周 双周");
        }
        courseSpaceView.setText("地点:" + cInfo.getPlace());

        deleteButton = (Button) findViewById(R.id.Btn_Delete);
    }

    private void initListener() {
        backView.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                jumpToCourse();
            }
        });

        deleteButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                deleteCourse();
            }
        });

    }

    private void deleteCourse(){
        // 显示状态对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage(getResources().getString(R.string.loading_tip));
        progressDialog.setCancelable(true);
        progressDialog.show();

        handleDeleteCourse(uid, cid);
    }

    /**
     * 删除课程子线程,删除uc表项,选项2为删除课程
     */
    private void handleDeleteCourse(int uid,int cid) {

    }

    private void jumpToCourse() {//返回课程界面
        Intent intent = new Intent();
        intent.setClass(this, CourseActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
        finish();
    }

}


text:
let gulpConfig = require('./gulpConfig.js');

module.exports = require('ima-gulp-task-loader')(
  [
    './node_modules/ima-gulp-tasks/tasks',
    './node_modules/ima-examples/tasks',
    './app/gulp/tasks'
  ],
  gulpConfig
);


text:
package org.apache.hadoop.hbase.backup;

import static org.junit.Assert.assertTrue;

import java.util.List;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.backup.util.BackupUtils;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category(LargeTests.class)
public class TestRestoreBoundaryTests extends TestBackupBase {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestRestoreBoundaryTests.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestRestoreBoundaryTests.class);

  /**
   * Verify that a single empty table is restored to a new table.
   *
   * @throws Exception if doing the backup or an operation on the tables fails
   */
  @Test
  public void testFullRestoreSingleEmpty() throws Exception {
    LOG.info("test full restore on a single table empty table");
    String backupId = fullTableBackup(toList(table1.getNameAsString()));
    LOG.info("backup complete");
    TableName[] tableset = new TableName[] { table1 };
    TableName[] tablemap = new TableName[] { table1_restore };
    getBackupAdmin().restore(
      BackupUtils.createRestoreRequest(BACKUP_ROOT_DIR, backupId, false, tableset, tablemap,
        false));
    HBaseAdmin hba = TEST_UTIL.getHBaseAdmin();
    assertTrue(hba.tableExists(table1_restore));
    TEST_UTIL.deleteTable(table1_restore);
  }

  /**
   * Verify that multiple tables are restored to new tables.
   *
   * @throws Exception if doing the backup or an operation on the tables fails
   */
  @Test
  public void testFullRestoreMultipleEmpty() throws Exception {
    LOG.info("create full backup image on multiple tables");

    List<TableName> tables = toList(table2.getNameAsString(), table3.getNameAsString());
    String backupId = fullTableBackup(tables);
    TableName[] restore_tableset = new TableName[] { table2, table3 };
    TableName[] tablemap = new TableName[] { table2_restore, table3_restore };
    getBackupAdmin().restore(
      BackupUtils.createRestoreRequest(BACKUP_ROOT_DIR, backupId, false, restore_tableset,
        tablemap, false));
    HBaseAdmin hba = TEST_UTIL.getHBaseAdmin();
    assertTrue(hba.tableExists(table2_restore));
    assertTrue(hba.tableExists(table3_restore));
    TEST_UTIL.deleteTable(table2_restore);
    TEST_UTIL.deleteTable(table3_restore);
    hba.close();
  }
}


text:
oTest.fnStart( "Initialise two table" );

$(document).ready( function () {
	$('table.display').dataTable();

	oTest.fnTest(
		"Check that initialisation was okay",
		null,
		function () { return true; }
	);

	oTest.fnComplete();
} );


text:
(function(){

    'use strict';

    /*
    * Geolocation service
    *-----------------------------------------------------
    */

    angular.module('app').factory('geoLocationService', ['$q', '$http', function($q, $http){

        var getLocation = function() {

            var defer = $q.defer();

            // If supported and have permission for location...
            if (navigator.geolocation) {

                //
                navigator.geolocation.getCurrentPosition(function(position){

                    var result = {latitude : position.coords.latitude , longitude : position.coords.longitude}

                    // Adding randomization since we are all in the same location...
                    result.latitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100  ) ;
                    result.longitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100  ) ;

                    getNearbyCity(result.latitude, result.longitude).then(function(data){
                        result.address = data.data.results[1].formatted_address;
                        defer.resolve(result);
                    });

                }, function(error){

                    defer.reject({message: error.message, code:error.code});

                });
            }
            else {
                defer.reject({error: 'Geolocation not supported'});
            }

            return defer.promise;
        }

        var getNearbyCity = function (latitude, longitude){

            var defer = $q.defer();
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude +',' + longitude +'&sensor=true';

            $http({method: 'GET', url: url}).
                success(function(data, status, headers, config) {

                     defer.resolve({data : data});
                }).
                error(function(data, status, headers, config) {
                  defer.reject({error: 'City not found'});
                });

            return defer.promise;
        }

        var service = {
            getLocation : getLocation,
            getNearbyCity: getNearbyCity
        };

        return service;
    }]);

    /*
    * Firebase service
    *-----------------------------------------------------
    */

    angular.module('app').factory('dataService', ['$firebase','$q', function($firebase,$q){

        var firebaseRef= new Firebase("https://vivid-fire-4635.firebaseio.com/");
        var geoFire = new GeoFire(firebaseRef.child("_geofire"));

        var getFirebaseRoot = function(){
            return firebaseRef;
        };

        var getGeoFireNode = function(){
            return geoFire;
        }

        var getFoodTruckNode = function(){
            return getFirebaseRoot().child("FoodTrucks");
        }

        var addData = function(data, locationData){
            // persist our data to firebase
            var ref = getFoodTruckNode();

            return  $firebase(ref).$push(data).then(function(childRef){
                   addGeofireData({key: childRef.name(), latitude: locationData.latitude, longitude: locationData.longitude});
            });
        };

        var addGeofireData = function(data){
            var defer = $q.defer();

            geoFire.set(data.key, [data.latitude, data.longitude]).then(function() {
                defer.resolve();
              }).catch(function(error) {
                defer.reject(error);
            });

            return defer.promise;
        };

        var getData = function(callback){

            var ref = getFoodTruckNode();
            return $firebase(ref).$asArray();

        }

        var service = {
            addData : addData,
            getData: getData,
            getFirebaseRoot: getFirebaseRoot,
            getGeoFireNode : getGeoFireNode
        };

        return service;

    }]);

})();


text:
'use strict';

/**
 * Created by PHE on 2016/6/21.
 */
let aws = require('aws-sdk');

// AWS set region
if (process.env.SERVERLESS_REGION) {
  console.log("set region to", process.env.SERVERLESS_REGION);
  aws.config.update({
    region: process.env.SERVERLESS_REGION,
  });
} else {
  aws.config.update({
    region: 'ap-northeast-1',
  });
}
module.exports = aws;


text:
import { client } from './apollo-client-test-helper';
import { AddCounterDocument } from '../../../generated-models';
import 'jest';

describe('Apollo Client tests', () => {
    it('client test', async () => {
        const result = await client.mutate({
            mutation: AddCounterDocument,
            variables: { amount: 1 },
            // data: {},
        });
        expect(result).toEqual({ data: { addCounterState: null }, errors: undefined });
    });
});


text:
.. Astropy documentation master file, created by
   sphinx-quickstart on Tue Jul 26 02:59:34 2011.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

:tocdepth: 3

.. the "raw" directive below is used to hide the title in favor of just the logo being visible
.. raw:: html

    <style media="screen" type="text/css">
      h1 { display:none; }
    </style>

#####################
Astropy Documentation
#####################

.. |logo_svg| image:: _static/astropy_banner.svg

.. |logo_png| image:: _static/astropy_banner_96.png

.. raw:: html

   <img src="_static/astropy_banner.svg" onerror="this.src='_static/astropy_banner_96.png'; this.onerror=null;" width="485"/>

.. only:: latex

    .. image:: _static/astropy_logo.pdf

The ``astropy`` package contains key functionality and common tools needed for
performing astronomy and astrophysics with Python.  It is at the core of the
`Astropy Project <http://www.astropy.org/about.html>`_, which aims to enable
the community to develop a robust ecosystem of `affiliated packages`_
covering a broad range of needs for astronomical research, data
processing, and data analysis.

.. Important:: If you use Astropy for work presented in a publication or talk
   please help the project via proper `citation or acknowledgement
   <https://www.astropy.org/acknowledging.html>`_.  This also applies to use of
   software or `affiliated packages`_ that depend on the astropy
   core package.

.. _getting-started:

***************
Getting Started
***************

.. toctree::
   :maxdepth: 1

   install
   whatsnew/4.3
   importing_astropy
   Example Gallery <generated/examples/index>
   Tutorials <https://learn.astropy.org/>
   Get Help <http://www.astropy.org/help.html>
   Contribute and Report Problems <http://www.astropy.org/contribute.html>
   About the Astropy Project <http://www.astropy.org/about.html>

.. _user-docs:

******************
User Documentation
******************

Data structures and transformations
-----------------------------------

.. toctree::
   :maxdepth: 1

   constants/index
   units/index
   nddata/index
   table/index
   time/index
   timeseries/index
   coordinates/index
   wcs/index
   modeling/index
   uncertainty/index

Files, I/O, and Communication
-----------------------------

.. toctree::
   :maxdepth: 1

   io/unified
   io/fits/index
   io/ascii/index
   io/votable/index
   io/misc
   samp/index

Computations and utilities
--------------------------

.. toctree::
   :maxdepth: 1

   cosmology/index
   convolution/index
   visualization/index
   stats/index

Nuts and bolts
--------------

.. toctree::
   :maxdepth: 1

   config/index
   io/registry
   logging
   warnings
   utils/index

.. _developer-docs:

***********************
Developer Documentation
***********************

The developer documentation contains instructions for how to contribute to
Astropy or affiliated packages, install and test the development version,
as well as coding, documentation, and testing guidelines.

{% if is_development %}

For the guiding vision of this process and the project
as a whole, see :doc:`development/vision`.

.. toctree::
   :maxdepth: 1

   development/workflow/development_workflow
   development/workflow/get_devel_version
   development/when_to_rebase
   development/codeguide
   development/docguide
   development/style-guide
   development/testguide
   testhelpers
   development/scripts
   development/building
   development/ccython
   development/releasing
   development/workflow/maintainer_workflow
   development/astropy-package-template
   changelog

There are some additional tools, mostly of use for maintainers, in the
`astropy/astropy-procedures repository
<https://github.com/astropy/astropy-procedures>`__.

{%else%}

To read the developer documentation, you will need to go to the
`latest developer version of the documentation <https://docs.astropy.org/en/latest/#developer-documentation>`__.

.. toctree::
   :maxdepth: 1

   changelog

{%endif%}

.. _project-details:

***************
Project details
***************

.. toctree::
   :maxdepth: 1

   stability
   whatsnew/index
   known_issues
   credits
   license

*****
Index
*****

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. _feedback@astropy.org: mailto:feedback@astropy.org
.. _affiliated packages: https://www.astropy.org/affiliated/


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Tour;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class ReportController extends Controller
{
    /**
     * @Route("/admin/report/revenue", name="admin_revenue_report")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function revenueReport()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $current_date = new \DateTime();
        $graph_data = array();

        for ($month = 1; $month <= 12; $month++) {
            $revenue = 0;
            $monthHasOrder = $em->createQuery(
                "SELECT to
                FROM AppBundle:TourOrder to
                WHERE DATE_FORMAT(to.createdAt, '%m-%Y') = :month
                "
            )->setParameter('month', $month . '-' . $current_date->format('Y'))->getResult();

            if ($monthHasOrder) {
                foreach ($monthHasOrder as $order) {
                    if ('completed' == $order->getStatus())
                        $revenue += $order->getInvoice()->getTotalPrice();
                }
            }

            $graph_data[] = array('Th' . $month, $revenue);
        }

        $graph_data = $this->get('jms_serializer')->serialize($graph_data, 'json');

        return $this->render('Admin/revenue_report.html.twig', array(
            'graph_data' => $graph_data,
        ));
    }

    /**
     * @Route("/admin/report/tour/", name="admin_tour_report")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function tourReportShowAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $tours = $em->getRepository('AppBundle:Tour')->findAll();

        return $this->render('Admin/tour_report.html.twig', [
            'tours' => $tours,
        ]);
    }

    /**
     * @Route("/admin/report/tour/{id}", name="admin_tour_detail_report")
     *
     * @param Tour $tour
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function tourReportDetailAction(Tour $tour)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $tourRepository = $em->getRepository('AppBundle:Tour');
        $orders = $tourRepository->find($tour->getId())->getTourOrders();
        $graph_data = array();

        for ($month = 1; $month <= 12; $month++) {
            $revenue = 0;
            $current_month = \DateTime::createFromFormat('m', $month)->format('m');

            foreach ($orders as $key => $order) {
                $order_date = $order->getcreatedAt();
                if ($order_date->format('m') === $current_month) {
                    if ('completed' == $order->getStatus()) {
                        $revenue += $order->getInvoice()->getTotalPrice();

                        unset($orders[$key]);
                    }
                } else {
                    continue;
                }
            }

            $graph_data[] = array('Th' . $month, $revenue);
        }

        $graph_data = $this->get('jms_serializer')->serialize($graph_data, 'json');

        return $this->render('Admin/revenue_report.html.twig', array(
            'graph_data' => $graph_data,
        ));
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.settings;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.TitledSeparator;
import com.intellij.xdebugger.settings.DebuggerConfigurableProvider;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

class MergedCompositeConfigurable implements SearchableConfigurable {
  static final EmptyBorder BOTTOM_INSETS = new EmptyBorder(0, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0);

  private static final Insets FIRST_COMPONENT_INSETS = new Insets(0, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0);
  private static final Insets N_COMPONENT_INSETS = new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0);

  protected final Configurable[] children;
  protected JComponent rootComponent;

  private final String id;
  private final String displayName;
  private final String helpTopic;

  MergedCompositeConfigurable(@NotNull String id,
                                     @NotNull String displayName,
                                     @Nullable String helpTopic,
                                     @NotNull Configurable[] children) {
    this.children = children;
    this.id = id;
    this.displayName = displayName;
    this.helpTopic = helpTopic;
  }

  @NotNull
  @Override
  public String getId() {
    return id;
  }

  @Nls
  @Override
  public String getDisplayName() {
    return displayName;
  }

  @Nullable
  @Override
  public String getHelpTopic() {
    if (helpTopic != null) {
      return helpTopic;
    }
    return children.length == 1 ? children[0].getHelpTopic() : null;
  }

  /**
   * false by default.
   *
   * If Ruby general settings will be without titled border in RubyMine, user could think that all other debugger categories also about Ruby.
   */
  protected boolean isUseTargetedProductPolicyIfSeveralChildren() {
    return false;
  }

  @Nullable
  @Override
  public JComponent createComponent() {
    if (rootComponent == null) {
      Configurable firstConfigurable = children[0];
      if (children.length == 1) {
        JComponent component = firstConfigurable.createComponent();
        String rootComponentDisplayName = firstConfigurable.getDisplayName();
        if (!StringUtil.isEmpty(rootComponentDisplayName) && !isTargetedToProduct(firstConfigurable)) {
          component.setBorder(IdeBorderFactory.createTitledBorder(rootComponentDisplayName, false, FIRST_COMPONENT_INSETS));
        }
        rootComponent = createPanel(true);
        rootComponent.add(component);
      }
      else {
        boolean isFirstNamed = true;
        JPanel panel = createPanel(true);
        for (Configurable configurable : children) {
          JComponent component = configurable.createComponent();
          assert component != null;
          String displayName = configurable.getDisplayName();
          if (StringUtil.isEmpty(displayName)) {
            component.setBorder(BOTTOM_INSETS);
          }
          else {
            boolean addBorder = true;
            if (isUseTargetedProductPolicyIfSeveralChildren() && isFirstNamed) {
              isFirstNamed = false;
              if (isTargetedToProduct(configurable)) {
                addBorder = false;
              }
            }
            if (addBorder) {
              component.setBorder(IdeBorderFactory.createTitledBorder(displayName, false, firstConfigurable == configurable ? FIRST_COMPONENT_INSETS : N_COMPONENT_INSETS));
            }
          }
          panel.add(component);
        }
        rootComponent = panel;
      }
    }
    return rootComponent;
  }

  static boolean isTargetedToProduct(@NotNull Configurable configurable) {
    for (DebuggerConfigurableProvider provider : DebuggerConfigurableProvider.EXTENSION_POINT.getExtensions()) {
      if (provider.isTargetedToProduct(configurable)) {
        return true;
      }
    }
    return false;
  }

  @NotNull
  static JPanel createPanel(boolean isUseTitledBorder) {
    int verticalGap = TitledSeparator.TOP_INSET;
    JPanel panel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, isUseTitledBorder ? 0 : verticalGap, true, true));
    // VerticalFlowLayout incorrectly use vertical gap as top inset
    if (!isUseTitledBorder) {
      panel.setBorder(new EmptyBorder(-verticalGap, 0, 0, 0));
    }
    return panel;
  }

  @Override
  public boolean isModified() {
    for (Configurable child : children) {
      if (child.isModified()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public void apply() throws ConfigurationException {
    for (Configurable child : children) {
      if (child.isModified()) {
        child.apply();
      }
    }
  }

  @Override
  public void reset() {
    for (Configurable child : children) {
      child.reset();
    }
  }

  @Override
  public void disposeUIResources() {
    rootComponent = null;

    for (Configurable child : children) {
      child.disposeUIResources();
    }
  }
}


text:
"""
Does the initial indexing of the records in material view
"""
import logging

from django.core.management import BaseCommand

from facilities.models import FacilityExportExcelMaterialView
from search.search_utils import index_instance

logger = logging.getLogger(__name__)

class Command(BaseCommand):

    def handle(self, *args, **options):
        for record in FacilityExportExcelMaterialView.objects.all():
            index_instance(record)
            logger.info("indexed instance {0}".format(record.name))


text:
package leap.lang.http.client.apache;

import leap.lang.Disposable;
import leap.lang.Initializable;
import leap.lang.http.client.AbstractHttpClient;
import leap.lang.http.client.HttpRequest;
import leap.lang.logging.Log;
import leap.lang.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.util.concurrent.TimeUnit;

public class ApacheHttpClient extends AbstractHttpClient implements Initializable, Disposable {

    private static final Log log = LogFactory.get(ApacheHttpClient.class);

    private boolean             init;
    private CloseableHttpClient httpClient;
    private RequestConfig       requestConfig;
    private int                 maxTotal                = 300;
    private int                 defaultMaxPerRoute      = 30;
    private boolean             evictExpiredConnections = true;
    private boolean             evictIdleConnections    = true;
    private long                maxIdleTimeInSeconds    = 10;
    private int                 bufferSize;

    public HttpClient getHttpClient() {
        return httpClient;
    }

    public int getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    /**
     * @deprecated  Refactor to {@link #setMaxTotal(int)}.
     */
    @Deprecated
    public void setMaxConnectionTotal(int i) {
        this.setMaxTotal(i);
    }

    public int getDefaultMaxPerRoute() {
        return defaultMaxPerRoute;
    }

    public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
        this.defaultMaxPerRoute = defaultMaxPerRoute;
    }

    /**
     * @deprecated  Refactor {@link #setDefaultMaxPerRoute(int)}
     */
    @Deprecated
    public void setMaxConnectionPerRoute(int i) {
        this.setDefaultMaxPerRoute(i);
    }

    public boolean isEvictExpiredConnections() {
        return evictExpiredConnections;
    }

    public void setEvictExpiredConnections(boolean evictExpiredConnections) {
        this.evictExpiredConnections = evictExpiredConnections;
    }

    public boolean isEvictIdleConnections() {
        return evictIdleConnections;
    }

    public void setEvictIdleConnections(boolean evictIdleConnections) {
        this.evictIdleConnections = evictIdleConnections;
    }

    public long getMaxIdleTimeInSeconds() {
        return maxIdleTimeInSeconds;
    }

    public void setMaxIdleTimeInSeconds(long maxIdleTimeInSeconds) {
        this.maxIdleTimeInSeconds = maxIdleTimeInSeconds;
    }

    public int getBufferSize() {
        return bufferSize;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    @Override
    public HttpRequest request(String url) {
        return new ApacheHttpRequest(this, url);
    }

    public void init() {
        if (this.init) {
            return;
        }

        this.init = true;
        this.requestConfig = initRequestConfig();
        this.httpClient = initHttpClient();
    }

    @Override
    public void dispose() throws Throwable {
        if (null != httpClient) {
            log.info("Close http client");
            this.init = false;
            httpClient.close();
        }
    }

    RequestConfig getRequestConfig() {
        return requestConfig;
    }

    protected RequestConfig initRequestConfig() {
        return RequestConfig.copy(RequestConfig.DEFAULT)
                .setConnectTimeout(getDefaultConnectTimeout())
                .setSocketTimeout(getDefaultReadTimeout())
                .build();
    }

    protected CloseableHttpClient initHttpClient() {
        return initHttpClient(getDefaultConnectionManager(), new DefaultHttpRequestRetryHandler());
    }

    protected CloseableHttpClient initHttpClient(HttpClientConnectionManager cm, HttpRequestRetryHandler retryHandler) {
        HttpClientBuilder cb = HttpClientBuilder.create();

        if (null == cm){
            throw new IllegalArgumentException("connection manager must not null");
        }
        if (null == retryHandler){
            throw new IllegalArgumentException("retry handler must not null");
        }
        cb.setRetryHandler(retryHandler);
        cb.disableRedirectHandling();

        if(evictExpiredConnections) {
            cb.evictExpiredConnections();
        }
        if(evictIdleConnections) {
            cb.evictIdleConnections(maxIdleTimeInSeconds, TimeUnit.SECONDS);
        }
        cb.setConnectionManager(cm);
        cb.setDefaultRequestConfig(requestConfig);
        cb.disableCookieManagement();
        return cb.build();
    }

    protected HttpClientConnectionManager getDefaultConnectionManager(ConnectionConfig cc){
        //TODO : small buffer size will cause socket closed when reading response entity?
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
        //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

        cm.setMaxTotal(maxTotal);
        cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        if (null != cc){
            cm.setDefaultConnectionConfig(cc);
        }
        return cm;
    }

    protected HttpClientConnectionManager getDefaultConnectionManager(){
        return getDefaultConnectionManager(getDefaultConnectionConfig());
    }

    protected ConnectionConfig getDefaultConnectionConfig(){
        if (bufferSize > 0) {
            ConnectionConfig cc =
                    ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

            return cc;
        }
        return null;
    }

    protected Registry<ConnectionSocketFactory> getDefaultRegistry() {
        RegistryBuilder<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create();

        reg.register("http", PlainConnectionSocketFactory.getSocketFactory());

        SSLConnectionSocketFactory sslSocketFactory =
                new SSLConnectionSocketFactory(SSL_CONTEXT, (s, sslSession) -> true);
        reg.register("https", sslSocketFactory);

        return reg.build();
    }

}


text:
namespace Perfectial.Infrastructure.Identity
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Owin.Security.DataProtection;

    using Perfectial.Domain.Model;
    using Perfectial.Infrastructure.Identity.Base;

    /// <summary>
    /// Token provider that uses an IDataProtector to generate encrypted tokens based off of the security stamp.
    /// </summary>
    public class DataProtectorTokenProvider : IUserTokenProvider
    {
        private readonly Encoding DefaultEncoding = new UTF8Encoding(false, true);

        private readonly IDataProtector dataProtector;
        public TimeSpan TokenLifespan { get; set; } = TimeSpan.FromDays(1.0);

        public DataProtectorTokenProvider(IDataProtector dataProtector)
        {
            this.dataProtector = dataProtector;
        }

        public Task<string> GenerateAsync(string modifier, User user)
        {
            string securityToken;

            using (var memoryStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(memoryStream, this.DefaultEncoding, true))
                {
                    binaryWriter.Write(DateTimeOffset.UtcNow.UtcTicks);
                    binaryWriter.Write(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
                    binaryWriter.Write(modifier ?? string.Empty);
                    binaryWriter.Write(user.SecurityStamp ?? string.Empty);
                }

                byte[] protectedBytes = this.dataProtector.Protect(memoryStream.ToArray());
                securityToken = Convert.ToBase64String(protectedBytes);
            }

            return Task.FromResult(securityToken);
        }

        public Task<bool> ValidateAsync(string modifier, User user, string token)
        {
            bool tokenIsValid;
            try
            {
                byte[] unprotectedData = this.dataProtector.Unprotect(Convert.FromBase64String(token));

                var memoryStream = new MemoryStream(unprotectedData);
                using (var binaryReader = new BinaryReader(memoryStream, this.DefaultEncoding, true))
                {
                    DateTimeOffset creationTime = new DateTimeOffset(binaryReader.ReadInt64(), TimeSpan.Zero);
                    DateTimeOffset expirationTime = creationTime + this.TokenLifespan;

                    if (expirationTime < DateTimeOffset.UtcNow)
                    {
                        tokenIsValid = false;
                    }
                    else
                    {
                        string userId = binaryReader.ReadString();
                        if (!string.Equals(userId, Convert.ToString(user.Id, CultureInfo.InvariantCulture)))
                        {
                            tokenIsValid = false;
                        }
                        else
                        {
                            string expectedModifier = binaryReader.ReadString();
                            if (!string.Equals(expectedModifier, modifier))
                            {
                                tokenIsValid = false;
                            }
                            else
                            {
                                string securityStamp = binaryReader.ReadString();
                                if (binaryReader.PeekChar() != -1)
                                {
                                    tokenIsValid = false;
                                }
                                else
                                {
                                    tokenIsValid = securityStamp == user.SecurityStamp;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                tokenIsValid = false;
            }

            return Task.FromResult(tokenIsValid);
        }

        public Task<bool> IsValidAsync(User user)
        {
            return Task.FromResult(true);
        }

        public Task NotifyAsync(User user, string token)
        {
            return Task.FromResult(0);
        }
    }
}


text:
#if defined( __cplusplus )
}
#endif

#endif /* !defined( _${python_module_name_upper_case}_H ) */


text:
package com.thinkberg.moxo.dav;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author Matthias L. Jugel
 * @version $Id$
 */
public class Util {

  private static final SimpleDateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);

  public static String getDateString(long time) {
    return httpDateFormat.format(new Date(time));
  }

//  public static String getISODateString(long time) {
//    return "";
//  }

  public static int copyStream(InputStream is, OutputStream os) throws IOException {
    byte[] buffer = new byte[8192];
    int bytesRead, bytesCount = 0;
    while ((bytesRead = is.read(buffer)) != -1) {
      os.write(buffer, 0, bytesRead);
      bytesCount += bytesRead;
    }
    os.flush();

    return bytesCount;
  }
}


text:
<?php

namespace Google\Service\Speech;

class TranscriptOutputConfig extends \Google\Model
{
  /**
   * @var string
   */
  public $gcsUri;

  /**
   * @param string
   */
  public function setGcsUri($gcsUri)
  {
    $this->gcsUri = $gcsUri;
  }
  /**
   * @return string
   */
  public function getGcsUri()
  {
    return $this->gcsUri;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(TranscriptOutputConfig::class, 'Google_Service_Speech_TranscriptOutputConfig');


text:
package trdsql

import (
	"bufio"
	"errors"
	"io"
	"strings"
)

// LTSVReader provides methods of the Reader interface.
type LTSVReader struct {
	reader    *bufio.Reader
	preRead   []map[string]string
	delimiter string
	names     []string
	types     []string
	limitRead bool
	needNULL  bool
	inNULL    string
}

// NewLTSVReader returns LTSVReader and error.
func NewLTSVReader(reader io.Reader, opts *ReadOpts) (*LTSVReader, error) {
	r := &LTSVReader{}
	r.reader = bufio.NewReader(reader)
	r.delimiter = "\t"

	if opts.InSkip > 0 {
		skipRead(r, opts.InSkip)
	}

	r.limitRead = opts.InLimitRead

	r.needNULL = opts.InNeedNULL
	r.inNULL = opts.InNULL

	names := map[string]bool{}
	for i := 0; i < opts.InPreRead; i++ {
		row, keys, err := r.read()
		if err != nil {
			if !errors.Is(err, io.EOF) {
				return r, err
			}
			r.setColumnType()
			debug.Printf(err.Error())
			return r, nil
		}

		// Add only unique column names.
		for k := 0; k < len(keys); k++ {
			if !names[keys[k]] {
				names[keys[k]] = true
				r.names = append(r.names, keys[k])
			}
		}
		r.preRead = append(r.preRead, row)
	}
	r.setColumnType()
	return r, nil
}

func (r *LTSVReader) setColumnType() {
	if r.names == nil {
		return
	}
	r.types = make([]string, len(r.names))
	for i := 0; i < len(r.names); i++ {
		r.types[i] = DefaultDBType
	}
}

// Names returns column names.
func (r *LTSVReader) Names() ([]string, error) {
	return r.names, nil
}

// Types returns column types.
// All LTSV types return the DefaultDBType.
func (r *LTSVReader) Types() ([]string, error) {
	return r.types, nil
}

// PreReadRow is returns only columns that store preread rows.
func (r *LTSVReader) PreReadRow() [][]interface{} {
	rowNum := len(r.preRead)
	rows := make([][]interface{}, rowNum)
	for n := 0; n < rowNum; n++ {
		rows[n] = make([]interface{}, len(r.names))
		for i := range r.names {
			rows[n][i] = r.preRead[n][r.names[i]]
			if r.needNULL {
				rows[n][i] = replaceNULL(r.inNULL, rows[n][i])
			}
		}
	}
	return rows
}

// ReadRow is read the rest of the row.
func (r *LTSVReader) ReadRow(row []interface{}) ([]interface{}, error) {
	if r.limitRead {
		return nil, io.EOF
	}

	record, _, err := r.read()
	if err != nil {
		return row, err
	}
	for i, name := range r.names {
		row[i] = record[name]
		if r.needNULL {
			row[i] = replaceNULL(r.inNULL, row[i])
		}
	}
	return row, nil
}

func (r *LTSVReader) read() (map[string]string, []string, error) {
	line, err := r.readline()
	if err != nil {
		return nil, nil, err
	}
	columns := strings.Split(line, r.delimiter)
	lvs := make(map[string]string)
	keys := make([]string, 0, len(columns))
	for _, column := range columns {
		kv := strings.SplitN(column, ":", 2)
		if len(kv) != 2 {
			return nil, nil, ErrInvalidColumn
		}
		lvs[kv[0]] = kv[1]
		keys = append(keys, kv[0])
	}
	return lvs, keys, nil
}

func (r *LTSVReader) readline() (string, error) {
	var builder strings.Builder
	for {
		line, isPrefix, err := r.reader.ReadLine()
		if err != nil {
			return "", err
		}
		builder.Write(line)
		if isPrefix {
			continue
		}
		str := strings.TrimSpace(builder.String())
		if len(str) != 0 {
			return str, nil
		}
		builder.Reset()
	}
}


text:
require "devise/bootstrapped/version"
require "devise/generators/bootstrapped_generator"

module Devise
  module Bootstrapped
    class Engine < ::Rails::Engine
    end
  end
end


text:
package container

import (
	"errors"
)

var (
	// ErrImageRequired returned if a task is missing the image definition.
	ErrImageRequired = errors.New("dockerexec: image required")

	// ErrContainerDestroyed returned when a container is prematurely destroyed
	// during a wait call.
	ErrContainerDestroyed = errors.New("dockerexec: container destroyed")

	// ErrContainerUnhealthy returned if controller detects the health check failure
	ErrContainerUnhealthy = errors.New("dockerexec: unhealthy container")
)


text:
Locally I have an install of Jekyll and [this template](https://github.com/ikumen/jekyll-workflow-template). The local Jekyll installation allows me to preview my site. When I'm happy with the generated content, I check-in my raw Markdown files to Git, then push to a remote Git repository to permanently save. If I wish I can also push to a server, where a Git `post-receive` hook will use Jekyll (installed on the server) to build my site from the checked-in content, and publish to an `Nginx` server for the world to see.

If you're interested in giving the workflow a try, read on!

## Server configuration

My installation is specific to Ubuntu, but the instructions should be very similar for other environments after the required packages are installed.

#### Requirements

You'll need to have [Ruby](https://www.ruby-lang.org/en/), Git, and Jekyll installed. For some reason I could not get Jekyll to work with the default Ruby installation on my [Ubuntu 14.04 server](http://releases.ubuntu.com/14.04/)—I had to use [Ruby 2.2 specifically](https://www.brightbox.com/blog/2015/01/05/ruby-2-2-0-packages-for-ubuntu/).

``` bash
# get Ruby 2.2 package and install
$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.2 ruby2.2-dev

# install Jekyll
$ gem install jekyll

# depending on you needs, you may need additional Jekyll plugins,
# I needed the following three
$ gem install jekyll-sitemap
$ gem install pygments.rb   # for highlighting
$ gem install redcarpet     # markdown language
```

#### Git Hook Configuration

Next we'll need to set up a bare Git repository on the server to handle pushes from our local repository. In the bare repository, we add a `post-receive` hook that will take our pushed content, run it through Jekyll, generates the site and finally pushes the generate site to Nginx.

``` bash
$ mkdir /home/user/yourname/myblog.git
$ cd /home/user/yourname/myblog.git
$ git --bare init
```

Add the following to `post-receive` hook script to `/home/user/yourname/myblog.git/hooks`.

``` bash
# post-receive
# where the local git repo will be pushed
GIT_REPO=/home/user/yourname/myblog.git
# where your generated site will be served from
PUBLIC_WWW=/var/www/myblog
TMP_GIT_CLONE=$GIT_REPO/tmp

# move the pushed content to tmp
git clone $GIT_REPO $TMP_GIT_CLONE
# generate the site off the content in tmp
jekyll build -s $TMP_GIT_CLONE -d $PUBLIC_WWW
# clean up our work
rm -Rf $TMP_GIT_CLONE
exit
```

That's it for the server configuration, it's ready now to receive pushes from our local Git repositories containing our Jekyll managed site.

## Local Configuration

I won't go into the details of how to use Jekyll, but on a local workstation or laptop, you'll need to clone [this template](https://github.com/ikumen/jekyll-workflow-template) or set up a new site and initialize it as a Git managed repository.

``` bash
# clone this template
$ git clone git@github.com:ikumen/jekyll-workflow-template.git myblog

# -- OR --
# generate a new site under ./myblog
$ jekyll new myblog
# initialize myblog as a git repo
$ cd myblog
$ git init

# where I keep original copy of my blog
$ git remote add origin git@bitbucket.org:ikumen/myblog.git
# the server we configured above
$ git remote add deploy server:/home/user/yourname/myblog.git

# add ignores for the `_site` directory that Jekyll generates
$ echo _site >> .gitignore
```

That's basically it—if you're using Jekyll and Git, you probably have something very similar set up and would just need to add the `deploy` remote.

## Deployment

After I'm happy with a local post, I check it into Git and push to my server like so.

``` bash
# on my local computer
$ git add .... # posts that I just edited/added
$ git commit -am "new posts about Jekyll workflow"
$ git push origin master  # pushing to original copy of my blog
$ git push deploy master  # pushing to server configure above
```