text:
'use strict';

import * as React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import Text from '../../../Text/Text';
import TouchableNativeFeedback from '../TouchableNativeFeedback';
import View from '../../View/View';

const render = require('../../../../jest/renderer');

describe('TouchableWithoutFeedback', () => {
  it('renders correctly', () => {
    const instance = render.create(
      <TouchableNativeFeedback style={{}}>
        <Text>Touchable</Text>
      </TouchableNativeFeedback>,
    );

    expect(instance.toJSON()).toMatchSnapshot();
  });

  it('has displayName', () => {
    expect(TouchableNativeFeedback.displayName).toEqual(
      'TouchableNativeFeedback',
    );
  });
});

describe('<TouchableNativeFeedback />', () => {
  it('should render as expected', () => {
    const instance = ReactTestRenderer.create(
      <TouchableNativeFeedback>
        <View />
      </TouchableNativeFeedback>,
    );

    expect(instance.toJSON()).toMatchSnapshot();
  });
});

describe('<TouchableNativeFeedback disabled={true}>', () => {
  it('should be disabled when disabled is true', () => {
    expect(
      ReactTestRenderer.create(
        <TouchableNativeFeedback disabled={true}>
          <View />
        </TouchableNativeFeedback>,
      ),
    ).toMatchSnapshot();
  });
});

describe('<TouchableNativeFeedback disabled={true} accessibilityState={{}}>', () => {
  it('should be disabled when disabled is true and accessibilityState is empty', () => {
    expect(
      ReactTestRenderer.create(
        <TouchableNativeFeedback disabled={true} accessibilityState={{}}>
          <View />
        </TouchableNativeFeedback>,
      ),
    ).toMatchSnapshot();
  });
});

describe('<TouchableNativeFeedback disabled={true} accessibilityState={{checked: true}}>', () => {
  it('should keep accessibilityState when disabled is true', () => {
    expect(
      ReactTestRenderer.create(
        <TouchableNativeFeedback
          disabled={true}
          accessibilityState={{checked: true}}>
          <View />
        </TouchableNativeFeedback>,
      ),
    ).toMatchSnapshot();
  });
});

describe('<TouchableNativeFeedback disabled={true} accessibilityState={{disabled:false}}>', () => {
  it('should overwrite accessibilityState with value of disabled prop', () => {
    expect(
      ReactTestRenderer.create(
        <TouchableNativeFeedback
          disabled={true}
          accessibilityState={{disabled: false}}>
          <View />
        </TouchableNativeFeedback>,
      ),
    ).toMatchSnapshot();
  });
});

describe('<TouchableNativeFeedback disabled={false} accessibilityState={{disabled:true}}>', () => {
  it('should overwrite accessibilityState with value of disabled prop', () => {
    expect(
      ReactTestRenderer.create(
        <TouchableNativeFeedback
          disabled={false}
          accessibilityState={{disabled: true}}>
          <View />
        </TouchableNativeFeedback>,
      ),
    ).toMatchSnapshot();
  });
});


text:
FROM python:2-alpine

RUN apk add --no-cache unrar
WORKDIR /usr/src/app

COPY requirements.pip ./
RUN pip install --no-cache-dir -r requirements.pip

COPY . .

CMD [ "python", "./runner.py" ]

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace admin\assets;

class Bower extends \luya\base\Asset
{
    public $sourcePath = '@bower';

    public $js = [
        'angular/angular.min.js',
        'angular-i18n/angular-locale_de-ch.js',
        'angular-resource/angular-resource.min.js',
        'angular-ui-router/release/angular-ui-router.min.js',
        'angular-dragdrop/src/angular-dragdrop.min.js',
        'angular-loading-bar/build/loading-bar.min.js',
        'angular-slugify/angular-slugify.js',
        'twig.js/twig.min.js',
        'ng-wig/dist/ng-wig.min.js',

        'ng-file-upload/ng-file-upload.min.js',
        'ng-file-upload/ng-file-upload-shim.min.js',

        // ace
        // 'ace-builds/src-min-noconflict/ace.js', // "bower-asset/angular-ui-ace" : "0.*@stable",
        // 'angular-ui-ace/ui-ace.js', // "bower-asset/ace-builds" : "1.1.8@stable",
    ];

    public $css = [
        'angular-loading-bar/build/loading-bar.min.css',
        'ng-wig/dist/css/ng-wig.css'
    ];
}


text:
<template name="missions">
    {{#if isMobileDevice}}
        {{> missionsMobile}}
    {{else}}
        {{> missionsDesktop}}
    {{/if}}
</template>


text:
import { c } from 'ttag';

import { Info, InputFieldTwo, TotpInput } from '../../../components';

interface Props {
    type: 'totp' | 'recovery-code';
    code: string;
    error: string;
    loading?: boolean;
    bigger?: boolean;
    setCode: (value: string) => void;
}

const TotpInputs = ({ code, type, setCode, error, loading, bigger }: Props) => {
    return (
        <>
            {type === 'totp' && (
                <>

{c('Info').t`Enter the code from your authenticator app`}

                    <InputFieldTwo
                        id="totp"
                        as={TotpInput}
                        key="totp"
                        length={6}
                        error={error}
                        disableChange={loading}
                        autoFocus
                        autoComplete="one-time-code"
                        value={code}
                        onValue={setCode}
                        bigger={bigger}
                    />
                </>
            )}
            {type === 'recovery-code' && (
                <>

                        {c('Info').t`Each code can only be used once`}{' '}
                        <Info
                            className="ml0-5"
                            title={c('Info')
                                .t`When you set up two-factor authentication, we provide recovery codes which you can use to sign in if you lose access to your authenticator app.`}
                        />

                    <InputFieldTwo
                        id="recovery-code"
                        type="alphabet"
                        key="recovery-code"
                        as={TotpInput}
                        length={8}
                        error={error}
                        disableChange={loading}
                        autoFocus
                        value={code}
                        onValue={setCode}
                        bigger={bigger}
                    />
                </>
            )}
        </>
    );
};
export default TotpInputs;


text:
namespace ui {
class DragSourceWin;
}

namespace views {
class DesktopDropTargetWin;

class VIEWS_EXPORT DesktopDragDropClientWin
    : public aura::client::DragDropClient {
 public:
  DesktopDragDropClientWin(aura::Window* root_window, HWND window);
  ~DesktopDragDropClientWin() override;

  // Overridden from aura::client::DragDropClient:
  int StartDragAndDrop(const ui::OSExchangeData& data,
                       aura::Window* root_window,
                       aura::Window* source_window,
                       const gfx::Point& screen_location,
                       int operation,
                       ui::DragDropTypes::DragEventSource source) override;
  void DragUpdate(aura::Window* target, const ui::LocatedEvent& event) override;
  void Drop(aura::Window* target, const ui::LocatedEvent& event) override;
  void DragCancel() override;
  bool IsDragDropInProgress() override;

  void OnNativeWidgetDestroying(HWND window);

 private:
  bool drag_drop_in_progress_;

  int drag_operation_;

  Microsoft::WRL::ComPtr<ui::DragSourceWin> drag_source_;

  scoped_refptr<DesktopDropTargetWin> drop_target_;

  base::WeakPtrFactory<DesktopDragDropClientWin> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(DesktopDragDropClientWin);
};

}  // namespace views

#endif  // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_WIN_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AISA.Custom_Controls
{
    /// <summary>
    /// Interaction logic for Speech.xaml
    /// </summary>
    public partial class Collapse : UserControl
    {
        public Action Clicked { get; set; }

        public Collapse()
        {
            InitializeComponent();
        }

        private bool clicked = false;

        private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ellipse.Fill = SystemParameters.WindowGlassBrush;
            ellipse.Opacity = .5d;

            clicked = true;
        }

        private void UserControl_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ellipse.Fill = SystemParameters.WindowGlassBrush;
            ellipse.Opacity = 1d;

            if (clicked)
            {
                Clicked();
            }
        }
        public void Activate()
        {
            //Start Storyboard
            var visualDrop = this.FindResource("VisualDropAnimation") as Storyboard;
            visualDrop.Begin();

            //Make the topDrawer visible
            var da = new DoubleAnimation(0, 65, TimeSpan.FromMilliseconds(500));
            topDrawer.BeginAnimation(WidthProperty, da);
            topDrawer.BeginAnimation(HeightProperty, da);

            var opa = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(500));
            topDrawer.BeginAnimation(OpacityProperty, opa);
        }

        public void Deactivate()
        {
            //Stop the Storyboard
            var visualDrop = this.FindResource("VisualDropAnimation") as Storyboard;
            visualDrop.Stop();

            //Add a smoothing animation
            var da = new DoubleAnimation(50, TimeSpan.FromMilliseconds(500));
            ellipse.BeginAnimation(WidthProperty, da);
            ellipse.BeginAnimation(HeightProperty, da);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ellipse.Fill = SystemParameters.WindowGlassBrush;
        }
    }
}


text:
package ai.h2o.sparkling.ml.algos

import ai.h2o.sparkling.ml.internals.H2OModel
import ai.h2o.sparkling.ml.models.{H2OBinaryModel, H2OMOJOModel, H2OStackedEnsembleMOJOModel}
import ai.h2o.sparkling.ml.params.H2OStackedEnsembleParams
import ai.h2o.sparkling.H2OContext
import ai.h2o.sparkling.ml.utils.H2OParamsReadable
import hex.Model
import hex.ensemble.StackedEnsembleModel.StackedEnsembleParameters
import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.ml.param._
import org.apache.spark.ml.util._
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.Dataset

import scala.reflect.ClassTag

/**
  * H2O Stacked Ensemble algorithm exposed via Spark ML pipelines.
  *
  */
class H2OStackedEnsemble(override val uid: String)
  extends H2OSupervisedAlgorithm[StackedEnsembleParameters]
  with H2OStackedEnsembleParams {

  def this() = this(Identifiable.randomUID(classOf[H2OStackedEnsemble].getSimpleName))

  override def fit(dataset: Dataset[_]): H2OStackedEnsembleMOJOModel = {

    if (getBaseAlgorithms().length < 2) {
      throw new IllegalArgumentException("Stacked Ensemble needs at least two base algorithms to operate.")
    }

    val (train, valid) = prepareDatasetForFitting(dataset)
    prepareH2OTrainFrameForFitting(train)

    val baseModels = getBaseAlgorithms().map(alg => alg.trainH2OModel(train, valid))

    val params = getH2OAlgorithmParams(train) ++
      Map(
        "training_frame" -> train.frameId,
        "model_id" -> convertModelIdToKey(getModelId()),
        "base_models" -> modelsIdsToString(baseModels)) ++
      valid
        .map { fr =>
          Map("validation_frame" -> fr.frameId)
        }
        .getOrElse(Map())

    val modelId = trainAndGetDestinationKey(s"/99/ModelBuilders/stackedensemble", params)
    val model = H2OModel(modelId)
    val withCrossValidationModels = if (hasParam("keepCrossValidationModels")) {
      getOrDefault(getParam("keepCrossValidationModels")).asInstanceOf[Boolean]
    } else {
      false
    }

    val result = model
      .toMOJOModel(createMOJOUID(), createMOJOSettings(), withCrossValidationModels)
      .asInstanceOf[H2OStackedEnsembleMOJOModel]

    if (H2OContext.get().forall(_.getConf.isModelPrintAfterTrainingEnabled)) {
      println(result)
    }

    deleteRegisteredH2OFrames()

    if (getKeepBinaryModels()) {
      val downloadedModel = downloadBinaryModel(modelId, H2OContext.ensure().getConf)
      binaryModel = Some(H2OBinaryModel.read("file://" + downloadedModel.getAbsolutePath, Some(modelId)))
    } else {
      model.tryDelete()
      deleteModels(baseModels)
    }

    result
  }

  private def modelsIdsToString(baseModels: Array[H2OMOJOModel]) = {
    modelsIds(baseModels).mkString("[", ",", "]")
  }

  private def modelsIds(baseModels: Seq[H2OMOJOModel]): Seq[String] = {
    baseModels.map(_.mojoFileName)
  }

  private def deleteModels(baseModels: Seq[H2OMOJOModel]): Unit = {
    modelsIds(baseModels).foreach(H2OModel(_).tryDelete())
  }

  @DeveloperApi
  override def transformSchema(schema: StructType): StructType = schema

  override def copy(extra: ParamMap): this.type = defaultCopy(extra)

  override protected def paramTag: ClassTag[StackedEnsembleParameters] =
    scala.reflect.classTag[StackedEnsembleParameters]

  override private[sparkling] def getInputCols(): Array[String] = getFeaturesCols()

  override private[sparkling] def setInputCols(value: Array[String]): this.type = setFeaturesCols(value)
}

object H2OStackedEnsemble extends H2OParamsReadable[H2OStackedEnsemble]


text:
//
//  MusicalScaleAbstract.h
//  MusicalLib
//
/// \author  Created by Hari Karam Singh on 07/09/2011.
//  Copyright (c) 2011-2015 Air Craft Media Ltd.  MIT License.
//

#import <Foundation/Foundation.h>
#import "MusicalNote.h"
#import "MusicalDefs.h"
#import "MusicalScaleDefinition.h"

/**
 Immutable scale object. Scale = definition + musical key. Also contains methods for scale maths.
 */
@interface MusicalScale : NSObject

/////////////////////////////////////////////////////////////////////////
#pragma mark - Life Cycle
/////////////////////////////////////////////////////////////////////////

/** Should generally only be called internally by ScaleFactory */
+ (instancetype)scaleWithDefinition:(MusicalScaleDefinition *)scaleDef key:(MusicalKey)key;
- (instancetype)initWithScaleDefinition:(MusicalScaleDefinition *)scaleDef key:(MusicalKey)key;

/** Make a copy of the scale with a new key */
- (instancetype)scaleWithNewKey:(MusicalKey)newKey;

/** Make a copy of the scale with a new definition (e.g Minor) and the same key */
- (instancetype)scaleWithNewDefinition:(MusicalScaleDefinition *)newScaleDefinition;

/////////////////////////////////////////////////////////////////////////
#pragma mark - Properties
/////////////////////////////////////////////////////////////////////////

/** The underlying key-agnostic, scale definition. */
@property (nonatomic, readonly) MusicalScaleDefinition *scaleDefinition;

@property (nonatomic, readonly) MusicalKey key;

/** Convenience method for the property on the underlying scale definition */
@property (nonatomic, readonly) NSString *name;

/////////////////////////////////////////////////////////////////////////
#pragma mark - Public API
/////////////////////////////////////////////////////////////////////////

/**
 Methods for getting a note in the current key/scale closest to a given note.
 @{
 */
- (MusicalNote *)nearestInKeyNoteGreaterThanOrEqualTo:(MusicalNote *)aNote;
- (MusicalNote *)nearestInKeyNoteLessThanOrEqualTo:(MusicalNote *)aNote;
- (MusicalNote *)nearestInKeyNoteForNote:(MusicalNote *)theNote above:(BOOL)above;
/// @}

/** Checks up and down and returns the closer or the higher if tie  */
//- (MusicalNote *)nearestInKeyNote;

- (MusicalNote *)nearestInKeyNoteForInterval:(MusicalInterval)anInterval note:(MusicalNote *)aStartNote;

/** Returns notes in scale/key in the given range */
- (NSArray *)arrayOfNotesInRangeFrom:(MusicalNote *)fromNote to:(MusicalNote *)toNote;

/** Returns whether the given note name is in this scale/key
 */
- (BOOL)keyIsInScale:(MusicalKey)key;

/**
 Return the idx of the musical note in the scale definition.  C#=Db

 Wrapper for protected method @link getHalfstepDefinitionIndexForKey:

 @return 0 for first note.  NSNotFound
 */
- (NSUInteger)indexOfKeyInScale:(MusicalKey)MusicalKey;

/** Get the note in this key/scale that is relPosition notes away from the reference. E.g. C1 => -3 in C Major = G0

 @param referenceNote   If not in the current scale it will first be snapped to scale in the direction opposite that implied by relPosition
 */
- (MusicalNote *)noteWithScalePosition:(NSInteger)relPosition relativeToNote:(MusicalNote *)referenceNote;

@end


text:
require 'mixer_api/adapters'
require 'mixer_api/client'
require 'mixer_api/request'
require 'mixer_api/version'

module MixerApi
  def self.new(options={})
    MixerApi::Client.new(options)
  end
end


text:
import {AttributeTypes, Reporter, PathReporter, Diagnostic} from '@openmicrostep/msbuildsystem.shared';
import {assert} from 'chai';

function testValidator<T, A0>(validator: AttributeTypes.Validator<T, A0>, value: any, a0: A0, expected: T | undefined, diagnostics: Diagnostic[]) {
  let reporter = new Reporter();
  let at = new PathReporter(reporter);
  let v = validator.validate(at, value, a0);
  if (expected instanceof Set) {
    assert.instanceOf(v, Set);
    expected = <any>Array.from(expected.values());
    v = <any>Array.from((<any>v as Set<any>).values());
  }
  if (expected instanceof Map) {
    assert.instanceOf(v, Map);
    expected = <any>Array.from(expected.entries());
    v = <any>Array.from((<any>v as Map<any, any>).entries());
  }
  assert.notInstanceOf(v, Set);
  assert.notInstanceOf(v, Map);
  assert.deepEqual(v, expected);
  assert.deepEqual(reporter.diagnostics, diagnostics);
}

function validateAny() {
  testValidator(AttributeTypes.validateAny, undefined, undefined, undefined, []);
  testValidator(AttributeTypes.validateAny, true, undefined, true, []);
  testValidator(AttributeTypes.validateAny, false, undefined, false, []);
  testValidator(AttributeTypes.validateAny, "mystring", undefined, "mystring", []);
  testValidator(AttributeTypes.validateAny, ["myarray"], undefined, ["myarray"], []);
  testValidator(AttributeTypes.validateAny, { "mykey": ["myarray"] }, undefined, { "mykey": ["myarray"] }, []);
}
function validateAnyToUndefined() {
  testValidator(AttributeTypes.validateAnyToUndefined, undefined, undefined, undefined, []);
  testValidator(AttributeTypes.validateAnyToUndefined, true, undefined, undefined, []);
  testValidator(AttributeTypes.validateAnyToUndefined, false, undefined, undefined, []);
  testValidator(AttributeTypes.validateAnyToUndefined, "mystring", undefined, undefined, []);
  testValidator(AttributeTypes.validateAnyToUndefined, ["myarray"], undefined, undefined, []);
  testValidator(AttributeTypes.validateAnyToUndefined, { "mykey": ["myarray"] }, undefined, undefined, []);
}
function validateString() {
  testValidator(AttributeTypes.validateString, 'this is a string', undefined, 'this is a string', []);
  testValidator(AttributeTypes.validateString, { t: 'this is not a string' }, undefined, undefined, [
    {is: "warning", "msg": "attribute must be a string, got object" }
  ]);
  testValidator(AttributeTypes.validateString, '', undefined, undefined, [
    {is: "warning", "msg": "attribute can't be an empty string" }
  ]);
}
function validateAnyString() {
  testValidator(AttributeTypes.validateAnyString, 'this is a string', undefined, 'this is a string', []);
  testValidator(AttributeTypes.validateAnyString, { t: 'this is not a string' }, undefined, undefined, [
    {is: "warning", "msg": "attribute must be a string, got object" }
  ]);
  testValidator(AttributeTypes.validateAnyString, '', undefined, '', []);
}
function validateObject() {
  testValidator(AttributeTypes.validateObject, { o: 1 }, undefined, { o: 1 }, []);
  testValidator(AttributeTypes.validateObject, 'this is a string', undefined, undefined, [
    {is: "warning", "msg": "attribute must be an object, got string" }
  ]);
  testValidator(AttributeTypes.validateObject, {}, undefined, {}, []);
}
function validateArray() {
  testValidator(AttributeTypes.validateArray, [1, 2, 3], undefined, [1, 2, 3], []);
  testValidator(AttributeTypes.validateArray, 'this is a string', undefined, [], [
    {is: "warning", "msg": "attribute must be an array" }
  ]);
  testValidator(AttributeTypes.validateArray, [], undefined, [], []);
}
function validateBoolean() {
  testValidator(AttributeTypes.validateBoolean, true, undefined, true, []);
  testValidator(AttributeTypes.validateBoolean, false, undefined, false, []);
  testValidator(AttributeTypes.validateBoolean, 'this is a string', undefined, undefined, [
    {is: "warning", "msg": "attribute must be a boolean, got string" }
  ]);
}
function validateStringList() {
  testValidator(AttributeTypes.validateStringList, ['this is a string'], undefined, ['this is a string'], []);
  testValidator(AttributeTypes.validateStringList, ['0', '1'], undefined, ['0', '1'], []);
  testValidator(AttributeTypes.validateStringList, [{ t: 'this is not a string' }], undefined, [], [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[0]" }
  ]);
  testValidator(AttributeTypes.validateStringList, ['0', { t: 'this is not a string' }], undefined, ['0'], [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[1]" }
  ]);
  testValidator(AttributeTypes.validateStringList, ['0', '', 1], undefined, ['0'], [
    {is: "warning", "msg": "attribute can't be an empty string", "path": "[1]" },
    {is: "warning", "msg": "attribute must be a string, got number", "path": "[2]" }
  ]);
  testValidator(AttributeTypes.validateStringList, '', undefined, [], [
    {is: "warning", "msg": "attribute must be an array" }
  ]);
}
function validateStringSet() {
  testValidator(AttributeTypes.validateStringSet, ['this is a string'], undefined, new Set(['this is a string']), []);
  testValidator(AttributeTypes.validateStringSet, ['0', '1'], undefined, new Set(['0', '1']), []);
  testValidator(AttributeTypes.validateStringSet, [{ t: 'this is not a string' }], undefined, new Set<string>([]), [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[0]" }
  ]);
  testValidator(AttributeTypes.validateStringSet, ['0', { t: 'this is not a string' }], undefined, new Set(['0']), [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[1]" }
  ]);
  testValidator(AttributeTypes.validateStringSet, ['0', '', 1], undefined, new Set(['0']), [
    {is: "warning", "msg": "attribute can't be an empty string", "path": "[1]" },
    {is: "warning", "msg": "attribute must be a string, got number", "path": "[2]" }
  ]);
  testValidator(AttributeTypes.validateStringSet, '', undefined, new Set([]), [
    {is: "warning", "msg": "attribute must be an array" }
  ]);
}

function chain() {
  testValidator(AttributeTypes.chain(AttributeTypes.validateArray, AttributeTypes.validateStringList), ['this is a string'], undefined, ['this is a string'], []);
  testValidator(AttributeTypes.chain(AttributeTypes.validateArray, AttributeTypes.validateString), ['this is a string'], undefined, undefined, [
    { is: "warning", "msg": "attribute must be a string, got object" }
  ]);
}

function oneOf() {
  testValidator(AttributeTypes.oneOf(AttributeTypes.validateString, AttributeTypes.validateStringList), ['this is a string'], undefined, ['this is a string'], []);
  testValidator(AttributeTypes.oneOf(AttributeTypes.validateString, AttributeTypes.validateStringList), 'this is a string', undefined, 'this is a string', []);
  testValidator(AttributeTypes.oneOf(AttributeTypes.validateString, AttributeTypes.validateStringList), { t: 'this is not a string' }, undefined, undefined, [{
    is: "warning", "msg": "attribute must be one of",
    "notes": [
      { is: "warning", "msg": "attribute must be a string, got object" },
      { is: "warning", "msg": "attribute must be an array" },
    ]
  }]);
}
function defaultsTo() {
  testValidator(AttributeTypes.defaultsTo(AttributeTypes.validateString, 'default string value'), 'this is a string', undefined, 'this is a string', []);
  testValidator(AttributeTypes.defaultsTo(AttributeTypes.validateString, 'default string value'), undefined, undefined, 'default string value', []);
  testValidator(AttributeTypes.defaultsTo(AttributeTypes.validateString, 'default string value'), { t: 'this is not a string' }, undefined, 'default string value', [
    { is: "warning", "msg": "attribute must be a string, got object" }
  ]);
}
function listValidator() {
  let validator = AttributeTypes.listValidator(AttributeTypes.validateString);
  testValidator(validator, ['this is a string'], undefined, ['this is a string'], []);
  testValidator(validator, ['0', '1'], undefined, ['0', '1'], []);
  testValidator(validator, [{ t: 'this is not a string' }], undefined, [], [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[0]" }
  ]);
  testValidator(validator, ['0', { t: 'this is not a string' }], undefined, ['0'], [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[1]" }
  ]);
  testValidator(validator, ['0', '', 1], undefined, ['0'], [
    {is: "warning", "msg": "attribute can't be an empty string", "path": "[1]" },
    {is: "warning", "msg": "attribute must be a string, got number", "path": "[2]" }
  ]);
  testValidator(validator, '', undefined, [], [
    {is: "warning", "msg": "attribute must be an array" }
  ]);
}
function setValidator() {
  let validator = AttributeTypes.setValidator(AttributeTypes.validateString);
  testValidator(validator, ['this is a string'], undefined, new Set(['this is a string']), []);
  testValidator(validator, ['0', '1'], undefined, new Set(['0', '1']), []);
  testValidator(validator, [{ t: 'this is not a string' }], undefined, new Set([]), [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[0]" }
  ]);
  testValidator(validator, ['0', { t: 'this is not a string' }], undefined, new Set(['0']), [
    {is: "warning", "msg": "attribute must be a string, got object", "path": "[1]" }
  ]);
  testValidator(validator, ['0', '', 1], undefined, new Set(['0']), [
    {is: "warning", "msg": "attribute can't be an empty string", "path": "[1]" },
    {is: "warning", "msg": "attribute must be a string, got number", "path": "[2]" }
  ]);
  testValidator(validator, '', undefined, new Set([]), [
    {is: "warning", "msg": "attribute must be an array" }
  ]);
}
function objectValidator() {
  let validator = AttributeTypes.objectValidator({
    's': AttributeTypes.defaultsTo(AttributeTypes.validateString, 'a string') ,
    'b': AttributeTypes.defaultsTo(AttributeTypes.validateBoolean, false) ,
  });
  let validator2 = AttributeTypes.objectValidator({
    's': AttributeTypes.defaultsTo(AttributeTypes.validateString, 'a') ,
    'b': AttributeTypes.defaultsTo(AttributeTypes.validateString, 'b') ,
  }, AttributeTypes.validateString);
  testValidator(validator, { s: 'test', b: true }, undefined, { s: 'test', b: true }, []);
  testValidator(validator, { s: 'test' }, undefined, { s: 'test', b: false }, []);
  testValidator(validator, { s: 0 }, undefined, { s: 'a string', b: false }, [
    { is: "warning", "msg": "attribute must be a string, got number", "path": ".s" }
  ]);
  testValidator(validator, { }, undefined, { s: 'a string', b: false }, []);
  testValidator(validator, { not_defined: 0 }, undefined, { s: 'a string', b: false }, [
    { is: "warning", "msg": "attribute is unused", "path": ".not_defined" }
  ]);
  testValidator(validator2, { not_defined: "test" }, undefined, { s: 'a', b: 'b', not_defined: "test" }, []);
  testValidator(validator2, { not_defined: 0 }, undefined, { s: 'a', b: 'b' }, [
    { is: "warning", "msg": "attribute must be a string, got number", "path": ".not_defined" }
  ]);
}

export const tests = { name: 'attributes', tests: [
  validateAny,
  validateAnyToUndefined,
  validateString,
  validateAnyString,
  validateObject,
  validateArray,
  validateBoolean,
  validateStringList,
  validateStringSet,
  chain,
  oneOf,
  defaultsTo,
  listValidator,
  objectValidator,
  setValidator
]};


text:
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
   public class MethodPartFactoryTest : TestCase {
      private static interface Bean {
         public abstract int Integer {
            get;
         }
         //public int GetInteger();
         public abstract List<String> List {
            get;
         }
         //public List<String> GetList();
         public Map<String, String> getMap();
         public abstract Map<String, String> Map {
            set;
         }
         //public void SetMap(Map<String, String> map);
         public abstract String[] Array {
            set;
         }
         //public void SetArray(String[] array);
      public void TestMethodPart() {
         assertTrue(Element.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("getInteger")).getAnnotation().getClass()));
         assertTrue(Element.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("setInteger", int.class)).getAnnotation().getClass()));
         assertTrue(ElementMap.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("getMap")).getAnnotation().getClass()));
         assertTrue(ElementMap.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("setMap", Map.class)).getAnnotation().getClass()));
         assertTrue(ElementList.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("getList")).getAnnotation().getClass()));
         assertTrue(ElementList.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("setList", List.class)).getAnnotation().getClass()));
         assertTrue(ElementArray.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("getArray")).getAnnotation().getClass()));
         assertTrue(ElementArray.class.isAssignableFrom(new MethodPartFactory().getInstance(Bean.class.getMethod("setArray", String[].class)).getAnnotation().getClass()));
      }
   }
}


text:
const electron = require('electron')

// Module to control application life.
const app = electron.app

// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const session = electron.session
const dialog = electron.dialog

const path = require('path')
const parseArguments = require('minimist')

const argDefaults = {
  'title': null
}

const argv = parseArguments(process.argv.slice(1), {default: argDefaults})

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

const siteUrl = argv._.slice(-1)[0]
const siteSessionId = siteUrl.replace(/\//g, '_')
const windowTitle = argv.title

let siteSession

const appUserDataPath = app.getPath('userData')
app.setPath('userData', path.join(appUserDataPath, 'sessions', siteSessionId))

// TODO check for required arguments

var handleRedirect = function (e, url) {
  if (url !== mainWindow.webContents.getURL()) {
    e.preventDefault()
    electron.shell.openExternal(url)
  }
}

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    session: siteSession,
    show: false,
    webPreferences: {
      nodeIntegration: false
    }
  })
  // Hide the menu since we do not need it!
  mainWindow.setMenu(null)

  // Enable the DevTools if the debug flag is set
  if (argv.debug) {
    mainWindow.webContents.openDevTools()
  }

  // and load the index.html of the app.
  mainWindow.loadURL(siteUrl)

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })

  mainWindow.webContents.on('did-fail-load', function (event, errorCode, errorDescription) {
    dialog.showErrorBox('Error loading website', `
    URL: ${siteUrl}
    Error: ${errorCode} (${errorDescription})

    Make sure you didn't misstype the URL and try again.`)
    mainWindow.close()
  })

  mainWindow.webContents.on('did-finish-load', function (event) {
    mainWindow.setTitle(windowTitle)
  })

  // Display window when page is fully loaded
  mainWindow.once('ready-to-show', function () {
    mainWindow.show()
  })

  mainWindow.webContents.on('will-navigate', handleRedirect)
  mainWindow.webContents.on('new-window', handleRedirect)
}

function init () {
  siteSession = session.fromPartition('persist:' + siteSessionId)
  createWindow()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', init)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})


text:
<?php

include("conection.php");
if(isset($_POST["button"]))
{
mysql_query("UPDATE attendance SET studid='$_POST[stid]',subid='$_POST[subid]',totalclasses='$_POST[totcla]',attendedclasses='$_POST[attcla]',percentage='$_POST[percent]',comment='$_POST[comment]'  WHERE attid ='$_POST[attid]'");
echo "Record updated successfully...";
}

$result = mysql_query("SELECT * FROM attendance where examid='$_GET[coid]'");
 while($row = mysql_fetch_array($result))
  {
$attid =  $row[attid];
$studid =  $row[studid];
$subid =  $row[subid];
$totalclasses = $row[totalclasses];
$attendedclasses = $row[attendedclasses];
$percentage =  $row[percentage];
$comment =  $row[comment];
  }
?>

<form method="post" action="">

Attendance ID :

  <input type="text" name="attid" id="examid" value="<?php echo $attid; ?>" />

Student ID :
  <input type="text" name="stid" id="stid" value="<?php echo $studid; ?>"  />

Subject ID:
  <input type="text" name="subid" id="subid" value="<?php echo $subid; ?>"  />

Total Classes :
  <input type="text" name="totcla" id="totcla" value="<?php echo $totalclasses; ?>"  />

Attended Classes:

  <input type="text" name="attcla" id="maxm2" value="<?php echo $attendedclasses; ?>"  />

Percentage:
  <input type="text" name="percent" id="maxm" value="<?php echo $percentage; ?>"  />

Comment:

  <textarea name="comment" id="comment" cols="45" rows="5" value="<?php echo $comment; ?>" ></textarea>

  <input type="submit" name="button" id="button" value="Submit" />

</form>


text:
Killer = setmetatable({}, { __index = PhysicalEntity })

function Killer.new(cell, opts, deck, idx, verts, callback)
  local self = setmetatable(
      PhysicalEntity.new(cell), { __index = Killer })

  local fixture = createAlignedRectFromVerts(
      self:createBody_(MOAIBox2DBody.STATIC), verts,
      opts.collision_width, opts.collision_height)

  fixture:setCollisionHandler(
      function(phase, a, b, arbiter)
        arbiter:setContactEnabled(false)
        local do_callback = MOAICoroutine.new()
        do_callback:run(callback)
      end, MOAIBox2DArbiter.PRE_SOLVE, settings.collision_masks.player)

  fixture:setFilter(settings.collision_masks.lethal,
                    settings.collision_masks.player)

  self.prop_ = createPropFromVerts(deck, idx, verts)
  self.prop_:setPriority(settings.priorities.doodads)
  cell.fgLayer:insertProp(self.prop_)

  self.layer_ = cell.fgLayer

  return self
end

function Killer:getNode()
  return self.body
end

function Killer:destroy()
  self.layer_:removeProp(self.prop_)
  self.layer_ = nil
  self.prop_ = nil

  PhysicalEntity.destroy(self)
end


text:
require "features/helper"

RSpec.describe "Running commands", type: :aruba do
  before do
    create_config(accounts: [])
    run_command("imap-backup local accounts")
    last_command_started.stop
  end

  context "when no accounts are configured" do
    it "succeeds" do
      expect(last_command_started).to have_exit_status(0)
    end
  end
end


text:
package com.amazonaws.services.elasticmapreduce.model.transform;

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * EbsConfiguration JSON Unmarshaller
 */
public class EbsConfigurationJsonUnmarshaller implements
        Unmarshaller<EbsConfiguration, JsonUnmarshallerContext> {

    public EbsConfiguration unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        EbsConfiguration ebsConfiguration = new EbsConfiguration();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context
                        .testExpression("EbsBlockDeviceConfigs", targetDepth)) {
                    context.nextToken();
                    ebsConfiguration
                            .setEbsBlockDeviceConfigs(new ListUnmarshaller<EbsBlockDeviceConfig>(
                                    EbsBlockDeviceConfigJsonUnmarshaller
                                            .getInstance()).unmarshall(context));
                }
                if (context.testExpression("EbsOptimized", targetDepth)) {
                    context.nextToken();
                    ebsConfiguration.setEbsOptimized(context.getUnmarshaller(
                            Boolean.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return ebsConfiguration;
    }

    private static EbsConfigurationJsonUnmarshaller instance;

    public static EbsConfigurationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new EbsConfigurationJsonUnmarshaller();
        return instance;
    }
}


text:
id: 5a24c314108439a4d4036157
title: Write a Counter with Redux
challengeType: 6
isRequired: false
videoUrl: ''
localeTitle: 用Redux写一个计数器
---

## Description

现在您已经了解了Redux的所有核心原则!您已经了解了如何创建操作和操作创建器,创建Redux存储,针对存储分派操作以及使用纯reducer设计状态更新。您甚至已经了解了如何使用reducer组合管理复杂状态并处理异步操作。这些示例过于简单,但这些概念是Redux的核心原则。如果您理解它们,那么您已准备好开始构建自己的Redux应用程序。接下来的挑战涵盖了有关state不变性的一些细节,但首先,这里是对迄今为止所学到的所有内容的回顾。

## Instructions

在本课程中,您将从头开始使用Redux实现一个简单的计数器。代码编辑器中提供了基础知识,但您必须填写详细信息!使用提供的名称并定义incAction和decAction操作创建者, decAction counterReducer() , INCREMENT和DECREMENT操作类型,最后定义Redux store 。一旦完成,您应该能够发送INCREMENT或DECREMENT操作来增加或减少store保存的状态。祝你好运第一个Redux应用程序!

## Tests

```yml
tests:
  - text: 动作创建者<code>incAction</code>应返回<code>type</code>等于<code>INCREMENT</code>值的动作对象
    testString: assert(incAction().type ===INCREMENT);
  - text: 动作创建者<code>decAction</code>应与返回动作对象<code>type</code>等于的值<code>DECREMENT</code>
    testString: assert(decAction().type === DECREMENT);
  - text: Redux存储应该以0 <code>state</code>初始化。
    testString: assert(store.getState() === 0);
  - text: 在Redux存储上调度<code>incAction</code>应该将<code>state</code>增加1。
    testString: assert((function() { const initialState = store.getState(); store.dispatch(incAction()); const incState = store.getState(); return initialState + 1 === incState })());
  - text: 在Redux存储上调度<code>decAction</code>应该将<code>state</code>减1。
    testString: assert((function() { const initialState = store.getState(); store.dispatch(decAction()); const decState = store.getState(); return initialState - 1 === decState })());
  - text: <code>counterReducer</code>应该是一个函数
    testString: assert(typeof counterReducer === 'function');

```

## Challenge Seed

```jsx
const INCREMENT = null; // define a constant for increment action types
const DECREMENT = null; // define a constant for decrement action types

const counterReducer = null; // define the counter reducer which will increment or decrement the state based on the action it receives

const incAction = null; // define an action creator for incrementing

const decAction = null; // define an action creator for decrementing

const store = null; // define the Redux store here, passing in your reducers

```

## Solution

```js
// solution required
```


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol");
const workspace_1 = tslib_1.__importDefault(require("../workspace"));
const logger = require('../util/logger')('provider-manager');
class Manager {
    constructor() {
        this.providers = new Set();
    }
    hasProvider(document) {
        return this.getProvider(document) != null;
    }
    getProvider(document) {
        let currScore = 0;
        let providerItem;
        for (let item of this.providers) {
            let { selector, priority } = item;
            let score = workspace_1.default.match(selector, document);
            if (score == 0)
                continue;
            if (typeof priority == 'number') {
                score = priority;
            }
            if (score < currScore)
                continue;
            currScore = score;
            providerItem = item;
        }
        return providerItem;
    }
    poviderById(id) {
        let item = Array.from(this.providers).find(o => o.id == id);
        return item ? item.provider : null;
    }
    getProviders(document) {
        let items = Array.from(this.providers);
        items = items.filter(item => {
            return workspace_1.default.match(item.selector, document) > 0;
        });
        return items.sort((a, b) => {
            return workspace_1.default.match(b.selector, document) - workspace_1.default.match(a.selector, document);
        });
    }
    mergeDefinitions(arr) {
        let res = [];
        for (let def of arr) {
            if (!def)
                continue;
            if (vscode_languageserver_protocol_1.Location.is(def)) {
                let { uri, range } = def;
                let idx = res.findIndex(l => l.uri == uri && l.range.start.line == range.start.line);
                if (idx == -1) {
                    res.push(def);
                }
            }
            else if (Array.isArray(def)) {
                for (let d of def) {
                    let { uri, range } = d;
                    let idx = res.findIndex(l => l.uri == uri && l.range.start.line == range.start.line);
                    if (idx == -1) {
                        res.push(d);
                    }
                }
            }
            else {
                workspace_1.default.showMessage(`Bad definition ${JSON.stringify(def)}`, 'error');
            }
        }
        return res;
    }
}
exports.default = Manager;
//# sourceMappingURL=manager.js.map


text:
package com.gemstone.gemfire.internal.cache.tier.sockets;

import com.gemstone.gemfire.internal.cache.BridgeObserverAdapter;
import com.gemstone.gemfire.internal.cache.BridgeObserverHolder;
import com.gemstone.gemfire.cache.client.internal.PoolImpl;

import dunit.DistributedTestCase;
import dunit.Host;

/**
 * Tests Redundancy Level Functionality
 *
 * @author Suyog Bhokare
 *
 */
public class RedundancyLevelPart3DUnitTest extends RedundancyLevelTestBase
{
    /** constructor */
  public RedundancyLevelPart3DUnitTest(String name) {
    super(name);
  }

  public static void caseSetUp() throws Exception {
    DistributedTestCase.disconnectAllFromDS();
  }

  /**
   * This tests failing of a primary server in a situation where teh rest of the server are all redundant.
   * After every failure, the order, the dispatcher, the interest registration and the makePrimary calls
   * are verified. The failure detection in these tests could be either through CCU or cache operation,
   * whichever occurs first
   *
   */
  public void testRegisterInterestAndMakePrimaryWithFullRedundancy()
  {
    try {
      CacheServerTestUtil.disableShufflingOfEndpoints();
      createClientCache(getServerHostName(Host.getHost(0)), PORT1, PORT2, PORT3, PORT4, 3);
      createEntriesK1andK2();
      registerK1AndK2();
      assertEquals(3, pool.getRedundantNames().size());
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server1.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      server2.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      server0.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      server1.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      server2.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      server3.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      PoolImpl.BEFORE_REGISTER_CALLBACK_FLAG = true;
      PoolImpl.BEFORE_PRIMARY_IDENTIFICATION_FROM_BACKUP_CALLBACK_FLAG = true;
      PoolImpl.BEFORE_RECOVER_INTEREST_CALLBACK_FLAG = true;
      registerInterestCalled = false;
      makePrimaryCalled = false;
      BridgeObserverHolder.setInstance(new BridgeObserverAdapter() {
        public void beforeInterestRegistration()
        {
          registerInterestCalled = true;
        }
        public void beforeInterestRecovery()
        {
          registerInterestCalled = true;

        }
        public void beforePrimaryIdentificationFromBackup()
        {
          makePrimaryCalled = true;
        }
      });
      server0.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server1.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server2.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      verifyLiveAndRedundantServers(3, 2);
      if(registerInterestCalled){
        fail("register interest should not have been called since we failed to a redundant server !");
      }
      if(!makePrimaryCalled){
        fail("make primary should have been called since primary did fail and a new primary was to be chosen ");
      }
      assertEquals(2, pool.getRedundantNames().size());
      makePrimaryCalled = false;
      server1.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server2.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsNotAlive");
      verifyLiveAndRedundantServers(2, 1);
      if(registerInterestCalled){
        fail("register interest should not have been called since we failed to a redundant server !");
      }
      if(!makePrimaryCalled){
        fail("make primary should have been called since primary did fail and a new primary was to be chosen ");
      }
      assertEquals(1, pool.getRedundantNames().size());
      makePrimaryCalled = false;
      server2.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      verifyLiveAndRedundantServers(1, 0);
      if(registerInterestCalled){
        fail("register interest should not have been called since we failed to a redundant server !");
      }
      if(!makePrimaryCalled){
        fail("make primary should have been called since primary did fail and a new primary was to be chosen ");
      }
      assertEquals(0, pool.getRedundantNames().size());
      server3.invoke(RedundancyLevelTestBase.class, "stopServer");
      server0.invoke(RedundancyLevelTestBase.class, "startServer");
      doPuts();
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server0.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(1, 0);
      if(!registerInterestCalled){
        fail("register interest should have been called since a recovered server came up!");
      }
      assertEquals(0, pool.getRedundantNames().size());
      PoolImpl.BEFORE_REGISTER_CALLBACK_FLAG = false;
      PoolImpl.BEFORE_PRIMARY_IDENTIFICATION_FROM_BACKUP_CALLBACK_FLAG = false;
      PoolImpl.BEFORE_RECOVER_INTEREST_CALLBACK_FLAG = false;
    }
     catch (Exception ex) {
        ex.printStackTrace();
        fail(
            "test failed due to exception in test testRedundancySpecifiedMoreThanEPs ",
            ex);
     }
   }

  /**
   * This tests failing of a primary server in a situation where the rest of the server are all non redundant.
   * After every failure, the order, the dispatcher, the interest registration and the makePrimary calls
   * are verified. The failure detection in these tests could be either through CCU or cache operation,
   * whichever occurs first
   *
   */

  public void testRegisterInterestAndMakePrimaryWithZeroRedundancy()
  {
    try {
      CacheServerTestUtil.disableShufflingOfEndpoints();
      createClientCache(getServerHostName(Host.getHost(0)), PORT1, PORT2, PORT3, PORT4, 0);
      createEntriesK1andK2();
      registerK1AndK2();
      assertEquals(0, pool.getRedundantNames().size());
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server0.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      server0.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server1.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server1.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(3, 0);
      assertEquals(0, pool.getRedundantNames().size());
      server1.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server2.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server2.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(2, 0);
      assertEquals(0, pool.getRedundantNames().size());
      server2.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server3.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(1, 0);
      assertEquals(0, pool.getRedundantNames().size());
      server3.invoke(RedundancyLevelTestBase.class, "stopServer");
      server0.invoke(RedundancyLevelTestBase.class, "startServer");
      doPuts();
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server0.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(1, 0);
      assertEquals(0, pool.getRedundantNames().size());
    }
     catch (Exception ex) {
        ex.printStackTrace();
        fail(
            "test failed due to exception in test testRedundancySpecifiedMoreThanEPs ",
            ex);
     }
   }

  /**
   * This tests failing of a primary server in a situation where only one of the rest of teh servers is redundant.
   * After every failure, the order, the dispatcher, the interest registration and the makePrimary calls
   * are verified. The failure detection in these tests could be either through CCU or cache operation,
   * whichever occurs first
   *
   */
  public void testRegisterInterestAndMakePrimaryWithRedundancyOne()
  {
    try {
//      long maxWaitTime = 60000;
      CacheServerTestUtil.disableShufflingOfEndpoints();
      createClientCache(getServerHostName(Host.getHost(0)), PORT1, PORT2, PORT3, PORT4, 1);
      createEntriesK1andK2();
      registerK1AndK2();
      assertEquals(1, pool.getRedundantNames().size());
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server0.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server1.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server2.invoke(RedundancyLevelTestBase.class, "verifyCCP");
      server2.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(3, 1);
      assertEquals(1, pool.getRedundantNames().size());
      server1.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server2.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server2.invoke(RedundancyLevelTestBase.class, "stopServer");
      doPuts();
      server3.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server3.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(1, 0);
      assertEquals(0, pool.getRedundantNames().size());
      server3.invoke(RedundancyLevelTestBase.class, "stopServer");
      server0.invoke(RedundancyLevelTestBase.class, "startServer");
      doPuts();
      server0.invoke(RedundancyLevelTestBase.class, "verifyDispatcherIsAlive");
      server0.invoke(RedundancyLevelTestBase.class, "verifyInterestRegistration");
      verifyLiveAndRedundantServers(1, 0);
      assertEquals(0, pool.getRedundantNames().size());
     }
    catch (Exception ex) {
      ex.printStackTrace();
      fail(
          "test failed due to exception in test testRedundancySpecifiedMoreThanEPs ",
          ex);
    }
  }

}


text:
package com.intel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AudioRecorderActivity extends Activity {
	private final static String TAG = "AudioRecorderActivity";

	private Button      mStartBt;
	private Button      mStopBt;
	private int         mAudioSource       = MediaRecorder.AudioSource.MIC;
	private static int  mSampleRateInHz    = 16000;
	private static int  mChannelConfig     = AudioFormat.CHANNEL_IN_MONO;
	private static int  mAudioFormat       = AudioFormat.ENCODING_PCM_16BIT;
	private int         mBufferSizeInBytes = 0;
	private AudioRecord mAudioRecord       = null;;
	private boolean     isRecord    = false;
	private String      mPcmName    = "";
	private String      mAudioName  = "";
	private String      mWavName    = "";
	private String      mStrKeyword = "";
	private String      mStrEnv     = "";
	private ProgressBar mProgressBar;
	private AlertDialog mAlertDialog;
	private byte[]      mAudioBuf;

	private ArrayDeque<Integer>  mEmptyBufRing = new ArrayDeque<Integer>( 2 );
	private ArrayDeque<Integer>  mFillBufRing  = new ArrayDeque<Integer>( 2 );

	private AlertDialog.Builder mKeywordBuilder;
	private AlertDialog.Builder mEnvBuilder;

	private Time     time  = new Time( "GMT+8" );

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.main );

		mStartBt = (Button)this.findViewById( R.id.onButton );
		mStopBt  = (Button)this.findViewById( R.id.offButton );

		mProgressBar = (ProgressBar)this.findViewById( R.id.Recording );
		mProgressBar.setVisibility( 4 );

		mStartBt.setOnClickListener( new TestAudioListener() );
		mStopBt.setOnClickListener( new TestAudioListener() );
	}

	private void popDialog()
	{
		final CharSequence[] keyword = { "academy", "computer", "geniusbutton", "hamburger",
		                                 "hello-blugenie", "hello-intel", "hey-vlingo",
		                                 "listen-to-me", "original", "start-listening", "wake-up", "noise" };

		final CharSequence[] environment = { "office", "car", "shuttle", "outside", "pub", "motion" };

		mKeywordBuilder = new AlertDialog.Builder( this );
		mKeywordBuilder.setTitle( "Pick a keyword" );
		mKeywordBuilder.setSingleChoiceItems( keyword, -1, new DialogInterface.OnClickListener()
		{
			public void onClick( DialogInterface dialog, int i )
			{
				mStrKeyword = keyword[i].toString();
				mAlertDialog.cancel();

				mAlertDialog = mEnvBuilder.create();
				mAlertDialog.setCancelable( false );
				mAlertDialog.show();
			}
		} );

		mEnvBuilder = new AlertDialog.Builder( this );
		mEnvBuilder.setTitle( "Pick an environment" );
		mEnvBuilder.setSingleChoiceItems( environment, -1, new DialogInterface.OnClickListener()
		{
			public void onClick( DialogInterface dialog, int i )
			{
				mStrEnv = environment[i].toString();
				mWavName = mAudioName + "-" + mStrKeyword + "-" + mStrEnv + ".wav";
				Toast.makeText( getApplicationContext(), mWavName, Toast.LENGTH_SHORT ).show();
				mAlertDialog.cancel();
				Log.i( TAG, mWavName );
				copyWaveFile( mPcmName, mWavName );
			}
		} );

		Runnable r = new Runnable()
		{
			public void run()
			{
				mAlertDialog = mKeywordBuilder.create();
				mAlertDialog.setCancelable( false );
				mAlertDialog.show();
			}
		};
		this.runOnUiThread( r );
	}

	class TestAudioListener implements OnClickListener
	{
		public void onClick( View v )
		{
			if ( v == mStartBt )
			{
				creatAudioRecord();
				startRecord();
				mProgressBar.setVisibility( 0 );
			}
			if ( v == mStopBt )
			{
				stopRecord();
				mProgressBar.setVisibility( 4 );
			}
		}
	}

	private void creatAudioRecord()
	{
		Log.i( TAG, "=========creatAudioRecord()===========" );
		mBufferSizeInBytes = AudioRecord.getMinBufferSize( mSampleRateInHz, mChannelConfig, mAudioFormat ) * 5;
		mAudioBuf = new byte[mBufferSizeInBytes * 2];
		mAudioRecord = new AudioRecord( mAudioSource, mSampleRateInHz, mChannelConfig, mAudioFormat, mBufferSizeInBytes );
	}

	private void startRecord()
	{
		// Log.i( TAG, "=========creatAudioRecord()===========1" );
		// long time = System.currentTimeMillis();
		// SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
		// String date = formatter.format( new java.util.Date() );
		// Log.i( TAG, "=========creatAudioRecord()===========2" );
		time.setToNow();
		int year   = time.year;
		int month  = time.month + 1;
		int day    = time.monthDay;
		int hour   = time.hour;
		int minute = time.minute;

		Log.d( TAG, "!!!year: " + year + " month: " + month + " day: " + day + " hour: " + hour + " minute: " + minute );

		mAudioName = getString( R.string._sdcard_ ) + String.valueOf( year ) + String.valueOf( month ) + String.valueOf( day )
		             + String.valueOf( hour ) + String.valueOf( minute );
		mPcmName   = mAudioName + ".pcm";
		// Log.i( TAG, "=========creatAudioRecord()===========3" );
		mEmptyBufRing.add( 0 );
		mEmptyBufRing.add( 1 );
		mAudioRecord.startRecording();
		mStartBt.setClickable( false );
		isRecord = true;
		new Thread( new AudioRecordThread() ).start();
		new Thread( new AudioWriteThread() ).start();
	}

	private void stopRecord()
	{
		mStartBt.setClickable( true );
		close();
	}

	private void close()
	{
		if ( mAudioRecord != null )
		{
			System.out.println( "stopRecord" );
			isRecord = false;
			mAudioRecord.stop();
			mAudioRecord.release();
			mEmptyBufRing.clear();
			mFillBufRing.clear();
			mAudioRecord = null;
		}
	}

	class AudioRecordThread implements Runnable
	{
		public void run()
		{
			readDataFromMic();
		}
	}

	class AudioWriteThread implements Runnable
	{
		public void run()
		{
			writeDataToFile();
			Log.i( TAG, mAudioName );
			popDialog();
		}
	}

	private void readDataFromMic()
	{
		int readSize = 0;

		while ( isRecord == true )
		{
			if ( mEmptyBufRing.isEmpty() )
			{
				// Log.d( TAG, "%%%%%%%%%%%%%%%%%%%%%" );
				try
				{
					Thread.sleep( 1 );
				} catch ( InterruptedException e )
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				continue;
			}

			int idx = mEmptyBufRing.remove();
			// Log.d( TAG, "read idx: " + idx );
			readSize = mAudioRecord.read( mAudioBuf, idx * mBufferSizeInBytes, mBufferSizeInBytes );
			if ( mAudioRecord.ERROR_INVALID_OPERATION != readSize )
			{
				// notify file write thread
				mFillBufRing.add( idx );
			}
		}
	}

	private void writeDataToFile()
	{
		FileOutputStream fos = null;

		try
		{
			File file = new File( mPcmName );
			if ( file.exists() )
			{
				file.delete();
			}
			fos = new FileOutputStream( file );
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}

		while ( isRecord == true )
		{
			if ( mFillBufRing.isEmpty() )
			{
				// Log.d( TAG, "aaaaaaaaaaaaa" );
				try {
					Thread.sleep( 1 );
				} catch ( InterruptedException e )
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				continue;
			}

			int idx = mFillBufRing.remove();
			// Log.d( TAG, "write idx: " + idx + ", mBufferSizeInBytes: " + mBufferSizeInBytes );
			try
			{
				fos.write( mAudioBuf, idx * mBufferSizeInBytes, mBufferSizeInBytes );
			} catch ( IOException e )
			{
				e.printStackTrace();
			}
			mEmptyBufRing.add( idx );
		}

		try
		{
			fos.close();
		} catch ( IOException e )
		{
			e.printStackTrace();
		}
	}

	private void copyWaveFile( String inFilename, String outFilename )
	{
		FileInputStream in   = null;
		FileOutputStream out = null;
		long totalAudioLen = 0;
		long totalDataLen = totalAudioLen + 36;
		long longSampleRate = mSampleRateInHz;
		int  channels = 1;
		long byteRate = 16 * mSampleRateInHz * channels / 8;
		byte[] data = new byte[mBufferSizeInBytes];
		try
		{
			in = new FileInputStream( inFilename );
			out = new FileOutputStream( outFilename );
			totalAudioLen = in.getChannel().size();
			totalDataLen = totalAudioLen + 36;
			WriteWaveFileHeader( out, totalAudioLen, totalDataLen,
			                     longSampleRate, channels, byteRate );
			while ( in.read( data ) != -1 )
			{
				out.write( data );
			}
			in.close();
			out.close();
		}
		catch ( FileNotFoundException e )
		{
			e.printStackTrace();
		}
		catch ( IOException e )
		{
			e.printStackTrace();
		}
	}

	private void WriteWaveFileHeader( FileOutputStream out, long totalAudioLen,
	                                  long totalDataLen, long longSampleRate, int channels, long byteRate )
	throws IOException
	{
		byte[] header = new byte[44];
		header[0] = 'R'; // RIFF/WAVE header
		header[1] = 'I';
		header[2] = 'F';
		header[3] = 'F';
		header[4] = (byte)(totalDataLen & 0xff);
		header[5] = (byte)((totalDataLen >> 8) & 0xff);
		header[6] = (byte)((totalDataLen >> 16) & 0xff);
		header[7] = (byte)((totalDataLen >> 24) & 0xff);
		header[8] = 'W';
		header[9] = 'A';
		header[10] = 'V';
		header[11] = 'E';
		header[12] = 'f'; // 'fmt' chunk
		header[13] = 'm';
		header[14] = 't';
		header[15] = ' ';
		header[16] = 16;  // 4 bytes: size of 'fmt' chunk
		header[17] = 0;
		header[18] = 0;
		header[19] = 0;
		header[20] = 1;   // format = 1
		header[21] = 0;
		header[22] = (byte)channels;
		header[23] = 0;
		header[24] = (byte)(longSampleRate & 0xff);
		header[25] = (byte)((longSampleRate >> 8) & 0xff);
		header[26] = (byte)((longSampleRate >> 16) & 0xff);
		header[27] = (byte)((longSampleRate >> 24) & 0xff);
		header[28] = (byte)(byteRate & 0xff);
		header[29] = (byte)((byteRate >> 8) & 0xff);
		header[30] = (byte)((byteRate >> 16) & 0xff);
		header[31] = (byte)((byteRate >> 24) & 0xff);
		header[32] = (byte)(2 * 8 / 8); // block align
		header[33] = 0;
		header[34] = 16; // bits per sample
		header[35] = 0;
		header[36] = 'd';
		header[37] = 'a';
		header[38] = 't';
		header[39] = 'a';
		header[40] = (byte)(totalAudioLen & 0xff);
		header[41] = (byte)((totalAudioLen >> 8) & 0xff);
		header[42] = (byte)((totalAudioLen >> 16) & 0xff);
		header[43] = (byte)((totalAudioLen >> 24) & 0xff);
		out.write( header, 0, 44 );
	}

	@Override
	protected void onDestroy()
	{
		close();
		super.onDestroy();
	}
}


text:
import warnings
from functools import lru_cache

from django.contrib import admin
from django.contrib.auth import logout
from django.contrib.messages import error
from django.contrib.redirects.models import Redirect
from django.core.exceptions import MiddlewareNotUsed
from django.http import (
    HttpResponse,
    HttpResponseGone,
    HttpResponsePermanentRedirect,
    HttpResponseRedirect,
)
from django.middleware.csrf import CsrfViewMiddleware, get_token
from django.template import RequestContext, Template
from django.urls import resolve, reverse
from django.utils.cache import get_max_age
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _

from mezzanine.conf import settings
from mezzanine.core.management.commands.createdb import (
    DEFAULT_PASSWORD,
    DEFAULT_USERNAME,
)
from mezzanine.core.models import SitePermission
from mezzanine.utils.cache import (
    cache_get,
    cache_installed,
    cache_key_prefix,
    cache_set,
    nevercache_token,
)
from mezzanine.utils.conf import middlewares_or_subclasses_installed
from mezzanine.utils.deprecation import MiddlewareMixin, is_authenticated
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.urls import next_url

class AdminLoginInterfaceSelectorMiddleware(MiddlewareMixin):
    """
    Checks for a POST from the admin login view and if authentication is
    successful and the "site" interface is selected, redirect to the site.
    """

    def process_view(self, request, view_func, view_args, view_kwargs):
        login_type = request.POST.get("mezzanine_login_interface")
        if login_type and not is_authenticated(request.user):
            response = view_func(request, *view_args, **view_kwargs)
            if is_authenticated(request.user):
                if login_type == "admin":
                    next = next_url(request) or request.get_full_path()
                    username = request.user.get_username()
                    if username == DEFAULT_USERNAME and request.user.check_password(
                        DEFAULT_PASSWORD
                    ):
                        error(
                            request,
                            mark_safe(
                                _(
                                    "Your account is using the default password, "
                                    "please change it immediately."
                                )
                                % reverse(
                                    "user_change_password", args=(request.user.id,)
                                )
                            ),
                        )
                else:
                    next = "/"
                return HttpResponseRedirect(next)
            else:
                return response
        return None

class SitePermissionMiddleware(MiddlewareMixin):
    """
    Marks the current user with a ``has_site_permission`` which is
    used in place of ``user.is_staff`` to achieve per-site staff
    access.
    """

    def process_view(self, request, view_func, view_args, view_kwargs):
        has_site_permission = False
        if request.user.is_superuser:
            has_site_permission = True
        elif request.user.is_staff:
            lookup = {"user": request.user, "sites": current_site_id()}
            try:
                SitePermission.objects.get(**lookup)
            except SitePermission.DoesNotExist:
                admin_index = reverse("admin:index")
                if request.path.startswith(admin_index):
                    logout(request)
                    view_func = admin.site.login
                    extra_context = {"no_site_permission": True}
                    return view_func(request, extra_context=extra_context)
            else:
                has_site_permission = True
        request.user.has_site_permission = has_site_permission

class TemplateForDeviceMiddleware(MiddlewareMixin):
    """
    DEPRECATED: Device detection has been removed from Mezzanine.
    Inserts device-specific templates to the template list.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        warnings.warn(
            "`TemplateForDeviceMiddleware` is deprecated. "
            "Please remove it from your middleware settings.",
            FutureWarning,
            stacklevel=2,
        )

class TemplateForHostMiddleware(MiddlewareMixin):
    """
    Inserts host-specific templates to the template list.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        warnings.warn(
            "`TemplateForHostMiddleware` is deprecated. Please upgrade "
            "to the template loader. See: https://goo.gl/SzHPR4",
            FutureWarning,
            stacklevel=2,
        )

class UpdateCacheMiddleware(MiddlewareMixin):
    """
    Response phase for Mezzanine's cache middleware. Handles caching
    the response, and then performing the second phase of rendering,
    for content enclosed by the ``nevercache`` tag.
    """

    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not is_authenticated(request.user)
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode("utf-8")
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part.decode("utf-8")).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, "_messages"):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        if csrf_middleware_installed():
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response

@lru_cache(maxsize=None)
def csrf_middleware_installed():
    csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
    return middlewares_or_subclasses_installed([csrf_mw_name])

class FetchFromCacheMiddleware(MiddlewareMixin):
    """
    Request phase for Mezzanine cache middleware. Return a response
    from cache if found, othwerwise mark the request for updating
    the cache in ``UpdateCacheMiddleware``.
    """

    def process_request(self, request):
        if (
            cache_installed()
            and request.method == "GET"
            and not is_authenticated(request.user)
        ):
            cache_key = cache_key_prefix(request) + request.get_full_path()
            response = cache_get(cache_key)
            # We need to force a csrf token here, as new sessions
            # won't receieve one on their first request, with cache
            # middleware running.
            if csrf_middleware_installed():
                csrf_mw = CsrfViewMiddleware()
                csrf_mw.process_view(request, lambda x: None, None, None)
                get_token(request)
            if response is None:
                request._update_cache = True
            else:
                return HttpResponse(response)

class SSLRedirectMiddleware(MiddlewareMixin):
    """
    Handles redirections required for SSL when ``SSL_ENABLED`` is ``True``.

    If ``SSL_FORCE_HOST`` is ``True``, and is not the current host,
    redirect to it.

    Also ensure URLs defined by ``SSL_FORCE_URL_PREFIXES`` are redirect
    to HTTPS, and redirect all other URLs to HTTP if on HTTPS.
    """

    def __init__(self, *args):
        warnings.warn(
            "SSLRedirectMiddleware is deprecated. See "
            "https://docs.djangoproject.com/en/stable/ref/middleware/"
            "#module-django.middleware.security for alternative solutions.",
            DeprecationWarning,
        )
        super().__init__(*args)

    def languages(self):
        if not hasattr(self, "_languages"):
            self._languages = dict(settings.LANGUAGES).keys()
        return self._languages

    def process_request(self, request):
        force_host = settings.SSL_FORCE_HOST
        response = None
        if force_host and request.get_host().split(":")[0] != force_host:
            url = f"http://{force_host}{request.get_full_path()}"
            response = HttpResponsePermanentRedirect(url)
        elif settings.SSL_ENABLED and not settings.DEV_SERVER:
            url = f"{request.get_host()}{request.get_full_path()}"
            path = request.path
            if settings.USE_I18N and path[1:3] in self.languages():
                path = path[3:]
            if path.startswith(settings.SSL_FORCE_URL_PREFIXES):
                if not request.is_secure():
                    response = HttpResponseRedirect("https://%s" % url)
            elif request.is_secure() and settings.SSL_FORCED_PREFIXES_ONLY:
                response = HttpResponseRedirect("http://%s" % url)
        if response and request.method == "POST":
            if resolve(request.get_full_path()).url_name == "fb_do_upload":
                # The handler for the flash file uploader in filebrowser
                # doesn't have access to the http headers Django will use
                # to determine whether the request is secure or not, so
                # in this case we don't attempt a redirect - note that
                # when /admin is restricted to SSL using Mezzanine's SSL
                # setup, the flash uploader will post over SSL, so
                # someone would need to explictly go out of their way to
                # trigger this.
                return
            # Tell the client they need to re-POST.
            response.status_code = 307
        return response

class RedirectFallbackMiddleware(MiddlewareMixin):
    """
    Port of Django's ``RedirectFallbackMiddleware`` that uses
    Mezzanine's approach for determining the current site.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if "django.contrib.redirects" not in settings.INSTALLED_APPS:
            raise MiddlewareNotUsed

    def process_response(self, request, response):
        if response.status_code == 404:
            lookup = {
                "site_id": current_site_id(),
                "old_path": request.get_full_path(),
            }
            try:
                redirect = Redirect.objects.get(**lookup)
            except Redirect.DoesNotExist:
                pass
            else:
                if not redirect.new_path:
                    response = HttpResponseGone()
                else:
                    response = HttpResponsePermanentRedirect(redirect.new_path)
        return response


text:
package com.windcatcher.dmhelper.fragments;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.windcatcher.dmhelper.GlobalConfig;
import com.windcatcher.dmhelper.R;
import com.windcatcher.dmhelper.SQLite.GameSQLDataSource;
import com.windcatcher.dmhelper.SQLite.tables.CreaturesTable;
import com.windcatcher.dmhelper.activities.CameraActivity;
import com.windcatcher.dmhelper.camera.CreatureCameraHost;
import com.windcatcher.dmhelper.dialogs.QuickDialogs;
import com.windcatcher.dmhelper.dialogs.QuickDialogs.FieldNames;
import com.windcatcher.dmhelper.dialogs.QuickDialogs.INoPictureCallback;
import com.windcatcher.dmhelper.dialogs.QuickDialogs.IPictureChoiceCallback;
import com.windcatcher.dmhelper.dialogs.QuickDialogs.IPictureOverwriteCallback;

public class CreateCreatureFragment extends Fragment implements IPictureChoiceCallback, IPictureOverwriteCallback{

	private CreateCreatureFragment(){}

	// ===========================================================
	// TODO Fields
	// ===========================================================

	private EditText mName, mHP, mInit;
	private String mImagePath;

	private CursorListFragment mFragment = null;

	private static Uri outputImageURI;

	private static CreateCreatureFragment activeInstance;
	private boolean mActivated = false;

	// ===========================================================
	// TODO Constants
	// ===========================================================

	public static final int GET_PICTURE_CODE = 1928;
	public static final String EXISTING_ROW_ID = "existing";

	// ===========================================================
	// TODO Inherited Methods
	// ===========================================================

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		activeInstance = null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// inflate the view
		View v = inflater.inflate(R.layout.fragment_create_creature, null);

		// grab the edit text references
		mName = (EditText)v.findViewById(R.id.create_player_name);
		mHP = (EditText)v.findViewById(R.id.create_creature_hp);
		mInit = (EditText)v.findViewById(R.id.create_creature_init);

		// set the set image button
		Button b = (Button)v.findViewById(R.id.create_creature_set_image);
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// choose camera/gallery to get the picture
				QuickDialogs.showPictureChooserDialog(getActivity(), CreateCreatureFragment.this);

			}
		});

		// check for existing row argument which signifies that this is modifying an existing creature
		int existingRow = getArguments().getInt(EXISTING_ROW_ID);
		if(existingRow != -1){
			// row exists, grab the information and populate the fields
			Cursor c = CreaturesTable.query(GameSQLDataSource.getDatabase(getActivity()), existingRow);
			if(c.moveToFirst()){
				mName.setText(c.getString(CreaturesTable.COLUMN_NAME.getNum()));
				mHP.setText(c.getInt(CreaturesTable.COLUMN_HP.getNum()));
				mInit.setText(c.getInt(CreaturesTable.COLUMN_INIT_MOD.getNum()));
				mImagePath = c.getString(CreaturesTable.COLUMN_IMAGE.getNum());
			}
		}

		return v;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.create_creature, menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.create_creature_save:
			saveCreature();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCamera() {
		// check for an empty name
		String creatureName = mName.getText().toString();
		if(creatureName == null || creatureName.isEmpty()){
			QuickDialogs.showFieldNotNullDialog(getActivity(), FieldNames.Name);
			return;
		}

		// check for an existing picture for this creature name
		File image = CreatureCameraHost.getFilePath(creatureName);
		if(image.exists()){
			Intent i = new Intent(new Intent(getActivity(), CameraActivity.class));
			i.putExtra(CameraActivity.ARGS_NAME, mName.getText().toString());
			startActivityForResult(i, GET_PICTURE_CODE);
			activeInstance = this;
			// now return because the callback will bring up the next dialog if necessary
			return;
		}

		Intent i = new Intent(new Intent(getActivity(), CameraActivity.class));
		i.putExtra(CameraActivity.ARGS_NAME, mName.getText().toString());
		startActivityForResult(i, GET_PICTURE_CODE);
		activeInstance = this;
	}

	@Override
	public void onGallery() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent,
				"Select Picture..."), GET_PICTURE_CODE);
		activeInstance = this;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == CreateCreatureFragment.GET_PICTURE_CODE && resultCode == Activity.RESULT_OK){
			String path;
			// check for gallery intent
			Uri selectedImage = data.getData();
			if(selectedImage != null){
				path = getPath(selectedImage);

				CreateCreatureFragment.getActiveInstance().setImagePath(path);
			}
			//nope, was the camera
			path = data.getStringExtra(CameraActivity.DATA_PATH);
			if(path != null){
				CreateCreatureFragment.getActiveInstance().setImagePath(path);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onOverwrite() {
		// choose camera/gallery to get the picture
		QuickDialogs.showPictureChooserDialog(getActivity(), CreateCreatureFragment.this);
	}

	// ===========================================================
	// TODO Methods
	// ===========================================================

	public static CreateCreatureFragment newInstance(long existingRow){
		CreateCreatureFragment frag = new CreateCreatureFragment();

		Bundle args = new Bundle();
		args.putLong(EXISTING_ROW_ID, existingRow);

		frag.setArguments(args);

		return frag;
	}

	private void saveCreature(){

		// sanity checks
		final String name = mName.getText().toString();
		if(name == null || name.isEmpty()){
			QuickDialogs.showFieldNotNullDialog(getActivity(), FieldNames.Name);
			return;
		}
		String hpS = mHP.getText().toString();
		if(hpS == null || name.isEmpty()){
			QuickDialogs.showFieldNotNullDialog(getActivity(), FieldNames.HP);
			return;
		}
		String initS = mInit.getText().toString();
		if(initS == null || name.isEmpty()){
			QuickDialogs.showFieldNotNullDialog(getActivity(), FieldNames.Init);
			return;
		}

		final int hp;
		final int init;
		try{
			hp = Integer.valueOf(hpS);
			init = Integer.valueOf(initS);
		}catch(NumberFormatException e){
			QuickDialogs.showFieldWrongInputDialog(getActivity(), FieldNames.HP);
			return;
		}

		// check for duplicate creature names
		if(CreaturesTable.exists(GameSQLDataSource.getDatabase(getActivity()), name)){
			QuickDialogs.showNameExistsDialog(getActivity());
			return;
		}

		// not needed for sanity, but check if they want to add a picture
		if(mImagePath == null || mImagePath.isEmpty()){
			QuickDialogs.showNoImageDialog(getActivity(), new INoPictureCallback() {

				@Override
				public void onNo() {
					CreaturesTable.addCreature(GameSQLDataSource.getDatabase(getActivity()), name, hp, init, mImagePath);
					getActivity().onBackPressed();
				}

				@Override
				public void onChangedMind() {
					// choose camera/gallery to get the picture
					QuickDialogs.showPictureChooserDialog(getActivity(), CreateCreatureFragment.this);

				}
			});
			return; // return because continuing depends on dialog input
		}

		// whew, input sanitized. Add it to the database
		CreaturesTable.addCreature(GameSQLDataSource.getDatabase(getActivity()), name, hp, init, mImagePath);
		getActivity().onBackPressed();
	}

	public void setImagePath(String path){
		// set the path
		mImagePath = path;
		// null the instance
		activeInstance = null;
		GlobalConfig.log("Path to image: " + path);
	}

	public static CreateCreatureFragment getActiveInstance(){
		return activeInstance;
	}

	public static Uri getOutputImageURI(){
		return outputImageURI;
	}

	public String getPath(Uri uri) {
		String[] projection = {  MediaColumns.DATA};
		Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
		if(cursor != null) {
			//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			String filePath = cursor.getString(columnIndex);
			cursor.close();
			return filePath;
		}
		else
			return uri.getPath();               // FOR OI/ASTRO/Dropbox etc
	}
}


text:
NS_ASSUME_NONNULL_BEGIN

//----------------------------------------------------------------------------//
@interface MKObjCProtocolReferencesSection : MKPointerListSection
@end

NS_ASSUME_NONNULL_END


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace citPOINT.eNeg.Data.Web
{
    public partial class Culture
    {
        #region Primitive Properties

        public virtual int CultureID
        {
            get;
            set;
        }

        public virtual string CultureName
        {
            get;
            set;
        }

        #endregion
        #region Navigation Properties

        public virtual ICollection<User> Users
        {
            get
            {
                if (_users == null)
                {
                    var newCollection = new FixupCollection<User>();
                    newCollection.CollectionChanged += FixupUsers;
                    _users = newCollection;
                }
                return _users;
            }
            set
            {
                if (!ReferenceEquals(_users, value))
                {
                    var previousValue = _users as FixupCollection<User>;
                    if (previousValue != null)
                    {
                        previousValue.CollectionChanged -= FixupUsers;
                    }
                    _users = value;
                    var newValue = value as FixupCollection<User>;
                    if (newValue != null)
                    {
                        newValue.CollectionChanged += FixupUsers;
                    }
                }
            }
        }
        private ICollection<User> _users;

        #endregion
        #region Association Fixup

        private void FixupUsers(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (User item in e.NewItems)
                {
                    item.Culture = this;
                }
            }

            if (e.OldItems != null)
            {
                foreach (User item in e.OldItems)
                {
                    if (ReferenceEquals(item.Culture, this))
                    {
                        item.Culture = null;
                    }
                }
            }
        }

        #endregion
    }
}


text:
package kodkod.engine.fol2sat;

import kodkod.ast.Variable;

/**
 * Represents a  variable binding environment as a
 * map from a {@link kodkod.ast.Variable variable} to a
 * {@link java.lang.Object value}.  An environment has
 * a (possibly empty) parent environment to which unsuccessful lookups
 * are delegated.
 *
 * @specfield variable: lone Variable
 * @specfield value: lone T
 * @specfield parent: Environment
 * @invariant this = parent => no variable
 * @author Emina Torlak
 */
@SuppressWarnings("unchecked")
final class Environment<T> {
	private final Variable variable;
	private final T value;
	private final Environment<T> parent;

	/**
	 * The empty environment; EMPTY is its own parent.
	 */
	@SuppressWarnings("rawtypes")
	static final Environment EMPTY = new Environment();

	/**
	 * Constructs the empty environment.
	 */
	private Environment() {
		this.variable = null;
		this.value = null;
		this.parent = this;
	}

	/**
	 * Constructs a new environment with the specified parent
	 * and mapping.
	 *
	 * @ensures this.parent' = parent && this.variable' = variable && this.value' = value
	 */
	private Environment(Environment<T> parent, Variable variable, T value) {
		this.variable = variable;
		this.value = value;
		this.parent = parent;
	}

	/**
	 * Returns the empty environment.
	 * @return the empty environment.
	 */
	public static <T> Environment<T> empty() {
		return (Environment<T>) EMPTY;
	}

	/**
	 * Returns the parent environment of this, or null if this
	 * does not have a parent.
	 *
	 * @return this.parent
	 */
	public Environment<T> parent() { return parent; }

	/**
	 * Returns a new environment that extends this environment with the specified
	 * mapping.
	 * @requires variable != null
	 * @return e : Environment | e.parent = this && e.variable = variable && e.value = value
	 */
	public Environment<T> extend(Variable variable, T value) {
		assert variable !=  null;
		return new Environment<T>(this, variable, value);
	}

	/**
	 * Returns this.variable.
	 * @return this.variable
	 */
	public Variable variable() {
		return this.variable;
	}

	/**
	 * Returns this.value.
	 * @return this.value
	 */
	public T value() {
		return this.value;
	}

	/**
	 * Returns true if this is the empty environment;
	 * otherwise returns false.
	 * @return this.parent = EMPTY
	 */
	public boolean isEmpty() {
		return this==EMPTY;
	}

	/**
	 * Looks up the given variable in this environment and its
	 * ancestors.  If the variable is not bound in this
	 * environment or any of its ancestors, null is returned.
	 * If the variable is bound in multiple environments,
	 * the first found binding is returned.  Note that null
	 * will also be returned if the variable is bound to null.
	 * @return variable = this.variable => this.value, this.parent.lookup(variable)
	 */
	public T lookup(Variable variable) {
		Environment<T> p = this;
		// ok to use == for testing variable equality:
		// see kodkod.ast.LeafExpression#equals
		while(p!=EMPTY && p.variable!=variable) {
			p = p.parent;
		}
		return p.value;
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return (parent == EMPTY ? "[]" : parent.toString()) + "["+variable+"="+value+"]";
	}

}


text:
<?php

namespace UMRA\Bundle\MemberBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Lexik\Bundle\FormFilterBundle\Filter\FilterBuilderExecuterInterface;
use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands;

class TransMemberFilterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('firstname', 'filter_text', array(
            'label' => 'First Name',
            'condition_pattern' => FilterOperands::STRING_BOTH,
            'attr' => array(
                'class' => 'form-control input-sm'
            )
        ));
        $builder->add('lastname', 'filter_text', array(
            'label' => 'Last Name',
            'condition_pattern' => FilterOperands::STRING_BOTH,
            'attr' => array(
                'class' => 'form-control input-sm'
            )
        ));
        $builder->add('id', 'filter_number', array(
            'label_attr' => array(
                'class' => 'hidden'
            ),
            'read_only' => true,
            'attr' => array(
               'class' => 'hidden'
            )
        ));
    }

    public function getParent()
    {
        return 'filter_sharedable';
    }

    public function getName()
    {
        return 'trans_member_filter';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection'   => false,
            'validation_groups' => array('filtering') // avoid NotBlank() constraint-related message
        ));
    }
}


text:
package proguard.classfile.constant.visitor;

import proguard.classfile.Clazz;
import proguard.classfile.constant.*;
import proguard.classfile.util.SimplifiedVisitor;

/**
 * This ConstantVisitor travels from any method handle constants that it visits
 * to their methodref constants, and applies a given constant visitor.
 *
 * @author Eric Lafortune
 */
public class MethodrefTraveler
extends      SimplifiedVisitor
implements   ConstantVisitor
{
    private ConstantVisitor methodrefConstantVisitor;

    /**
     * Creates a new v that will delegate to the given constant visitor.
     */
    public MethodrefTraveler(ConstantVisitor methodrefConstantVisitor)
    {
        this.methodrefConstantVisitor = methodrefConstantVisitor;
    }

    // Implementations for ConstantVisitor.

    public void visitAnyConstant(Clazz clazz, Constant constant) {}

    public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
    {
        clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex,
                                      methodrefConstantVisitor);
    }
}


text:
const mix = require('laravel-mix');

mix
    .setPublicPath('dist/css')
    .sass('src/sass/vue-context.scss', 'vue-context.css');


text:
CREATE TABLE cookies(
  user_id INT UNIQUE NOT NULL REFERENCES users(id),
  value VARCHAR(40)
)


text:
namespace zacc { namespace examples {

    using namespace math;

    struct __mandelbrot
    {
        using output_container = std::vector<int>;
        using input_container  = std::vector<int>;

        static constexpr auto kernel_name() { return "mandelbrot"; }

        virtual void configure(vec2<int> dim, vec2<float> cmin, vec2<float> cmax, size_t max_iterations) = 0;
        virtual void run(output_container &output) = 0;
    };

    using mandelbrot = system::kernel_interface<__mandelbrot>;
}}


text:
class AddConfirmerIdToCourseUserInvitations < ActiveRecord::Migration[4.2]
  def change
    add_column :course_user_invitations, :confirmer_id, :integer, foreign_key: { references: :users }
  end
end