text:
@implementation NSArray (MEDAdditions)

#pragma mark - Unique

- (NSArray *)med_uniqueElements
{
    return [self med_uniqueElementsWithKey:@"self"];
}

- (NSArray *)med_uniqueElementsWithKey:(NSString *)key
{
    if (!key || key.length == 0) {
        return @[];
    }

    NSString *distinctKeyPath = [NSString stringWithFormat:@"@distinctUnionOfObjects.%@", key];
    return [self valueForKeyPath:distinctKeyPath];
}

#pragma mark - Sort

- (NSArray *)med_arraySortedByKey:(NSString *)key ascending:(BOOL)ascending
{
    if (!key || key.length == 0) {
        return @[];
    }

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:key
                                                                     ascending:ascending
                                                                      selector:@selector(localizedCaseInsensitiveCompare:)];
    return [self sortedArrayUsingDescriptors:@[sortDescriptor]];
}

#pragma mark - Compare

- (NSArray *)med_localizedCompare
{
    return [self sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

- (NSArray *)med_compare
{
    return [self sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
}

- (NSArray *)med_shuffle
{
    NSMutableArray *mutable = [self mutableCopy];
    [mutable med_shuffle];
    return [mutable copy];
}

- (NSArray *)med_reverse
{
    return [[self reverseObjectEnumerator] allObjects];
}

#pragma mark - Operator

- (NSInteger)med_sum
{
    return [[self valueForKeyPath:@"@sum.self"] integerValue];
}

#pragma mark - RX
- (void)med_each:(void (^)(id object))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj);
    }];
}

- (void)med_eachWithIndex:(void (^)(id object, NSUInteger index))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj, idx);
    }];
}

- (NSArray *)med_map:(id (^)(id object))block {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];

    for (id object in self) {
        [array addObject:block(object) ?: [NSNull null]];
    }

    return array;
}

- (NSArray *)med_filter:(BOOL (^)(id object))block {
    return [self filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return block(evaluatedObject);
    }]];
}

- (NSArray *)med_reject:(BOOL (^)(id object))block {
    return [self filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return !block(evaluatedObject);
    }]];
}

- (id)med_detect:(BOOL (^)(id object))block {
    for (id object in self) {
        if (block(object))
            return object;
    }
    return nil;
}

- (id)med_reduce:(id (^)(id accumulator, id object))block {
    return [self med_reduce:nil withBlock:block];
}

- (id)med_reduce:(id)initial withBlock:(id (^)(id accumulator, id object))block {
    id accumulator = initial;

    for(id object in self)
        accumulator = accumulator ? block(accumulator, object) : object;

    return accumulator;
}

@end

@implementation NSMutableArray (MEDAdditions)

- (void)med_shuffle
{
    const NSUInteger count = self.count;
    for (NSUInteger i = 0; i < count - 1; ++i) {
        const NSUInteger n = arc4random_uniform((UInt32)count - i) + i;
        if (i != n) {
            [self exchangeObjectAtIndex:i withObjectAtIndex:n];
        }
    }
}

@end


text:
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using TestApi.Models;

namespace TestApi.Handlers
{
    public class ProductPartHandler : ContentHandler
    {
        public ProductPartHandler(IRepository<BookPartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Protobuild
{
    public interface IActionDispatch
    {
        bool PerformAction(
            ModuleInfo module,
            string action,
            string platform = null,
            string[] enabledServices = null,
            string[] disabledServices = null,
            string serviceSpecPath = null,
            bool debugServiceResolution = false,
            bool disablePackageResolution = false);

        bool DefaultAction(
            ModuleInfo module,
            string platform = null,
            string[] enabledServices = null,
            string[] disabledServices = null,
            string serviceSpecPath = null,
            bool debugServiceResolution = false,
            bool disablePackageResolution = false);
    }
}


text:
using Microsoft.Phone.Controls;

namespace CompassApplication
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
    }
}


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

-->
<resources>

	<!-- ### APPLICATION ======================================================================= -->

	<string name="app_name">Image Loader</string>
</resources>


text:
package controllers

import (
	"net/http"

	"github.com/apiseedprojects/go/responses"
)

type StatusController struct{}

func (sc StatusController) Statusz(w http.ResponseWriter, r *http.Request) {
	responses.OK(w, responses.M{"status": "ok"})
}


text:
package org.opentosca.toscana.model.node;

import java.util.Optional;

import org.opentosca.toscana.core.parse.model.MappingEntity;
import org.opentosca.toscana.model.capability.AttachmentCapability;
import org.opentosca.toscana.model.datatype.SizeUnit;
import org.opentosca.toscana.model.util.ToscaKey;
import org.opentosca.toscana.model.visitor.NodeVisitor;

import lombok.EqualsAndHashCode;
import lombok.ToString;

import static java.lang.String.format;

/**
 Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data
 from which raw storage volumes can be created.

 Note: In this draft of the TOSCA Simple Profile, distributed or Network Attached Storage (NAS) are not
 yet considered (nor are clustered file systems), but the TC plans to do so in future drafts.

 Resize is of existing volumes is not considered at this time.

 It is assumed that the volume contains a single filesystem that the operating system (that is
 hosting an associate application) can recognize and mount without additional information (i.e., it
 is operating system independent).

 (TOSCA Simple Profile in YAML Version 1.1, p. 175-176)
 */
@EqualsAndHashCode
@ToString
public class BlockStorage extends RootNode {

    /**
     The requested storage size in MB.

     Note : Required when an existing volume ({@link #VOLUME_ID}) is not available.

     If {@link #VOLUME_ID} is provided, size is ignored.

     Resize of existing volumes is not considered at this time.
     (TOSCA Simple Profile in YAML Version 1.1, p. 175)
     */
    public static ToscaKey<Integer> SIZE_IN_MB = new ToscaKey<>(PROPERTIES, "size")
        .type(Integer.class).directive(SizeUnit.FROM, SizeUnit.Unit.MB).directive(SizeUnit.TO, SizeUnit.Unit.MB);

    /**
     Optional ID of an existing volume (that is in the accessible scope of the requesting application).
     (TOSCA Simple Profile in YAML Version 1.1, p. 175)
     */
    public static ToscaKey<String> VOLUME_ID = new ToscaKey<>(PROPERTIES, "volume_id");

    /**
     Optional ID of an existing snapshot that should be used when creating the block storage (volume).
     (TOSCA Simple Profile in YAML Version 1.1, p. 175)
     */
    public static ToscaKey<String> SNAPSHOT_ID = new ToscaKey<>(PROPERTIES, "snapshot_id");

    public static ToscaKey<AttachmentCapability> ATTACHMENT = new ToscaKey<>(CAPABILITIES, "attachment")
        .type(AttachmentCapability.class);

    public BlockStorage(MappingEntity mappingEntity) {
        super(mappingEntity);
        init();
    }

    private void init() {
        setDefault(ATTACHMENT, new AttachmentCapability(getChildEntity(ATTACHMENT)));
    }

    /**
     @return {@link #ATTACHMENT}
     */
    public Optional<AttachmentCapability> getAttachment() {
        return Optional.ofNullable(get(ATTACHMENT));
    }

    /**
     Sets {@link #ATTACHMENT}
     */
    public BlockStorage setAttachment(AttachmentCapability attachment) {
        set(ATTACHMENT, attachment);
        return this;
    }

    /**
     @return {@link #SIZE_IN_MB}
     */
    public Optional<Integer> getSizeInMb() {
        return Optional.ofNullable(get(SIZE_IN_MB));
    }

    /**
     Sets {@link #SIZE_IN_MB}
     */
    public BlockStorage setSizeInMb(Integer sizeInMb) {
        if (sizeInMb < 1) {
            throw new IllegalArgumentException(format("Constraint violation: sizeInMB >= 1; but was '%d'", sizeInMb));
        }
        set(SIZE_IN_MB, sizeInMb);
        return this;
    }

    /**
     @return {@link #VOLUME_ID}
     */
    public Optional<String> getVolumeId() {
        return Optional.ofNullable(get(VOLUME_ID));
    }

    /**
     Sets {@link #VOLUME_ID}
     */
    public BlockStorage setVolumeId(String volumeId) {
        set(VOLUME_ID, volumeId);
        return this;
    }

    /**
     @return {@link #SNAPSHOT_ID}
     */
    public Optional<String> getSnapshotId() {
        return Optional.ofNullable(get(SNAPSHOT_ID));
    }

    /**
     Sets {@link #SNAPSHOT_ID}
     */
    public BlockStorage setSnapshotId(String snapshotId) {
        set(SNAPSHOT_ID, snapshotId);
        return this;
    }

    @Override
    public void accept(NodeVisitor v) {
        v.visit(this);
    }
}


text:
/* eslint-disable react/no-children-prop */
import clsx from 'clsx';
import { RichUtils } from 'draft-js';
import React, { MouseEvent, ReactNode } from 'react';
import { DraftJsStyleButtonType } from '..';

interface CreateBlockStyleButtonProps {
  blockType: string;
  children: ReactNode;
}

export default function createBlockStyleButton({
  blockType,
  children,
}: CreateBlockStyleButtonProps): DraftJsStyleButtonType {
  return function BlockStyleButton(props) {
    const toggleStyle = (event: MouseEvent): void => {
      event.preventDefault();
      props.setEditorState(
        RichUtils.toggleBlockType(props.getEditorState(), blockType)
      );
    };

    const preventBubblingUp = (event: MouseEvent): void => {
      event.preventDefault();
    };

    const blockTypeIsActive = (): boolean => {
      // if the button is rendered before the editor
      if (!props.getEditorState) {
        return false;
      }

      const editorState = props.getEditorState();
      const type = editorState
        .getCurrentContent()
        .getBlockForKey(editorState.getSelection().getStartKey())
        .getType();
      return type === blockType;
    };

    const { theme, buttonProps = {} } = props;
    const className = blockTypeIsActive()
      ? clsx(theme.button, theme.active)
      : theme.button;

    return (
      <div className={theme.buttonWrapper} onMouseDown={preventBubblingUp}>
        <button
          children={children}
          {...buttonProps}
          className={className}
          onClick={toggleStyle}
          type="button"
          role="button"
          aria-label={`create ${blockType}`}
        />
      </div>
    );
  };
}


text:
require 'spec_helper'

describe Puppet::Parser::Functions.function(:validate_string) do
  let(:scope) { PuppetlabsSpec::PuppetInternals.scope }

  describe 'when calling validate_string from puppet' do

    %w{ foo bar baz }.each do |the_string|

      it "should compile when #{the_string} is a string" do
        Puppet[:code] = "validate_string('#{the_string}')"
        scope.compiler.compile
      end

      it "should compile when #{the_string} is a bare word" do
        Puppet[:code] = "validate_string(#{the_string})"
        scope.compiler.compile
      end

    end

    %w{ true false }.each do |the_string|
      it "should compile when #{the_string} is a string" do
        Puppet[:code] = "validate_string('#{the_string}')"
        scope.compiler.compile
      end

      it "should not compile when #{the_string} is a bare word" do
        Puppet[:code] = "validate_string(#{the_string})"
        expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a string/)
      end
    end

    it "should compile when multiple string arguments are passed" do
      Puppet[:code] = <<-'ENDofPUPPETcode'
        $foo = ''
        $bar = 'two'
        validate_string($foo, $bar)
      ENDofPUPPETcode
      scope.compiler.compile
    end

    it "should compile when an explicitly undef variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do
      Puppet[:code] = <<-'ENDofPUPPETcode'
        $foo = undef
        validate_string($foo)
      ENDofPUPPETcode
      scope.compiler.compile
    end

    it "should compile when an undefined variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do
      Puppet[:code] = <<-'ENDofPUPPETcode'
        validate_string($foobarbazishouldnotexist)
      ENDofPUPPETcode
      scope.compiler.compile
    end
  end
end


text:
#include "tests_common.hpp"
#include "check_iteration.hpp"

typedef containers::ternary_tree<std::string, const char*> Tst_LM_Test;

// test a single case
bool longest_match_check(Tst_LM_Test& tst, const std::string& str, const std::string& expect)
{
	typedef Tst_LM_Test Tst;
	const char* beg = str.data();
	const char* end = str.data() + str.size();
	Tst::iterator it = tst.longest_match(beg, end);
	BOOST_CHECK(std::string(it.key()) == expect);
	BOOST_CHECK(std::string(it.key()) == std::string(str.data(), beg));
	return expect.empty() == (it == tst.end());
}

int longest_match_test()
{
	long result = errors_counter();
	typedef Tst_LM_Test Tst;
	Tst names;

	// Arjen Wagenar's test case (+2)
    names["Amsterdam"] = "Amsterdam";
    names["San Francisco"] = "San Francisco";
    names["New York"] = "New York";
    names["Brussels"] = "Brussels";
	BOOST_CHECK(longest_match_check(names, "X", ""));
	BOOST_CHECK(longest_match_check(names, "A", ""));
	BOOST_CHECK(longest_match_check(names, "Ams", ""));
	BOOST_CHECK(longest_match_check(names, "New", ""));
	BOOST_CHECK(longest_match_check(names, "Amsterdam the", "Amsterdam"));
	// ...which is not equivalent with the following,
	// since it gives different tree structure...

	//names.clear();
	names["abc"] = "abc";
	names["ab"] = "ab";
	names["a"] = "a";
	BOOST_CHECK(longest_match_check(names, "ax", "a"));
	BOOST_CHECK(longest_match_check(names, "bc", ""));
	names.erase("a");
	BOOST_CHECK(longest_match_check(names, "ax", ""));
	BOOST_CHECK(longest_match_check(names, "a", ""));
	names["a"] = "a";
	BOOST_CHECK(longest_match_check(names, "ax", "a"));
	BOOST_CHECK(longest_match_check(names, "abx", "ab"));
	// exercise shorter-than-matched backing-up (from "bcd" to "bc")
	names["bcdab"] = "bcdab";
	names["bcdef"] = "bcdef";
	names["bcde"] = "bcde";
	names["bcdaa"] = "bcdaa";
	names["bc"] = "bc";
	BOOST_CHECK(longest_match_check(names, "bcdx", "bc"));
	// and back-up past erase (from "bcdefg" past erased "bcdef" to "bc")
	names["bcdefgh"] = "bcdefgh";
	names.erase("bcdef");
	BOOST_CHECK(longest_match_check(names, "bcdefgx", "bcde"));
	names.erase("bcde");
	BOOST_CHECK(longest_match_check(names, "bcdefgx", "bc"));
	// erased
	names.erase("a");
	BOOST_CHECK(longest_match_check(names, "ax", ""));

	return errors_counter() - result;
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views import defaults as default_views
from django.views.generic import TemplateView

import config.api

urlpatterns = [  # :off

    # Django Admin, use {% url 'admin:index' %}
    url(settings.ADMIN_URL, include(admin.site.urls)),

    # User management
    url(r'^users/', include("annotation_tool.users.urls", namespace="users")),
    url(r'^accounts/', include('allauth.urls')),

    # Your stuff: custom urls includes go here
    url(r'^api/', include(config.api)),
    url(r'^(?P<path>(?:assets|scripts|styles)/.*)$','django.contrib.staticfiles.views.serve'),
    url('^$', TemplateView.as_view(template_name='index.html'))

]  # :on

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [url(r'^400/$', default_views.bad_request), url(r'^403/$', default_views.permission_denied),
                    url(r'^404/$', default_views.page_not_found), url(r'^500/$', default_views.server_error), ]


text:
var gulp = require('gulp');
var gutil = require("gulp-util");

gulp.task('coveralls', function (done) {
  return submitToCoveralls('test/reports/coverage/report-lcov/lcov.info', function(){
  done();
  });
});

function submitToCoveralls(fileName, callback) {
  gutil.log(gutil.colors.cyan('Coveralls:', 'Submitting file to coveralls.io: ' + fileName));

  var coveralls = require('coveralls');

  // Override coveralls option processing until it handles use as a srcrary better (TODO)
  coveralls.getOptions = coveralls.getBaseOptions;
  console.log(coveralls.getBaseOptions);

  var fs = require('fs');

  fs.readFile(fileName, 'utf8', function(err, fileContent) {
    if (err) {
      gutil.log('Coveralls:', "Failed to read file '" + fileName + "', with error: " + err);
      return callback(false);
    }

    coveralls.handleInput(fileContent, function(err) {
      if (err) {
        gutil.log('Coveralls:', "Failed to submit '" + fileName + "' to coveralls: " + err);
        return callback(false);
      }

      gutil.log('Coveralls:', "Successfully submitted " + fileName + " to coveralls");
      callback(true);
    });
  });
}


text:
package bdv.tools.transformation;

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

import mpicbg.spim.data.XmlHelpers;
import net.imglib2.realtransform.AffineTransform3D;

import org.jdom2.Element;

public class XmlIoTransformedSources
{
	public static final String SOURCETRANSFORMS_TAG = "ManualSourceTransforms";

	public static final String SOURCETRANSFORM_TAG = "SourceTransform";
	public static final String SOURCETRANSFORM_TYPE_ATTRIBUTE_NAME = "type";
	public static final String SOURCETRANSFORM_TYPE_VALUE_AFFINE = "affine";
	public static final String SOURCETRANSFORM_AFFINE_TAG = "affine";

	public String getTagName()
	{
		return SOURCETRANSFORMS_TAG;
	}

	public ManualSourceTransforms fromXml( final Element elem )
	{
		final ArrayList< AffineTransform3D > transforms = new ArrayList<>();
		for ( final Element t : elem.getChildren( SOURCETRANSFORM_TAG ) )
			transforms.add( fromXmlAffine( t ) );
		return new ManualSourceTransforms( transforms );
	}

	public Element toXml( final ManualSourceTransforms manualSourceTransforms )
	{
		final Element elem = new Element( SOURCETRANSFORMS_TAG );
		final List< AffineTransform3D > transforms = manualSourceTransforms.getTransforms();
		for ( final AffineTransform3D t : transforms )
			elem.addContent( toXmlAffine( t ) );
		return elem;
	}

	protected AffineTransform3D fromXmlAffine( final Element transform )
	{
		final AffineTransform3D affine = XmlHelpers.getAffineTransform3D( transform, SOURCETRANSFORM_AFFINE_TAG );
		return affine;
	}

	protected Element toXmlAffine( final AffineTransform3D transform )
	{
		final Element elem = new Element( SOURCETRANSFORM_TAG );
		elem.setAttribute( SOURCETRANSFORM_TYPE_ATTRIBUTE_NAME, SOURCETRANSFORM_TYPE_VALUE_AFFINE );
		elem.addContent( XmlHelpers.affineTransform3DElement( SOURCETRANSFORM_AFFINE_TAG, transform ) );
		return elem;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using LanguageExt;

namespace SJP.Schematic.Core.Comments
{
    public sealed class EmptyDatabaseViewCommentProvider : IDatabaseViewCommentProvider
    {
        public OptionAsync<IDatabaseViewComments> GetViewComments(Identifier viewName, CancellationToken cancellationToken = default)
        {
            if (viewName == null)
                throw new ArgumentNullException(nameof(viewName));

            return OptionAsync<IDatabaseViewComments>.None;
        }

        public IAsyncEnumerable<IDatabaseViewComments> GetAllViewComments(CancellationToken cancellationToken = default) => AsyncEnumerable.Empty<IDatabaseViewComments>();
    }
}


text:
using AutoMapper;
using Wilson.Accounting.Core.Entities;
using Wilson.Accounting.Core.Entities.ValueObjects;
using Wilson.Web.Areas.Accounting.Models.HomeViewModels;
using Wilson.Web.Areas.Accounting.Models.SharedViewModels;

namespace Wilson.Web.Areas.Accounting.Configurations
{
    public class AutoMapperAccountingProfileConfiguration : Profile
    {
        public AutoMapperAccountingProfileConfiguration()
        {
            CreateMap<Employee, EmployeeViewModel>();
            CreateMap<Payment, PaymentViewModel>();
            CreateMap<Paycheck, PaycheckViewModel>()
                .ForMember(x => x.Payments, opt => opt.ResolveUsing<PaychekPaymentsResolver>())
                .ForMember(x => x.Period, opt => opt.ResolveUsing<PeriodResolver<Paycheck, PaycheckViewModel>>());
        }
    }
}


text:
require 'soap/element'

module SOAP
module Header

class Handler
  attr_reader :elename
  attr_reader :mustunderstand
  attr_reader :encodingstyle

  def initialize(elename)
    @elename = elename
    @mustunderstand = false
    @encodingstyle = nil
  end

  # Should return a SOAP/OM, a SOAPHeaderItem or nil.
  def on_outbound
    nil
  end

  # Given header is a SOAPHeaderItem or nil.
  def on_inbound(header, mustunderstand = false)
    # do something.
  end

  def on_outbound_headeritem
    item = on_outbound
    if item.nil?
      nil
    elsif item.is_a?(::SOAP::SOAPHeaderItem)
      item.elename = @elename
      item
    else
      item.elename = @elename
      ::SOAP::SOAPHeaderItem.new(item, @mustunderstand, @encodingstyle)
    end
  end

  def on_inbound_headeritem(header)
    on_inbound(header.element, header.mustunderstand)
  end
end

end
end


text:
package gigigo.com.orchextra.data.datasources.api.model.requests;

import com.gigigo.orchextra.domain.model.entities.credentials.Credentials;

public class OrchextraApiSdkAuthRequest extends OrchextraApiAuthRequest {

  public OrchextraApiSdkAuthRequest(GrantType grantType, Credentials credentials) {
    super(grantType, credentials);
  }

  @Override ApiCredentials obtainApiCredentialsFromCredentials(Credentials credentials) {
    return new ApiSdkAuthCredentials(credentials);
  }
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
// Keep the Input import for now, we'll remove it later:
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var router_2 = require('@angular/router');
var common_1 = require('@angular/common');
var hero_service_1 = require('../shared/hero.service');
var TowerDetailComponent = (function () {
    function TowerDetailComponent(router, heroService, route, location) {
        this.router = router;
        this.heroService = heroService;
        this.route = route;
        this.location = location;
    }
    TowerDetailComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.route.params.forEach(function (params) {
            var id = params['id'];
            _this.heroService.getTower(id)
                .then(function (tower) { return _this.tower = tower; });
        });
    };
    TowerDetailComponent.prototype.goBack = function () {
        this.location.back();
    };
    TowerDetailComponent.prototype.save = function (tower, isValid) {
        var _this = this;
        if (isValid)
            this.heroService.updateTower(this.tower)
                .then(function () { return _this.goBack(); });
    };
    TowerDetailComponent.prototype.gotoHeroes = function (tower) {
        this.router.navigate(['/towers/' + this.tower._id + '/heroes/']);
    };
    TowerDetailComponent = __decorate([
        core_1.Component({
            moduleId: module.id,
            selector: 'tower-detail',
            templateUrl: 'tower-detail.component.html',
            styleUrls: ['tower-detail.component.css']
        }),
        __metadata('design:paramtypes', [router_2.Router, hero_service_1.HeroService, router_1.ActivatedRoute, common_1.Location])
    ], TowerDetailComponent);
    return TowerDetailComponent;
}());
exports.TowerDetailComponent = TowerDetailComponent;
//# sourceMappingURL=tower-detail.component.js.map


text:
cask 'toggldesktop' do
  version :latest
  sha256 :no_check

  url 'https://www.toggl.com/api/v8/installer?app=td&platform=darwin&channel=stable'
  appcast 'https://assets.toggl.com/installers/darwin_stable_appcast.xml',
          :sha256 => '9ab19ddd0df173611eeb42344254e108b36583f517e91561cbeff997897d85df'
  name 'TogglDesktop'
  homepage 'https://www.toggl.com'
  license :bsd

  app 'TogglDesktop.app'
end


text:
<!DOCTYPE html>

<title>How do I enable student peer review for an assignment?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.assignment" name="description">
<meta content="peer review, peer assessment, peer evaluation" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="../css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How to I add multiple parts to an assessment?

This explains how to create additional parts to assessment. Parts are often used to set up random question sets that pull questions from question pools.

Go to Tests & Quizzes.

Select the Tests & Quizzes tool from the Tool Menu in your site.

Select an assessment.

Parts may be added to any assessment. Select an existing assessment or create a new one.

Create a New Assessment.

Click Add.

For more information on creating new assessments, see How do I create an assessment?

Or edit an existing assessment.

Click Add Part.

Add a Title.

Type a title into the text box provided.

Note: If the part title is marked as the Default, the title will not appear to assessment takers.

Add Information. (Optional)

Use the text box provided to type Information about the created part.

Note: To edit with Rich-Text Editor, click the hyperlink to open the full menu.

Add attachment. (Optional)

Click Add Attachments to browse for and select a file attachment if desired.

Select Part Type.

Choose the option to author questions one-on-one or select random draw from question pool.

If "Questions authored one-by-one" is selected, the following options will display.

Select the radio button to order the questions As listed on Assessment Questions page, or to order them Random within Part.

If "Random draw from question pool" is selected, the following options will display.

Enter the number of questions to draw from the selected question pool.

Select the question pool from the drop-down menu.

Choose to either randomize student questions each time an assessment is submitted or randomize student questions once for all submissions.

Enter the point value for correct answers on each question. Note that all questions in this random draw must be worth the same amount of points.

(Optional) For True/False and Multiple Choice, Single Correct questions, you may also enter a negative point value if a question is answered incorrectly.

Note: Point values entered here override any value that was specified for individual questions in the corresponding Question Pool.

Add Metadata. (Optional)

Enter Metadata, such as the objective, keyword, and rubric, into the text boxes provided.

Click Save.

Click Save to save the question (or Cancel to exit).


text:
package io.lettuce.core.dynamic.annotation;

import java.lang.annotation.*;

/**
 * Command naming strategy for Redis command methods. Redis command methods name can be provided either by annotating method
 * with {@link Command} or derived from its name. Annotate a command interface or method with {@link CommandNaming} to set a
 * command naming {@link Strategy}.
 *
 * @author Mark Paluch
 * @since 5.0
 * @see Command
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
public @interface CommandNaming {

    /**
     * Apply a naming {@link Strategy} to transform the method name into a Redis command name.
     */
    Strategy strategy() default Strategy.DEFAULT;

    /**
     * Adjust letter case, defaults to {@link LetterCase#UPPERCASE}.
     */
    LetterCase letterCase() default LetterCase.DEFAULT;

    public enum Strategy {

        /**
         * Replace camel humps with spaces and split the method name into multiple command segments. A method named
         * {@code clientSetname} would issue a command {@code CLIENT SETNAME}.
         */
        SPLIT,

        /**
         * Replace camel humps with spaces. A method named {@code nrRun} would issue a command named {@code NR.RUN}.
         */
        DOT,

        /**
         * Passthru the command as-is. A method named {@code clientSetname} would issue a command named {@code CLIENTSETNAME}.
         */
        METHOD_NAME,

        /**
         * Not defined here which defaults to {@link #SPLIT} if nothing else found.
         */
        DEFAULT;
    }

    public enum LetterCase {
        /**
         * Keep command name as specified.
         */
        AS_IS,

        /**
         * Convert command to uppercase.
         */
        UPPERCASE,

        /**
         * Not defined here which defaults to {@link #UPPERCASE} if nothing else found.
         */
        DEFAULT;
    }

}


text:
#ifndef _AST_TYPE_VAR_H_
#define _AST_TYPE_VAR_H_

#include "ASTNode.h"
class ASTVisitor;

#include <string>

class ASTTypeVar : public ASTNode
{
public:
    ASTNode *type; // ASTTypeSeq for usual variables, ASTType for internal variables (e.g. xs:anyType for fun-def variables)

    ASTNode *var; // ASTVar

public:
    ASTTypeVar(const ASTNodeCommonData &loc, ASTNode *typep, ASTNode *vard) : ASTNode(loc), type(typep), var(vard) {}

    ~ASTTypeVar();

    void accept(ASTVisitor &v);
    ASTNode *dup();
    void modifyChild(const ASTNode *oldc, ASTNode *newc);

    static ASTNode *createNode(scheme_list &sl);
};

#endif


text:
from django.conf.urls import *
from django.views.static import serve
import os

JAVASCRIPT_PATH = "%s/js" % os.path.dirname(__file__)

urlpatterns = patterns('ajax.views',
    (r'^(?P<application>\w+)/(?P<model>\w+).json', 'endpoint_loader'),
    (r'^(?P<application>\w+)/(?P<model>\w+)/(?P<method>\w+).json', 'endpoint_loader'),
    (r'^(?P<application>\w+)/(?P<model>\w+)/(?P<pk>\d+)/(?P<method>\w+)/?(?P<taggit_command>(add|remove|set|clear|similar))?.json$', 'endpoint_loader'),
    (r'^js/(?P<path>.*)$', serve,
        {'document_root': JAVASCRIPT_PATH}),
)


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dtes = require("./src/dtes");
var firma = require("./src/firma_electronica");
var periodos = require("./src/periodo");
var responses = require("./src/responses");
var DteService = require("./src/dte-service");
var app_data_1 = require("./src/app-data");
exports.appData = app_data_1.default;
exports.dte = dtes;
exports.firma = firma;
exports.periodos = periodos;
exports.responses = responses;
exports.DteService = DteService;
//# sourceMappingURL=index.js.map


text:
package org.mifos.accounts.loan.schedule.domain;

import java.math.BigDecimal;
import java.util.Date;

public class InstallmentBuilder {
    private Installment installment;
    private InstallmentPayment installmentPayment;

    public InstallmentBuilder(String installmentId) {
        installment = new Installment();
        installmentPayment = installment.getCurrentPayment();
        installment.recordCurrentPayment();
        withInstallmentId(installmentId).
                withDueDate(new Date(0)).withPaymentDate(new Date(0)).
                withPrincipal(0).withPrincipalPaid(0).
                withInterest(0).withInterestPaid(0).
                withExtraInterest(0).withExtraInterestPaid(0).
                withFees(0).withFeesPaid(0).
                withMiscFees(0).withMiscFeesPaid(0).
                withPenalty(0).withPenaltyPaid(0).
                withMiscPenalty(0).withMiscPenaltyPaid(0);
    }

    public InstallmentBuilder withInstallmentId(String installmentId) {
        installment.setId(Integer.valueOf(installmentId));
        return this;
    }

    public InstallmentBuilder withPrincipal(double principal) {
        installment.setAmount(InstallmentComponent.PRINCIPAL, BigDecimal.valueOf(principal));
        return this;
    }

    public InstallmentBuilder withInterest(double interest) {
        installment.setAmount(InstallmentComponent.INTEREST, BigDecimal.valueOf(interest));
        return this;
    }

    public InstallmentBuilder withExtraInterest(double extraInterest) {
        installment.setAmount(InstallmentComponent.EXTRA_INTEREST, BigDecimal.valueOf(extraInterest));
        return this;
    }

    public InstallmentBuilder withFees(double fees) {
        installment.setAmount(InstallmentComponent.FEES, BigDecimal.valueOf(fees));
        return this;
    }

    public InstallmentBuilder withMiscFees(double miscFees) {
        installment.setAmount(InstallmentComponent.MISC_FEES, BigDecimal.valueOf(miscFees));
        return this;
    }

    public InstallmentBuilder withPenalty(double penalty) {
        installment.setAmount(InstallmentComponent.PENALTY, BigDecimal.valueOf(penalty));
        return this;
    }

    public InstallmentBuilder withMiscPenalty(double miscPenalty) {
        installment.setAmount(InstallmentComponent.MISC_PENALTY, BigDecimal.valueOf(miscPenalty));
        return this;
    }

    public InstallmentBuilder withPrincipalPaid(double principalPaid) {
        installmentPayment.setAmount(InstallmentComponent.PRINCIPAL, BigDecimal.valueOf(principalPaid));
        return this;
    }

    public InstallmentBuilder withInterestPaid(double interestPaid) {
        installmentPayment.setAmount(InstallmentComponent.INTEREST, BigDecimal.valueOf(interestPaid));
        return this;
    }

    public InstallmentBuilder withExtraInterestPaid(double extraInterestPaid) {
        installmentPayment.setAmount(InstallmentComponent.EXTRA_INTEREST, BigDecimal.valueOf(extraInterestPaid));
        return this;
    }

    public InstallmentBuilder withFeesPaid(double fees) {
        installmentPayment.setAmount(InstallmentComponent.FEES, BigDecimal.valueOf(fees));
        return this;
    }

    public InstallmentBuilder withMiscFeesPaid(double miscFeesPaid) {
        installmentPayment.setAmount(InstallmentComponent.MISC_FEES, BigDecimal.valueOf(miscFeesPaid));
        return this;
    }

    public InstallmentBuilder withPenaltyPaid(double penaltyPaid) {
        installmentPayment.setAmount(InstallmentComponent.PENALTY, BigDecimal.valueOf(penaltyPaid));
        return this;
    }

    public InstallmentBuilder withMiscPenaltyPaid(double miscPenaltyPaid) {
        installmentPayment.setAmount(InstallmentComponent.MISC_PENALTY, BigDecimal.valueOf(miscPenaltyPaid));
        return this;
    }

    public InstallmentBuilder withDueDate(Date dueDate) {
        installment.setDueDate(dueDate);
        return this;
    }

    public InstallmentBuilder withPaymentDate(Date paymentDate) {
        installment.setDueDate(paymentDate);
        return this;
    }

    public Installment build() {
        return installment;
    }
}


text:
官方文档链接  https://reactnavigation.org/docs/navigation-prop.html

this.props.navigation新增4个Action:

1. Push  与navigate类似,向前跳转
   `navigation.push(routeName, params, action)`

2. Pop  栈里弹出一个页面,回到上级,参数n表示向上弹出多少个页面
   `navigation.pop(n)`

3. PopToTop  返回第一个页面,关闭其他所有
   `navigation.popToTop()`

4. Replace  将当前页面换成其他页面
   `navigation.replace(routeName, params, action)`

新增addListener 监听页面生命周期:

`1.willBlur 即将失去焦点`

2.willFocus 即将获得焦点

3.didFocus 获得焦点

4.didBlur 失去焦点

did的两个状态会在页面切换结束后发生

```js
const didBlurSubscription = this.props.navigation.addListener(
  'didBlur',     //失去焦点后打印信息
  payload => {
    console.debug('didBlur', payload);
  }
);

// 在完成后取消监听事件
didBlurSubscription.remove();
```

isFocused 判断当前页面是否获得焦点

```js
let isFocused = this.props.navigation.isFocused(); //true获取false未获取
```

state 返回当前navigation的状态,自定义Action里需要的key可以在这里获取

```js
{
  // 页面名称
  routeName: 'profile',
  // 页面的key值
  key: 'main0',
  // 参数
  params: { hello: 'world' }
}
```

setParams,getParm 设置/获取navigation的参数params

非页面(如自定义组件)现在提供了获取导航器的方法 withNavigation

```js
import React from 'react';
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';

class MyBackButton extends React.Component {
  render() {
    return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
  }
}

// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);    //调用withNavigation(Component)后,可以使用this.props.navigation获取导航器,此方法返回Component
```

withNavigationFocus除了为非页面组件提供navigation,还提供了isFocused属性判断组件是否获取焦点

```js
import React from 'react';
import { Text } 'react-native';
import { withNavigationFocus } from 'react-navigation';

class FocusStateLabel extends React.Component {
  render() {
    return <Text>{this.props.isFocused ? 'Focused' : 'Not focused'}</Text>;
  }
}

// withNavigationFocus returns a component that wraps FocusStateLabel and passes
// in the navigation prop
export default withNavigationFocus(FocusStateLabel);
```


text:
using System;
using System.Collections.Generic;
using System.Text;
using TestHelperExtensions;

namespace PPTail.Data.MediaBlog.Test
{
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    public static class MediaPostBuilderExtensions
    {
        const Int32 _maxTags = 30;

        public static MediaPostBuilder UseRandomFlickrPost(this MediaPostBuilder builder)
        {
            var tags = new List<string>();
            for (Int32 i = 0; i < _maxTags.GetRandom(); i++)
            {
                tags.Add(string.Empty.GetRandom());
            }

            var flickrImage = new FlickrMediaItemBuilder()
                .UseRandom()
                .Build();

            return builder
                .AddFlickrImage(flickrImage)
                .Author(string.Empty.GetRandom())
                .Description(string.Empty.GetRandom())
                .IsPublished(true.GetRandom())
                .Posted(DateTime.Now.AddYears(30).GetRandom(DateTime.Now.AddYears(-10)))
                .AddTags(tags)
                .Title(string.Empty.GetRandom());
        }

        public static MediaPostBuilder UseRandomYouTubePost(this MediaPostBuilder builder)
        {
            var tags = new List<string>();
            for (Int32 i = 0; i < _maxTags.GetRandom(); i++)
            {
                tags.Add(string.Empty.GetRandom());
            }

            var youTubeVideo = new YouTubeMediaItemBuilder()
                .UseRandom()
                .Build();

            return builder
                .AddYouTubeVideo(youTubeVideo)
                .Author(string.Empty.GetRandom())
                .Description(string.Empty.GetRandom())
                .IsPublished(true.GetRandom())
                .Posted(DateTime.Now.AddYears(30).GetRandom(DateTime.Now.AddYears(-10)))
                .AddTags(tags)
                .Title(string.Empty.GetRandom());
        }

        public static MediaPostBuilder UseRandomEmptyPost(this MediaPostBuilder builder)
        {
            var tags = new List<string>();
            for (Int32 i = 0; i < _maxTags.GetRandom(); i++)
            {
                tags.Add(string.Empty.GetRandom());
            }

            var emptyPost = new EmptyMediaItemBuilder()
                .UseRandom()
                .Build();

            return builder
                .AddEmptyPost(emptyPost.Title, emptyPost.DisplayWidth, emptyPost.DisplayHeight, emptyPost.CreateDate)
                .Author(string.Empty.GetRandom())
                .Description(string.Empty.GetRandom())
                .IsPublished(true.GetRandom())
                .Posted(DateTime.Now.AddYears(30).GetRandom(DateTime.Now.AddYears(-10)))
                .AddTags(tags)
                .Title(string.Empty.GetRandom());
        }
    }
}


text:
package info.dgjones.st2x.transform.method.intra;

import java.util.List;

import info.dgjones.st2x.JavaMethod;
import info.dgjones.st2x.javatoken.JavaBlockEnd;
import info.dgjones.st2x.javatoken.JavaBlockStart;
import info.dgjones.st2x.javatoken.JavaCallEnd;
import info.dgjones.st2x.javatoken.JavaCallStart;
import info.dgjones.st2x.javatoken.JavaIdentifier;
import info.dgjones.st2x.javatoken.JavaKeyword;
import info.dgjones.st2x.javatoken.JavaParenthesisEnd;
import info.dgjones.st2x.javatoken.JavaParenthesisStart;
import info.dgjones.st2x.javatoken.JavaStatementTerminator;
import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory;

/**
 * TODO this class only exists because of limitations of choosing transformOnly with a String
 */
public class TransformGenericCrossRegionIntersects extends AbstractMethodBodyTransformation {

	public TransformGenericCrossRegionIntersects() {
		super();
	}
	public TransformGenericCrossRegionIntersects(TokenMatcherFactory factory) {
		super(factory);
	}

	protected TokenMatcher matchers(TokenMatcherFactory factory) {
		return factory.seq(
				factory.token(JavaIdentifier.class, "others"),
				factory.token(JavaCallStart.class, "destroy"),
				factory.token(JavaCallEnd.class),
				factory.token(JavaStatementTerminator.class));
	}

	protected int transform(JavaMethod javaMethod, List tokens, int i) {
		if (!javaMethod.getQualifiedName().equals("GenericCrossRegion.intersects")) {
			return i;
		}
		tokens.add(i+4, new JavaBlockEnd());

		int j = i;
		tokens.add(j++, new JavaKeyword("if"));
		tokens.add(j++, new JavaParenthesisStart());
		tokens.add(j++, new JavaIdentifier("others"));
		tokens.add(j++, new JavaKeyword("!="));
		tokens.add(j++, new JavaKeyword("null"));
		tokens.add(j++, new JavaParenthesisEnd());
		tokens.add(j++, new JavaBlockStart());

		return j+1;
	}
}


text:
import fnmatch
import inspect
import os
import re

def DiscoverModules(start_dir, top_level_dir, pattern='*'):
  """Discover all modules in |start_dir| which match |pattern|.

  Args:
    start_dir: The directory to recursively search.
    top_level_dir: The top level of the package, for importing.
    pattern: Unix shell-style pattern for filtering the filenames to import.

  Returns:
    list of modules.
  """
  modules = []
  for dir_path, _, filenames in os.walk(start_dir):
    for filename in filenames:
      # Filter out unwanted filenames.
      if filename.startswith('.') or filename.startswith('_'):
        continue
      if os.path.splitext(filename)[1] != '.py':
        continue
      if not fnmatch.fnmatch(filename, pattern):
        continue

      # Find the module.
      module_rel_path = os.path.relpath(os.path.join(dir_path, filename),
                                        top_level_dir)
      module_name = re.sub(r'[/\\]', '.', os.path.splitext(module_rel_path)[0])

      # Import the module.
      module = __import__(module_name, fromlist=[True])

      modules.append(module)
  return modules

# TODO(dtu): Normalize all discoverable classes to have corresponding module
# and class names, then always index by class name.
def DiscoverClasses(start_dir, top_level_dir, base_class, pattern='*',
                    index_by_class_name=False):
  """Discover all classes in |start_dir| which subclass |base_class|.

  Args:
    start_dir: The directory to recursively search.
    top_level_dir: The top level of the package, for importing.
    base_class: The base class to search for.
    pattern: Unix shell-style pattern for filtering the filenames to import.
    index_by_class_name: If True, use class name converted to
        lowercase_with_underscores instead of module name in return dict keys.

  Returns:
    dict of {module_name: class} or {underscored_class_name: class}
  """
  modules = DiscoverModules(start_dir, top_level_dir, pattern)
  classes = {}
  for module in modules:
    for _, obj in inspect.getmembers(module):
      if (inspect.isclass(obj) and obj is not base_class and
          issubclass(obj, base_class)):
        if index_by_class_name:
          key_name = re.sub('(?!^)([A-Z]+)', r'_\1', obj.__name__).lower()
        else:
          key_name = module.__name__.split('.')[-1]
        classes[key_name] = obj

  return classes