text:
name: Analyzer suggestion
about: Suggest a Roslyn analyzer related to code style. Semantic/code quality analyzers are developed in roslyn-analyzers repository.
labels: [Area-IDE, Feature Request]
---

**Brief description:**

Describe your suggestion here.

**Languages applicable:**

Is your analyzer C# only? VB Only? Or Both?

**Code example that the analyzer should report:**

A small code snippet that describes a case that the analyzer should report.

**Additional information:**

Any more additional information you would like to add.

**Documentation requirements:**

When this analyzer is implemented, it must be documented by following the steps at [Documentation for IDE CodeStyle analyzers](https://github.com/dotnet/roslyn/blob/master/docs/contributing/Documentation%20for%20IDE%20CodeStyle%20analyzers.md).

redpajama_set_name: RedPajamaGithub


text:
import chalk from 'chalk';
import execa from 'execa';
import semver from 'semver';
import npa from 'npm-package-arg';
import pluralize from 'pluralize';
import { basename, join } from 'path';
import XDGAppPaths from 'xdg-app-paths';
import { mkdirp, readJSON, writeJSON } from 'fs-extra';
import { NowBuildError, PackageJson } from '@vercel/build-utils';
import cliPkg from '../pkg';

import cmd from '../output/cmd';
import { Output } from '../output';
import { getDistTag } from '../get-dist-tag';
import { NoBuilderCacheError } from '../errors-ts';

import * as staticBuilder from './static-builder';
import { BuilderWithPackage } from './types';

type CliPackageJson = typeof cliPkg;

declare const __non_webpack_require__: typeof require;

const registryTypes = new Set(['version', 'tag', 'range']);

const createStaticBuilder = (scope: string): BuilderWithPackage => {
  return {
    runInProcess: true,
    requirePath: `${scope}/static`,
    builder: Object.freeze(staticBuilder),
    package: Object.freeze({ name: `@${scope}/static`, version: '' }),
  };
};

const localBuilders: { [key: string]: BuilderWithPackage } = {
  '@now/static': createStaticBuilder('now'),
  '@vercel/static': createStaticBuilder('vercel'),
};

const distTag = getDistTag(cliPkg.version);

export const cacheDirPromise = prepareCacheDir();
export const builderDirPromise = prepareBuilderDir();

/**
 * Prepare cache directory for installing Vercel runtimes.
 */
export async function prepareCacheDir() {
  const designated = XDGAppPaths('com.vercel.cli').cache();

  if (!designated) {
    throw new NoBuilderCacheError();
  }

  const cacheDir = join(designated, 'dev');
  await mkdirp(cacheDir);
  return cacheDir;
}

export async function prepareBuilderDir() {
  const builderDir = join(await cacheDirPromise, 'builders');
  await mkdirp(builderDir);

  // Create an empty `package.json` file, only if one does not already exist
  try {
    const buildersPkg = join(builderDir, 'package.json');
    await writeJSON(buildersPkg, { private: true }, { flag: 'wx' });
  } catch (err) {
    if (err.code !== 'EEXIST') {
      throw err;
    }
  }

  return builderDir;
}

function getNpmVersion(use = ''): string {
  const parsed = npa(use);
  if (registryTypes.has(parsed.type)) {
    return parsed.fetchSpec || '';
  }
  return '';
}

export function getBuildUtils(packages: string[], org: string): string {
  const version = packages
    .map(getNpmVersion)
    .some(ver => ver.includes('canary'))
    ? 'canary'
    : 'latest';

  return `@${org}/build-utils@${version}`;
}

function parseVersionSafe(rawSpec: string) {
  try {
    return semver.parse(rawSpec);
  } catch (e) {
    return null;
  }
}

export function filterPackage(
  builderSpec: string,
  distTag: string,
  buildersPkg: PackageJson,
  cliPkg: CliPackageJson
) {
  if (builderSpec in localBuilders) return false;
  const parsed = npa(builderSpec);
  const parsedVersion = parseVersionSafe(parsed.rawSpec);

  // Skip install of Runtimes that are part of Vercel CLI's `dependencies`
  if (isBundledBuilder(parsed, cliPkg)) {
    return false;
  }

  // Skip install of already installed Runtime with exact version match
  if (
    parsed.name &&
    parsed.type === 'version' &&
    parsedVersion &&
    buildersPkg.dependencies &&
    parsedVersion.version == buildersPkg.dependencies[parsed.name]
  ) {
    return false;
  }

  // Skip install of already installed Runtime with tag compatible match
  if (
    parsed.name &&
    parsed.type === 'tag' &&
    parsed.fetchSpec === distTag &&
    buildersPkg.dependencies
  ) {
    const parsedInstalled = npa(
      `${parsed.name}@${buildersPkg.dependencies[parsed.name]}`
    );
    if (parsedInstalled.type !== 'version') {
      return true;
    }
    const semverInstalled = semver.parse(parsedInstalled.rawSpec);
    if (!semverInstalled) {
      return true;
    }
    if (semverInstalled.prerelease.length > 0) {
      return semverInstalled.prerelease[0] !== distTag;
    }
    if (distTag === 'latest') {
      return false;
    }
  }

  return true;
}

/**
 * Install a list of builders to the cache directory.
 */
export async function installBuilders(
  packagesSet: Set<string>,
  output: Output,
  builderDir?: string
): Promise<void> {
  const packages = Array.from(packagesSet);
  if (
    packages.length === 0 ||
    (packages.length === 1 &&
      Object.hasOwnProperty.call(localBuilders, packages[0]))
  ) {
    // Static deployment, no builders to install
    return;
  }
  if (!builderDir) {
    builderDir = await builderDirPromise;
  }
  const buildersPkgPath = join(builderDir, 'package.json');
  const buildersPkgBefore = await readJSON(buildersPkgPath);
  const depsBefore = {
    ...buildersPkgBefore.devDependencies,
    ...buildersPkgBefore.dependencies,
  };

  // Filter out any packages that come packaged with Vercel CLI
  const packagesToInstall = packages.filter(p =>
    filterPackage(p, distTag, buildersPkgBefore, cliPkg)
  );

  if (packagesToInstall.length === 0) {
    output.debug('No Runtimes need to be installed');
    return;
  }

  packagesToInstall.push(
    getBuildUtils(packages, 'vercel'),
    getBuildUtils(packages, 'now')
  );

  await npmInstall(builderDir, output, packagesToInstall, false);

  const updatedPackages: string[] = [];
  const buildersPkgAfter = await readJSON(buildersPkgPath);
  const depsAfter = {
    ...buildersPkgAfter.devDependencies,
    ...buildersPkgAfter.dependencies,
  };
  for (const [name, version] of Object.entries(depsAfter)) {
    if (version !== depsBefore[name]) {
      output.debug(`Runtime "${name}" updated to version \`${version}\``);
      updatedPackages.push(name);
    }
  }

  purgeRequireCache(updatedPackages, builderDir, output);
}

async function npmInstall(
  cwd: string,
  output: Output,
  packagesToInstall: string[],
  silent: boolean
) {
  const sortedPackages = packagesToInstall.sort();

  if (!silent) {
    output.spinner(
      `Installing ${pluralize(
        'Runtime',
        sortedPackages.length
      )}: ${sortedPackages.join(', ')}`
    );
  }

  output.debug(`Running npm install in ${cwd}`);

  try {
    const args = [
      'install',
      '--save-exact',
      '--no-package-lock',
      '--no-audit',
      '--no-progress',
    ];
    if (process.stderr.isTTY) {
      // Force colors in the npm child process
      // https://docs.npmjs.com/misc/config#color
      args.push('--color=always');
    }
    args.push(...sortedPackages);
    const result = await execa('npm', args, {
      cwd,
      reject: false,
      stdio: output.isDebugEnabled() ? 'inherit' : 'pipe',
    });
    if (result.failed) {
      output.stopSpinner();
      if (result.stdout) {
        console.log(result.stdout);
      }
      if (result.stderr) {
        console.error(result.stderr);
      }
      throw new NowBuildError({
        message:
          (result as any).code === 'ENOENT'
            ? `Command not found: ${chalk.cyan(
                'npm'
              )}\nPlease ensure that ${cmd('npm')} is properly installed`
            : 'Failed to install `vercel dev` dependencies',
        code: 'NPM_INSTALL_ERROR',
        link: 'https://vercel.link/npm-install-failed-dev',
      });
    }
  } finally {
    output.stopSpinner();
  }
}

export async function updateBuilders(
  packagesSet: Set<string>,
  output: Output,
  builderDir?: string
): Promise<string[]> {
  if (!builderDir) {
    builderDir = await builderDirPromise;
  }

  const updatedPackages: string[] = [];
  const packages = Array.from(packagesSet);
  const buildersPkgPath = join(builderDir, 'package.json');
  const buildersPkgBefore = await readJSON(buildersPkgPath);
  const depsBefore = {
    ...buildersPkgBefore.devDependencies,
    ...buildersPkgBefore.dependencies,
  };

  const packagesToUpdate = packages.filter(p => {
    if (p in localBuilders) return false;

    // If it's a builder that is part of Vercel CLI's
    // `dependencies` then don't update it
    if (isBundledBuilder(npa(p), cliPkg)) {
      return false;
    }

    return true;
  });

  if (packagesToUpdate.length > 0) {
    packagesToUpdate.push(
      getBuildUtils(packages, 'vercel'),
      getBuildUtils(packages, 'now')
    );

    await npmInstall(builderDir, output, packagesToUpdate, true);

    const buildersPkgAfter = await readJSON(buildersPkgPath);
    const depsAfter = {
      ...buildersPkgAfter.devDependencies,
      ...buildersPkgAfter.dependencies,
    };
    for (const [name, version] of Object.entries(depsAfter)) {
      if (version !== depsBefore[name]) {
        output.debug(`Runtime "${name}" updated to version \`${version}\``);
        updatedPackages.push(name);
      }
    }

    purgeRequireCache(updatedPackages, builderDir, output);
  }

  return updatedPackages;
}

/**
 * Get a builder from the cache directory.
 */
export async function getBuilder(
  builderPkg: string,
  output: Output,
  builderDir?: string,
  isRetry = false
): Promise<BuilderWithPackage> {
  let builderWithPkg: BuilderWithPackage = localBuilders[builderPkg];
  if (!builderWithPkg) {
    if (!builderDir) {
      builderDir = await builderDirPromise;
    }
    let requirePath: string;
    const parsed = npa(builderPkg);

    // First check if it's a bundled Runtime in Vercel CLI's `node_modules`
    const bundledBuilder = isBundledBuilder(parsed, cliPkg);
    if (bundledBuilder && parsed.name) {
      requirePath = parsed.name;
    } else {
      const buildersPkg = await readJSON(join(builderDir, 'package.json'));
      const pkgName = getPackageName(parsed, buildersPkg) || builderPkg;
      requirePath = join(builderDir, 'node_modules', pkgName);
    }

    try {
      output.debug(`Requiring runtime: "${requirePath}"`);
      const mod = require(requirePath);
      const pkg = require(join(requirePath, 'package.json'));
      builderWithPkg = {
        requirePath,
        builder: Object.freeze(mod),
        package: Object.freeze(pkg),
      };
    } catch (err) {
      if (err.code === 'MODULE_NOT_FOUND' && !isRetry) {
        output.debug(
          `Attempted to require ${requirePath}, but it is not installed`
        );
        const pkgSet = new Set([builderPkg]);
        await installBuilders(pkgSet, output, builderDir);

        // Run `getBuilder()` again now that the builder has been installed
        return getBuilder(builderPkg, output, builderDir, true);
      }
      throw err;
    }

    // If it's a bundled builder, then cache the require call
    if (bundledBuilder) {
      localBuilders[builderPkg] = builderWithPkg;
    }
  }
  return builderWithPkg;
}

export function isBundledBuilder(
  parsed: npa.Result,
  { dependencies = {} }: PackageJson
): boolean {
  if (!parsed.name) {
    return false;
  }

  const bundledVersion = dependencies[parsed.name];
  if (bundledVersion) {
    if (parsed.type === 'tag') {
      if (parsed.fetchSpec === 'canary') {
        return bundledVersion.includes('canary');
      } else if (parsed.fetchSpec === 'latest') {
        return !bundledVersion.includes('canary');
      }
    } else if (parsed.type === 'version') {
      return parsed.fetchSpec === bundledVersion;
    }
  }

  return false;
}

function getPackageName(
  parsed: npa.Result,
  buildersPkg: PackageJson
): string | null {
  if (registryTypes.has(parsed.type)) {
    return parsed.name;
  }
  const deps: PackageJson.DependencyMap = {
    ...buildersPkg.devDependencies,
    ...buildersPkg.dependencies,
  };
  for (const [name, dep] of Object.entries(deps)) {
    if (dep === parsed.raw || basename(dep) === basename(parsed.raw)) {
      return name;
    }
  }
  return null;
}

function purgeRequireCache(
  packages: string[],
  builderDir: string,
  output: Output
) {
  const _require =
    typeof __non_webpack_require__ === 'function'
      ? __non_webpack_require__
      : require;

  // The `require()` cache for the builder's assets must be purged
  const packagesPaths = packages.map(b => join(builderDir, 'node_modules', b));
  for (const id of Object.keys(_require.cache)) {
    for (const path of packagesPaths) {
      if (id.startsWith(path)) {
        output.debug(`Purging require cache for "${id}"`);
        delete _require.cache[id];
      }
    }
  }
}


text:
import React from 'react';
import proxyquire from 'proxyquire';
import {defaultsDeep} from 'lodash';
import {ERROR, SUCCESS} from 'lib/constants/test-statuses';

describe('<Tabs />', () => {
    const sandbox = sinon.sandbox.create();
    let Tabs, State;

    const mkTabs = (props = {}) => {
        props = defaultsDeep(props, {
            result: {
                id: 'default-result-id',
                status: SUCCESS,
                imageIds: [],
                multipleTabs: true,
                screenshot: true
            }
        });

        return mount(<Tabs {...props} />);
    };

    beforeEach(() => {
        State = sinon.stub().returns(null);

        Tabs = proxyquire('lib/static/components/section/body/tabs', {
            '../../state': {default: State}
        }).default;
    });

    afterEach(() => sandbox.restore());

    it('should not render image tabs if images does not exist and test passed successfully', () => {
        const result = {status: SUCCESS, imageIds: []};

        const component = mkTabs({result});

        assert.lengthOf(component.find('.tab'), 0);
        assert.notCalled(State);
    });

    it('should render error tab if test failed without images', () => {
        const result = {status: ERROR, imageIds: []};

        const component = mkTabs({result});

        assert.lengthOf(component.find('.tab'), 1);
        assert.calledOnceWith(State, {result, imageId: null});
    });

    it('should render image tab for each image id', () => {
        const result = {status: ERROR, imageIds: ['img-1', 'img-2']};

        const component = mkTabs({result});

        assert.lengthOf(component.find('.tab'), 2);
        assert.calledTwice(State);
        assert.calledWith(State.firstCall, {result, imageId: 'img-1'});
        assert.calledWith(State.secondCall, {result, imageId: 'img-2'});
    });

    it('should not render additional error tab if test errored with screenshot on reject', () => {
        const result = {status: ERROR, imageIds: ['img-1'], screenshot: true};

        const component = mkTabs({result});

        assert.lengthOf(component.find('.tab'), 1);
        assert.calledOnceWith(State, {result, imageId: 'img-1'});
    });

    it('should render additional error tab if test errored without screenshot on reject', () => {
        const result = {status: ERROR, imageIds: ['img-1'], screenshot: false};

        const component = mkTabs({result});

        assert.lengthOf(component.find('.tab'), 2);
        assert.calledTwice(State);
        assert.calledWith(State.firstCall, {result, imageId: 'img-1'});
        assert.calledWith(State.secondCall, {result, imageId: null});
    });
});


text:
require_relative './band'

FactoryGirl.define do
  factory :album do
    title 'Album Title'
    band

    factory :pink_floyd_albums do
      association :band, factory: :pink_floyd

      factory :animals_album do
        title 'Animals'
      end

      factory :the_wall_album do
        title 'The Wall'
      end

      factory :meddle_album do
        title 'Meddle'
      end
    end

  end
end


text:
package com.adeptj.maven.plugin.bundle;

import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.core5.http.HttpEntity;

import java.io.File;

import static com.adeptj.maven.plugin.bundle.Constants.PARAM_ACTION;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_ACTION_INSTALL_VALUE;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_BUNDLE_FILE;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_PARALLEL_VERSION;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_REFRESH_PACKAGES;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_START;
import static com.adeptj.maven.plugin.bundle.Constants.PARAM_START_LEVEL;
import static com.adeptj.maven.plugin.bundle.Constants.VALUE_TRUE;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Utility methods.
 *
 * @author Rakesh.Kumar, AdeptJ
 */
final class BundleMojoUtil {

    private BundleMojoUtil() {
    }

    static HttpEntity newBundleInstallMultipartEntity(File bundle, String startLevel, boolean startBundle,
                                                      boolean refreshPackages, boolean parallelVersion) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setCharset(UTF_8)
                .addBinaryBody(PARAM_BUNDLE_FILE, bundle)
                .addTextBody(PARAM_ACTION, PARAM_ACTION_INSTALL_VALUE)
                .addTextBody(PARAM_START_LEVEL, startLevel);
        if (startBundle) {
            multipartEntityBuilder.addTextBody(PARAM_START, VALUE_TRUE);
        }
        if (refreshPackages) {
            multipartEntityBuilder.addTextBody(PARAM_REFRESH_PACKAGES, VALUE_TRUE);
        }
        // Since web console v4.4.0
        if (parallelVersion) {
            multipartEntityBuilder.addTextBody(PARAM_PARALLEL_VERSION, VALUE_TRUE);
        }
        return multipartEntityBuilder.build();
    }
}


text:
namespace gin {
class PerContextData;
}

namespace content {

class WebUIMojoContextState;

// WebUIMojo is responsible for enabling the renderer side of mojo bindings.
// It creates (and destroys) a WebUIMojoContextState at the appropriate times
// and handles the necessary browser messages. WebUIMojo destroys itself when
// the RendererView it is created with is destroyed.
class WebUIMojo
    : public RenderViewObserver,
      public RenderViewObserverTracker<WebUIMojo> {
 public:
  explicit WebUIMojo(RenderView* render_view);

 private:
  class MainFrameObserver : public RenderFrameObserver {
   public:
    explicit MainFrameObserver(WebUIMojo* web_ui_mojo);
    virtual ~MainFrameObserver();

    // RenderFrameObserver overrides:
    virtual void WillReleaseScriptContext(v8::Handle<v8::Context> context,
                                          int world_id) OVERRIDE;

   private:
    WebUIMojo* web_ui_mojo_;

    DISALLOW_COPY_AND_ASSIGN(MainFrameObserver);
  };

  virtual ~WebUIMojo();

  // Invoked from ViewMsg_SetBrowserHandle. Passes handle to current
  // MojoWebUIContextState.
  void OnSetBrowserHandle(MojoHandle handle);

  void CreateContextState();
  void DestroyContextState(v8::Handle<v8::Context> context);

  WebUIMojoContextState* GetContextState();

  // RenderViewObserver overrides:
  virtual void DidClearWindowObject(blink::WebFrame* frame,
                                    int world_id) OVERRIDE;

  MainFrameObserver main_frame_observer_;

  DISALLOW_COPY_AND_ASSIGN(WebUIMojo);
};

}  // namespace content

#endif  // CONTENT_RENDERER_WEB_UI_MOJO_H_


text:
using System;

namespace RandomBuilderPerformanceTest.Fortel
{
    public interface IFinNumberGenerator
    {
        FinNumber GetNextFinNumber(DateTime date);
        FinNumber GetNextJobNumber(Order order);
        FinNumber GetNextReconNumber(Order order);
        FinNumber GetNextInvoiceNumber();
        string GetNextQaNumber(Job job);
        FinNumber GetLatestInvoiceNumber();
    }
}


text:
0.3.0 / 2014-06-30
==================

* Added locals to options to properly render haml

0.2.0 / 2014-01-18
==================

 * Add option to specify global default layout path
 * Added a link to express 2.x ejs example. Closes #39.

0.1.1 / 2013-03-21
==================

  * Fixed issue with layouts in a subdirectory (#35 by rguerreiro)
  * Made tests run on windows (by rguerreiro)

0.1.0 / 2013-03-20
==================

  * Don't error out if we don't use a layout (#32 by tedkulp)
  * options.filename is set for renderers to make includes work in Jade (#31 by jep37)
  * Fixed bug with accessing locals within sub-partials (#27 by ecdeveloper)
  * Default to 127.0.0.1 for windows test support. (#25 by rguerreiro)
  * supporting windows paths with backslash (by rguerreiro)
  * Add partial as local to partials. (#22)
  * exporting lookup() in the module (#20 by rguerreiro)
  * Fixed partials within subdirs (#19 by ecdeveloper)
  * Equality typo. (#12)
  * Reorganized the tests into separate apps
  * Now using supertest and express 3.0

0.0.6 / 2012-09-10
==================

  * Added tests and fixes for layout path resolution. (thanks to Jakub Nešetřil @zzen)
  * Added Travis-CI.

0.0.5 / 2012-06-29
==================

  * Support Node v0.8.0 (or any node really).

0.0.4 / 2012-06-25
==================

  * Improved `partials.register()`. (thanks to Stéphane Alnet)

0.0.3 / 2012-06-25
==================

  * Added support for other template engines. (thanks to Stéphane Alnet)

0.0.2 / 2012-03-06
==================

  * Added some tests.
  * Added app locals as template locals.

0.0.1 / 2012-01-25
==================

  * Initial release


text:
1.0.1 / 2015-11-14
==================
  * Added npmignore

1.0.0 / 2015-04-02
==================
  * Zalgo factored out to the zalgolize module - this is now dependency free

0.2.1 / 2014-07-10
==================
  * Better documentation and code coverage

0.2.0 / 2013-01-12
==================
  * removed gimmicky `rainbow` and `zebra`
  * added zalgo as a separate entry point
  * made zalgo less arcane by using `trials` to do the clustering

0.1.0 / 2013-10-XX
==================
  * sane version that's in `logule` which includes `rainbow` and `zebra`


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151227_123219_add_column_in_table_video_hits_plus_minus extends Migration
{
    public function up()
    {
        $this->addColumn('video', 'hits', $this->integer(11)->defaultValue(0));
        $this->addColumn('video', 'plus', $this->integer(11)->defaultValue(0));
        $this->addColumn('video', 'minus', $this->integer(11)->defaultValue(0));
    }

    public function down()
    {
        $this->dropColumn('video', 'hits');
        $this->dropColumn('video', 'plus');
        $this->dropColumn('video', 'minus');
    }

}


text:
@interface CustomImageView()

@property (nonatomic,strong) UIImageView *leftImageView;
@property (nonatomic,strong) UIImageView *rightImageView;
@property (nonatomic,strong) NSArray *buttonNormalImages;
@property (nonatomic,strong) NSArray *buttonSelectedImages;
@property (nonatomic,strong) UIImage *leftCornerImage;
@property (nonatomic,strong) UIImage *rightCornerImage;
@property (nonatomic,assign) NSUInteger selectedIndex;

@end

@implementation CustomImageView

- (instancetype)initWithFrame:(CGRect)frame
           buttonNormalImages:(NSArray *)imageArrary
         buttonSelectedImages:(NSArray *)selectedImageArray
              leftCornerImage:(UIImage *)left
             rightCornerImage:(UIImage *)right
                     delegate:(id<ButtonIndexChangedDelegate>)indexChangedDelegate
{
  self = [super initWithFrame:frame];
  if (self) {
    _buttonNormalImages = imageArrary;
    _buttonSelectedImages = selectedImageArray;
    _leftCornerImage = left;
    _rightCornerImage = right;
    _selectedIndex = 1;
    _indexChangedDelegate = indexChangedDelegate;
    [self initButtonsWithImageArray:_buttonNormalImages];
  }
  return self;
}

- (void)initButtonsWithImageArray:(NSArray *)imageArray{

    for (int i = 0; i < imageArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(kLeftMargin + kButtonGap * i, 0, kButtonWidth, CGRectGetHeight(self.bounds));
        if (i == 0) {
            _rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kButtonGap - kImageViewOffsetX, 0, kScreenWidth - kButtonGap + kImageViewOffsetX, CGRectGetHeight(self.bounds))];
            UIEdgeInsets rightInset = UIEdgeInsetsMake(0,8,0,0);
            UIImage *iamge = [_rightCornerImage resizableImageWithCapInsets:rightInset resizingMode:UIImageResizingModeStretch];
            _rightImageView.image = iamge;
            [self addSubview:_rightImageView];

            _leftImageView = [[UIImageView alloc]initWithFrame:CGRectZero];
            [self addSubview:_leftImageView];
            [btn setImage:_buttonSelectedImages[0] forState:UIControlStateNormal];
            [self showSeperatorAtIndex:i + 1];
        }
        else{
            [btn setImage:imageArray[i] forState:UIControlStateNormal];
        }
        btn.tag = i + 1;
        if (i == imageArray.count - 1) {
            [btn addTarget:self action:@selector(backspacePressed) forControlEvents:UIControlEventTouchDown];
            btn.frame = CGRectMake(kLeftMargin + kButtonGap * i, 0, 40, CGRectGetHeight(self.bounds));
        }else{
            [btn addTarget:self action:@selector(segButtonChanged:) forControlEvents:UIControlEventTouchDown];
        }

        [self addSubview:btn];
    }
}

- (void)segButtonChanged:(UIButton *)sender{
    if (_selectedIndex == sender.tag) {
        return;
    }

    //取消上一次的选择
    [self setSegButtonAtIndex:_selectedIndex isSelected:NO];

    //显示这一次的选择
    _selectedIndex = sender.tag;
    [self setSegButtonAtIndex:_selectedIndex isSelected:YES];
    [self showSeperatorAtIndex:_selectedIndex];
    if ([_indexChangedDelegate respondsToSelector:@selector(segButtonDidChanged:)]) {
        [_indexChangedDelegate segButtonDidChanged:sender];
    }
}

- (void)backspacePressed{
    if ([_indexChangedDelegate respondsToSelector:@selector(backspaceButtonDidPress)]) {
        [_indexChangedDelegate backspaceButtonDidPress];
    }
}

- (void)setSegButtonAtIndex:(NSUInteger)index isSelected:(BOOL)isSelected{
    if (isSelected) {
        UIButton *btn = (UIButton *)[self viewWithTag:index];
        [btn setImage:_buttonSelectedImages[index - 1] forState:UIControlStateNormal];

        _leftImageView.frame = CGRectMake(0, 0, (index - 1) * kButtonGap - 1, CGRectGetHeight(self.bounds));
        UIEdgeInsets leftInset = UIEdgeInsetsMake(0,0,0,8);
        UIImage *leftIamge = [_leftCornerImage resizableImageWithCapInsets:leftInset resizingMode:UIImageResizingModeStretch];
        _leftImageView.image = leftIamge;

        _rightImageView.frame = CGRectMake(kButtonGap + (index - 1) * kButtonGap - kImageViewOffsetX, 0, kScreenWidth - kButtonGap + (index - 1) * kButtonGap + kImageViewOffsetX, CGRectGetHeight(self.bounds));
        UIEdgeInsets rightInset = UIEdgeInsetsMake(0,8,0,0);
        UIImage *rightIamge = [_rightCornerImage resizableImageWithCapInsets:rightInset resizingMode:UIImageResizingModeStretch];
        _rightImageView.image = rightIamge;
        if (index == 1) {
            _leftImageView.frame = CGRectZero;
        }
    }else{
        UIButton *btn = (UIButton *)[self viewWithTag:index];
        [btn setImage:_buttonNormalImages[index - 1] forState:UIControlStateNormal];
    }
}

- (void)showSeperatorAtIndex:(NSUInteger)index{
    [_rightImageView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_leftImageView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    switch (index) {
        case 1:
            //左0右5
            for (int i = 0; i < 5; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kRightSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_rightImageView addSubview:seperator];
            }
            break;
        case 2:
            //左0右4
            for (int i = 0; i < 4; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kRightSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_rightImageView addSubview:seperator];
            }
            break;
        case 3:
            //左1右3
        {
            for (int i = 0; i < 3; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kRightSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_rightImageView addSubview:seperator];
            }
            UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap - kLeftSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
            seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
            [_leftImageView addSubview:seperator];
        }
            break;
        case 4:
            //左2右2
        {
            for (int i = 0; i < 2; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kRightSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_rightImageView addSubview:seperator];
            }
            for (int i = 0; i < 2; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kLeftSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_leftImageView addSubview:seperator];
            }
        }
            break;
        case 5:
            //左3右1
        {
            for (int i = 0; i < 3; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kLeftSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_leftImageView addSubview:seperator];
            }
            UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap - kRightSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
            seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
            [_rightImageView addSubview:seperator];
        }
            break;
        case 6:
            //左4右0
            for (int i = 0; i < 4; i++) {
                UIImageView *seperator = [[UIImageView alloc] initWithFrame:CGRectMake(kSeperatorGap * (i + 1) - kLeftSeperatorOffsetX, 0, 8, CGRectGetHeight(self.bounds))];
                seperator.image = [UIImage imageNamed:@"icons_bg_separator"];
                [_leftImageView addSubview:seperator];
            }
            break;
        default:
            break;
    }
}

@end


text:
import {CREATE_USER, GET_USER_SUCCESS, LIST_USER_SUCCESS} from '../constants';
import {createUser, getUserSuccess, listUsersSuccess} from '../user';

describe('User actions', () => {
    it('should create an action to get an user', () => {
        const user = {
            id:   13,
            name: 'test'
        };
        const expectedAction = {
            type: GET_USER_SUCCESS,
            user: user
        };
        expect(getUserSuccess(user)).toEqual(expectedAction)
    });
    it('should create an action to list users', () => {
        const users = [
            {
                id:   13,
                name: 'test'
            }
        ];
        const expectedAction = {
            type:  LIST_USER_SUCCESS,
            users: users
        };
        expect(listUsersSuccess(users)).toEqual(expectedAction)
    });
    it('should create an action to create user', () => {
        const expectedAction = {
            type: CREATE_USER
        };
        expect(createUser()).toEqual(expectedAction)
    })
});


text:
package com.google.devtools.j2objc;

import com.google.devtools.j2objc.Options.OutputStyleOption;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Tests for {@link com.google.devtools.j2objc.J2ObjC#run(List)}.
 */
public class J2ObjCTest extends GenerationTest {
  String jarPath;
  String exampleJavaPath;
  String packageInfoPath;

  private static final String EXAMPLE_JAVA_SOURCE =
      "package com.google.devtools.j2objc.annotations;\n\n"
      + "import com.google.j2objc.annotations.ObjectiveCName;\n\n"
      + "@ObjectiveCName(\"foo\")\n"
      + "public class Example {\n"
      + "}\n";

  @Override
  public void setUp() throws IOException {
    super.setUp();

    List<String> classpathEntries = Options.getClassPathEntries();
    for (String entry : getComGoogleDevtoolsJ2objcPath()) {
      classpathEntries.add(entry);
    }

    jarPath = getResourceAsFile("util/example.jar");
    exampleJavaPath = "com/google/devtools/j2objc/util/Example.java";
    packageInfoPath = "com/google/devtools/j2objc/util/package-info.java";
    addSourceFile(
        "package com.google.devtools.j2objc.util; public class Example {}", exampleJavaPath);
    addSourceFile(
        "@ObjectiveCName(\"CBT\")\n"
        + "package com.google.devtools.j2objc.util;\n"
        + "import com.google.j2objc.annotations.ObjectiveCName;", packageInfoPath);
  }

  @Override
  public void tearDown() throws Exception {
    Options.getClassPathEntries().clear();
    Options.setBatchTranslateMaximum(0);
    super.tearDown();
  }

  // No assertions for packageInfoH--nothing interesting in it that other tests don't assert.
  private void makeAssertions(String exampleH, String exampleM, String packageInfoM)
      throws Exception {
    // These assertions should hold for any generated files, including (in the future)
    // combined jar generation.
    assertTranslation(exampleH, "Generated by the J2ObjC translator.");
    assertTranslation(exampleH, "interface CBTExample : NSObject");
    assertTranslation(exampleH, "- (instancetype)init;");
    assertTranslation(exampleH, "J2OBJC_EMPTY_STATIC_INIT(CBTExample)");
    assertTranslation(exampleH, "J2OBJC_TYPE_LITERAL_HEADER(CBTExample)");
    assertTranslation(exampleM, "@implementation CBTExample");
    assertTranslation(exampleM, "- (instancetype)init {");
    assertTranslation(exampleM, "+ (const J2ObjcClassInfo *)__metadata {");
    assertTranslation(exampleM, "J2OBJC_CLASS_TYPE_LITERAL_SOURCE(CBTExample)");
    assertTranslatedLines(packageInfoM,
        "+ (NSString *)__prefix {",
        "  return @\"CBT\";",
        "}");

    assertErrorCount(0);
  }

  private void makeAssertionsForJar() throws Exception {
    String exampleH = getTranslatedFile("com/google/test/Example.h");
    String exampleM = getTranslatedFile("com/google/test/Example.m");
    String packageInfoH = getTranslatedFile("com/google/test/package-info.h");
    String packageInfoM = getTranslatedFile("com/google/test/package-info.m");
    // Test the file header comments.
    assertTranslation(exampleH, "source: jar:file:");
    assertTranslation(exampleM, "source: jar:file:");
    assertTranslation(packageInfoH, "source: jar:file:");
    assertTranslation(packageInfoM, "source: jar:file:");
    assertTranslation(exampleH, jarPath);
    assertTranslation(exampleM, jarPath);
    assertTranslation(packageInfoH, jarPath);
    assertTranslation(packageInfoM, jarPath);
    assertTranslation(exampleH, "com/google/test/Example.java");
    assertTranslation(exampleM, "com/google/test/Example.java");
    assertTranslation(packageInfoH, "com/google/test/package-info.java");
    assertTranslation(packageInfoM, "com/google/test/package-info.java");
    // Test the includes
    assertTranslation(exampleH, "#pragma push_macro(\"INCLUDE_ALL_ComGoogleTestExample\")");
    assertTranslation(exampleM, "#include \"com/google/test/Example.h\"");
    assertTranslation(
        packageInfoH, "#pragma push_macro(\"INCLUDE_ALL_ComGoogleTestPackage_info\")");
    assertTranslation(packageInfoM, "@interface ComGoogleTestpackage_info : NSObject");
    assertTranslation(packageInfoM, "@implementation ComGoogleTestpackage_info");
    // All other assertions
    makeAssertions(exampleH, exampleM, packageInfoM);
  }

  public void testCompilingFromJar() throws Exception {
    J2ObjC.run(Collections.singletonList(jarPath));
    makeAssertionsForJar();
  }

  public void testBatchCompilingFromJar() throws Exception {
    Options.setBatchTranslateMaximum(2);
    J2ObjC.run(Collections.singletonList(jarPath));
    makeAssertionsForJar();
  }

  // Make assertions for java files with default output locations.
  private void makeAssertionsForJavaFiles() throws Exception {
    String exampleH = getTranslatedFile("com/google/devtools/j2objc/util/Example.h");
    String exampleM = getTranslatedFile("com/google/devtools/j2objc/util/Example.m");
    String packageInfoH = getTranslatedFile("com/google/devtools/j2objc/util/package-info.h");
    String packageInfoM = getTranslatedFile("com/google/devtools/j2objc/util/package-info.m");
    assertTranslation(exampleM, "#include \"com/google/devtools/j2objc/util/Example.h\"");
    makeAssertionsForJavaFiles(exampleH, exampleM, packageInfoH, packageInfoM);
  }

  private void makeAssertionsForJavaFiles(
      String exampleH, String exampleM, String packageInfoH, String packageInfoM)
      throws Exception {
    // Test the file header comments.
    assertTranslation(exampleH, exampleJavaPath);
    assertTranslation(exampleM, exampleJavaPath);
    assertTranslation(packageInfoH, packageInfoPath);
    assertTranslation(packageInfoM, packageInfoPath);
    // Test the includes
    assertTranslation(
        exampleH, "#pragma push_macro(\"INCLUDE_ALL_ComGoogleDevtoolsJ2objcUtilExample\")");
    assertTranslation(
        packageInfoM, "@interface ComGoogleDevtoolsJ2objcUtilpackage_info : NSObject");
    assertTranslation(packageInfoH,
        "#pragma push_macro(\"INCLUDE_ALL_ComGoogleDevtoolsJ2objcUtilPackage_info\")");
    assertTranslation(packageInfoM, "@implementation ComGoogleDevtoolsJ2objcUtilpackage_info");
    // All other assertions
    makeAssertions(exampleH, exampleM, packageInfoM);
  }

  public void testCompilingFromFiles() throws Exception {
    J2ObjC.run(Arrays.asList(exampleJavaPath, packageInfoPath));
    makeAssertionsForJavaFiles();
  }

  public void testBatchCompilingFromFiles() throws Exception {
    Options.setBatchTranslateMaximum(2);
    J2ObjC.run(Arrays.asList(exampleJavaPath, packageInfoPath));
    makeAssertionsForJavaFiles();
  }

  private void makeAssertionsForCombinedJar() throws Exception {
    String combinedH = getTranslatedFile(jarPath.replace(".jar", ".h"));
    String combinedM = getTranslatedFile(jarPath.replace(".jar", ".m"));
    makeAssertions(combinedH, combinedM, combinedM);
  }

  public void testCombinedJar() throws Exception {
    Options.setOutputStyle(OutputStyleOption.SOURCE_COMBINED);
    J2ObjC.run(Collections.singletonList(jarPath));
    makeAssertionsForCombinedJar();
  }

  public void testSourceDirsOption() throws Exception {
    Options.setOutputStyle(Options.OutputStyleOption.SOURCE);
    J2ObjC.run(Arrays.asList(exampleJavaPath, packageInfoPath));
    String exampleH = getTranslatedFile(exampleJavaPath.replace(".java", ".h"));
    String exampleM = getTranslatedFile(exampleJavaPath.replace(".java", ".m"));
    String packageInfoH = getTranslatedFile(packageInfoPath.replace(".java", ".h"));
    String packageInfoM = getTranslatedFile(packageInfoPath.replace(".java", ".m"));
    makeAssertionsForJavaFiles(exampleH, exampleM, packageInfoH, packageInfoM);
  }

  // Test a simple annotation processor on the classpath.
  public void testAnnotationProcessing() throws Exception {
    String processorPath = getResourceAsFile("annotations/Processor.jar");
    Options.getClassPathEntries().add(processorPath);

    String examplePath = addSourceFile(EXAMPLE_JAVA_SOURCE, "annotations/Example.java");
    J2ObjC.run(Collections.singletonList(examplePath));
    assertErrorCount(0);

    String translatedAnnotationHeader = getTranslatedFile("ProcessingResult.h");
    String translatedAnnotationImpl = getTranslatedFile("ProcessingResult.m");

    // Our dummy annotation processor is very simple--it always creates a class with no package,
    // ProcessingResult, with a minimal implementation.
    assertTranslation(translatedAnnotationHeader, "@interface ProcessingResult : NSObject");
    assertTranslation(translatedAnnotationHeader, "- (NSString *)getResult;");
    assertTranslation(translatedAnnotationImpl, "@implementation ProcessingResult");
    assertTranslation(translatedAnnotationImpl, "return @\"ObjectiveCName\"");
  }

  // Test a simple annotation processor on the processor path.
  public void testAnnotationProcessingWithProcessorPath() throws Exception {
    String processorPath = getResourceAsFile("annotations/Processor.jar");
    Options.getProcessorPathEntries().add(processorPath);

    String examplePath = addSourceFile(EXAMPLE_JAVA_SOURCE, "annotations/Example.java");
    J2ObjC.run(Collections.singletonList(examplePath));
    assertErrorCount(0);
  }

  // Test a specified annotation processor.
  public void testSpecifiedAnnotationProcessing() throws Exception {
    String processorPath = getResourceAsFile("annotations/Processor.jar");
    Options.getClassPathEntries().add(processorPath);
    Options.setProcessors("com.google.devtools.j2objc.annotations.J2ObjCTestProcessor");

    String examplePath = addSourceFile(EXAMPLE_JAVA_SOURCE, "annotations/Example.java");
    J2ObjC.run(Collections.singletonList(examplePath));
    assertErrorCount(0);
  }
}


text:
require "roger/test"

module RogerScsslint
  # SCSS linter plugin for Roger
  class Lint
    # Configurability is the root of all evil
    # http://fishshell.com/docs/current/design.html#conf
    def initialize(options = {})
      @options = {
        config_file: ".scss-lint.yml",
        scss_lint: "scss-lint"
      }

      detect_scsslint
      @options.update(options) if options
    end

    def call(test, _options)
      test.log(self, "SCSS linting files")
      system(Shellwords.join([@options[:scss_lint], "--config=#{@options[:config_file]}"]))
    end

    private

    def detect_scsslint
      command = [@options[:scss_lint], "-v", ">/dev/null"]
      detect = system(Shellwords.join(command))
      fail "Could not find linter. Linter should be in Gemfile." unless detect
    end
  end
end

Roger::Test.register :scsslint, RogerScsslint::Lint


text:
@interface PodsDummy_Pods_mobile : NSObject
@end
@implementation PodsDummy_Pods_mobile
@end


text:
// Purpose:      Enemy invaders
// Rev:          1.0
// Last updated: 22/03/10

using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace GridcoinGalaza
{
    public class clsInvader : clsCommon
    {

        private int gravitycount = 0;
        private bool gravity_warp_on = false;
        public bool ship_abducted = false;
        public int ScreenHeight = 900;
        private double abduction_Y = 0;
        // Obj refs and instances
        private System.Drawing.Bitmap[,] invader = new System.Drawing.Bitmap[6, 2];
        private System.Drawing.Bitmap[] background = new System.Drawing.Bitmap[7];
        private ImageAttributes ImageAtt = new ImageAttributes();
        private clsTScales tScales = new clsTScales();
        private clsCommon soundSurrogate = null;
        // Properties for this class
        private int invaderType;
        private int dockingCell;
        private int diveFrame;
        private int playerX;
        private int diveX;
        private int diveType;
        private bool lockedOn;
        private bool lockOnX1;
        private bool lockOnX2;
        private bool shoot;

        private bool docked;
        private bool docking;
        private bool reDocking;
        private bool rotate;
        private bool dive;
        private bool active;
        private bool hasCell;
        private bool twirl;
        private double angle;

        // Class refs ...
        private clsInvaderBullet bullet;
        private clsInvaderBullet bullet2;

        public clsInvader(int x, int y, int invaderType, bool active, clsCommon SoundSurrogate): base(x, y, 0, 0)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Class constructor
            //------------------------------------------------------------------------------------------------------------------
            soundSurrogate = SoundSurrogate;

            // Assign properties with values
            this.invaderType = invaderType;
            this.active = active;

            //:: Load resource image(s) & remove background
            invader[0, 0] = GridcoinGalaza.Properties.Resources.enemyD1;
            invader[0, 1] = GridcoinGalaza.Properties.Resources.enemyD2;
            invader[1, 0] = GridcoinGalaza.Properties.Resources.enemyA1;
            invader[1, 1] = GridcoinGalaza.Properties.Resources.enemyA2;
            invader[2, 0] = GridcoinGalaza.Properties.Resources.enemyE1;
            invader[2, 1] = GridcoinGalaza.Properties.Resources.enemyE2;
            invader[3, 0] = GridcoinGalaza.Properties.Resources.enemyB1;
            invader[3, 1] = GridcoinGalaza.Properties.Resources.enemyB2;
            invader[4, 0] = GridcoinGalaza.Properties.Resources.enemyC1;
            invader[4, 1] = GridcoinGalaza.Properties.Resources.enemyC2;
            invader[5, 0] = GridcoinGalaza.Properties.Resources.enemyF1;
            invader[5, 1] = GridcoinGalaza.Properties.Resources.enemyF2;

            // Remove backgrounds ...
            int i = 0;
            int j = 0;

            for (j = 0; j <= 1; j++)
            {
                for (i = 0; i <= 5; i++)
                {
                    invader[i, j].MakeTransparent(Color.White);
                }
            }
        }

        public void doDive()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method to dive straight down towards player
            //-----------------------------------------------------------------------------------------------------------------

            double x = 0;
            double y = 0;
            double deg = 360 / 12;
            double radius = 25;

            // Inc time scalers
            tScales.setTScaleB(tScales.getTAcaleB() + 1);
            tScales.setTScaleB(tScales.getTAcaleB() % 10);

            //:: Rotate from dock at start of dive ::
            if (this.twirl == false)
            {
                // Type val of 0 denotes a rotate before dive, otherwise a straight down dive
                if (this.getDiveType() == 0)
                {
                    // 10 Frames of it
                    if (this.getDiveFrame() < 10)
                    {
                        if (tScales.getTAcaleB() == 0)
                        {
                            // Fetch x & y
                            x = GetCos(this.getDiveFrame() * deg + 90) * radius;
                            y = GetSin(this.getDiveFrame() * deg + 90) * radius;

                            // Apply coords
                            base.setX(base.getX() + -Convert.ToInt32(x));
                            base.setY(base.getY() + -Convert.ToInt32(y));

                            // Inc dive frame counter
                            this.setDiveFrame(this.getDiveFrame() + 1);
                        }
                    }
                    else
                    {
                        // Now do twirl towards player
                        this.twirl = true;
                    }

                }
                else
                {
                    // Dive type is straight down
                    this.twirl = true;
                }

                //- Lock on to player's x-axis -
            }
            else
            {

                if (!lockedOn)
                {
                    // Inc / dec x-axis until we find player's ship
                    if (base.getX() < playerX)
                    {
                        x += 3;
                        lockOnX1 = true;
                    }
                    else
                    {
                        x -= 3;
                        lockOnX2 = true;
                    }

                    // Locked on, set flag ...
                    if (lockOnX1 & lockOnX2)
                    {
                        lockedOn = true;
                    }
                }

                //:: Dive towards player ::

                // Twirl back and forth
                diveX += 1;
                diveX = diveX % 64;
                if (diveX < 32)
                    x -= 2;
                if (diveX > 32)
                    x += 2;

                // Apply x & y locations ...
                base.setX(base.getX() + Convert.ToInt32(x));
                //4-19-2015

                if (diveX % 50 == 1)
                {
                    if (this.invaderType == 3 && base.getY() > 500 && !gravity_warp_on && !clsShared.global_gravity_warp_on
                        && !clsShared._clsPlayer.DoubleWideShip && clsShared.AbductionPhase == 0 && !clsShared.Global_Abducted)
                   {

                       if (!clsShared._clsPlayer.isDead() && !clsShared._clsPlayer.isDoingWarp())
                       {

                           //3 == Green Invader
                           //2 == Yellow Invader
                           gravity_warp_on = true;
                           clsShared.global_gravity_warp_on = true;
                           soundSurrogate.sndEffects[6].playSND(false);
                       }
                    }
                }

                if (!gravity_warp_on)               base.setY(base.getY() + 3);

                // Invader off the screen? -- reset and prepare to redock
                if (base.getY() > ScreenHeight)
                {
                    ReDockAlien();
                }
            }
        }

        public void ReDockAlien()
        {
            this.diveFrame = 0;
            this.diveX = 0;
            this.dive = false;
            this.docking = true;
            this.reDocking = true;
            this.lockedOn = false;
            this.lockOnX1 = false;
            this.lockOnX2 = false;
            this.twirl = false;
            base.setX(300);
            base.setY(0);

        }

        public void CheckForGravity(Graphics Destination)
        {
            //Halford 4-18-2015 If Invader Type is the B1 or C1, and dive is halfway down, and Gravity Field is applicable, start gravity field:
            if (gravity_warp_on)
            {
                double WIDTH = 100;
                int ship_y = (int)(clsShared._clsPlayer.getY() - abduction_Y);
                for (int yy = base.getY(); yy < ship_y; yy += 3)
                {
                    WIDTH = WIDTH - .5;
                    if (WIDTH < 5) WIDTH = 5;
                    DrawGravity(Destination, base.getX() - (int)(WIDTH / 2), yy + 20, (int)WIDTH);
                }
                //Check to see if player has been abducted
                if (clsShared._clsPlayer.getX() > base.getX() - 20 && clsShared._clsPlayer.getX() < base.getX() + 20 && clsShared.AbductionPhase == 0)
                {
                    clsShared.AbductionPhase = 1;
                    clsShared.iAbductionCounter = 0;
                    //Abduct the ship
                    soundSurrogate.sndEffects[6].playSND(false);
                    soundSurrogate.sndEffects[7].playSND(false);  //Abduction loop
                    abduction_Y=0;

                  //  clsShared._clsPlayer.setDoWarp(true);
                }
                else if (clsShared.AbductionPhase == 0)
                    {
                        //Ship is not in the field, but gravity field is on
                        soundSurrogate.sndEffects[6].playSND(false);

                    }

                if (clsShared.AbductionPhase == 1)
                {

                    soundSurrogate.sndEffects[7].playSND(false);  //Abduction loop

                    //Abduct the ship towards the alien
                    abduction_Y += 4;
                    this.setY(this.getY() - 3);
                    if (clsShared._clsPlayer.getY() - abduction_Y < 75) abduction_Y = abduction_Y - 5;
                    clsShared._clsPlayer.setWarpY((int)abduction_Y);
                    if (this.getY() < 50) this.setY(50);
                    if (this.getY() < 75  && (clsShared._clsPlayer.getY()-abduction_Y) < 100)
                    {
                        //Abduction complete
                        clsShared.lives -= 1;
                        gravity_warp_on = false;
                        clsShared.global_gravity_warp_on = false;
                        clsShared._clsPlayer.setWarpY(0);
                        ship_abducted = true;
                        clsShared.Global_Abducted = true;
                        soundSurrogate.sndEffects[6].playSND(false); //WARP SOUND
                        clsShared.AbductionPhase = 0;
                        ReDockAlien();
                        //If we abducted last ship, game is over:
                        if (clsShared.lives < -1)
                        {
                            clsShared.gameOver = true;
                        }

                    }

                }

            }

        }

        public void DrawGravity(Graphics Destination, int X, int Y, int WIDTH)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method to render pixels to graphics buffer
            //------------------------------------------------------------------------------------------------------------------

            // Creat brush instance
            SolidBrush brush = new SolidBrush(Color.White);

            // Draw sprite
            Destination.FillRectangle(brush, X, Y, WIDTH, 1);

            // Clean up
            brush.Dispose();
        }

        private double GetSin(double degAngle)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method (return sin)
            //------------------------------------------------------------------------------------------------------------------

            return Math.Sin(Math.PI * degAngle / 180);
        }

        private double GetCos(double degAngle)
        {
            //------------------------------------------------------------------------------------------------------------------
            //  Purpose: Method (return cosin)
            //------------------------------------------------------------------------------------------------------------------

            return Math.Cos(Math.PI * degAngle / 180);
        }

        public int getDiveType()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch dive type: targeted or just straight down)
            //------------------------------------------------------------------------------------------------------------------

            return this.diveType;
        }

        public bool hasDockingCell()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (does this invader have a docking cell allocated?)
            //------------------------------------------------------------------------------------------------------------------

            return this.hasCell;
        }

        public bool isActive()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader active?)
            //------------------------------------------------------------------------------------------------------------------

            return this.active;
        }

        public void setActive(bool active)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader active)
            //-----------------------------------------------------------------------------------------------------------------

            this.active = active;
        }

        public bool isRedocking()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader docking?)
            //------------------------------------------------------------------------------------------------------------------

            return this.reDocking;
        }

        public void setRedocking(bool reDocking)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader to do re-docking after a dive)
            //-----------------------------------------------------------------------------------------------------------------

            this.reDocking = reDocking;
        }

        public int getInvaderType()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch invader type)
            //------------------------------------------------------------------------------------------------------------------

            return this.invaderType;
        }

        public void setInvaderType(int invaderType)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader type)
            //-----------------------------------------------------------------------------------------------------------------

            this.invaderType = invaderType;
            base.setH(this.invader[invaderType, 0].Height);
            base.setW(this.invader[invaderType, 0].Width);
        }

        public bool isDiving()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader currently diving?)
            //------------------------------------------------------------------------------------------------------------------

            return this.dive;
        }

        public void setDoDiving(bool dive, int playerX, int diveType)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader to init diving)
            //-----------------------------------------------------------------------------------------------------------------
            if (ship_abducted) return;  //Dont allow alien holding an abducted ship to Dive

            this.dive = dive;
            this.playerX = playerX;
            this.diveType = diveType;
        }

        public int getDiveFrame()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch current dive frame)
            //------------------------------------------------------------------------------------------------------------------

            return this.diveFrame;
        }

        public void setDiveFrame(int diveFrame)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Purpose: Mutator (set invader dive frame)
            //-----------------------------------------------------------------------------------------------------------------

            this.diveFrame = diveFrame;
        }

        public bool isShooting()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader shooting?)
            //------------------------------------------------------------------------------------------------------------------

            return this.shoot;
        }

        public void setDoShooting(bool shoot)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method (set invader to init shooting)
            //-----------------------------------------------------------------------------------------------------------------

            if (shoot)
            {
                this.bullet = new clsInvaderBullet(base.getX() + 10, base.getY());
                this.shoot = shoot;

                this.bullet2 = new clsInvaderBullet(base.getX() + 7, base.getY());
                //this.shoot2 = shoot;

            }
            else
            {
                this.bullet = null;
                this.bullet2 = null;
                this.shoot = false;
            }
        }

        public bool isDocking()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader docking?)
            //------------------------------------------------------------------------------------------------------------------

            return this.docking;
        }

        public void setDoDocking(bool docking)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader to dock)
            //------------------------------------------------------------------------------------------------------------------

            this.docking = docking;
        }

        public int getDockingCell()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch dock cell num)
            //------------------------------------------------------------------------------------------------------------------

            return this.dockingCell;
        }

        public void setDockingCell(int dockingCell)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (assign an invader with a specific docking cell num)
            //------------------------------------------------------------------------------------------------------------------

            this.dockingCell = dockingCell;
            this.hasCell = true;
        }

        public bool isDocked()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader docked?)
            //------------------------------------------------------------------------------------------------------------------

            return this.docked;
        }

        public void setDocked(bool docked)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader docked)
            //------------------------------------------------------------------------------------------------------------------

            this.docked = docked;
        }

        public bool isRotating()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (is this invader rotating?)
            //------------------------------------------------------------------------------------------------------------------

            return this.rotate;
        }

        public void setDoRotate(bool rotate)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader to rotate)
            //------------------------------------------------------------------------------------------------------------------

            this.rotate = rotate;
        }

        public double getAngle()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch current rotation angle)
            //------------------------------------------------------------------------------------------------------------------

            return this.angle;

        }

        public void setAngle(double angle)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Mutator (set invader angle)
            //------------------------------------------------------------------------------------------------------------------

            this.angle = angle;
        }

        public int getBulletRectX()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch invader bullet collision rect x axis)
            //------------------------------------------------------------------------------------------------------------------

            return this.bullet.getRectX();
        }

        public int getBulletRectY()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch invader bullet collision rect y axis)
            //------------------------------------------------------------------------------------------------------------------

            return this.bullet.getRectY();
        }

        public int getBulletRectW()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch invader bullet collision rect width)
            //------------------------------------------------------------------------------------------------------------------

            return this.bullet.getRectW();
        }

        public int getBulletRectH()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Accessor (fetch invader bullet collision rect height)
            //------------------------------------------------------------------------------------------------------------------

            return this.bullet.getRectH();
        }

        public void doShoot(Graphics Destination)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method to control the invaders bullets
            //------------------------------------------------------------------------------------------------------------------

            if (this.bullet.getY() < ScreenHeight)
            {
                // Shift bullets down the screen
                if (this.bullet != null)
                {
                    this.bullet.moveBullets(Destination,0);
                    this.bullet2.moveBullets(Destination,2);
                }
            }
            else //- bullet has moved off the screen then kill off instance
            {
                this.bullet = null;
                this.shoot = false;
                this.bullet2 = null;
            }

        }

        public void Draw(Graphics Destination, double angle, int ani, bool rotate)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: method to draw invader sprites with or with rotation and sync collision rect
            //
            // Rotation method obtained from:
            // http://jelle.druyts.net/2004/05/26/RotatingAnImageAroundItsCenterInNET.aspx
            //------------------------------------------------------------------------------------------------------------------
            CheckForGravity(Destination);

            // Apply width and height for this invader
            base.setW(this.invader[this.invaderType, ani].Width);
            base.setH(this.invader[this.invaderType, ani].Height);

            if (rotate)
            {
                // Rotate the coordinates of the rectangle's corners
                Point upperLeft = RotatePoint(new Point(-invader[this.invaderType, ani].Width / 2, invader[this.invaderType, ani].Height / 2), angle);
                Point upperRight = RotatePoint(new Point(invader[this.invaderType, ani].Width / 2, invader[this.invaderType, ani].Height / 2), angle);
                Point lowerLeft = RotatePoint(new Point(-invader[this.invaderType, ani].Width / 2, -invader[this.invaderType, ani].Height / 2), angle);

                // Create the points array by offsetting the coordinates with the center
                Point[] points = {upperLeft, upperRight, lowerLeft};

                // Draw the rotated image
                Destination.DrawImage(invader[this.invaderType, ani], points);

                if (ship_abducted)
                {
                    Destination.DrawImage(clsShared._clsPlayer.player[0],
                        new Rectangle(base.getX() + 30, base.getY() - 30,
                        clsShared._clsPlayer.player[0].Width,
                        clsShared._clsPlayer.player[0].Height),
                        0, 0, clsShared._clsPlayer.player[0].Width, clsShared._clsPlayer.player[0].Height, GraphicsUnit.Pixel,
                        clsShared._clsPlayer.ImagingAtt);

                }

            }
            else // Render invader with no rotation applied
            {

                Destination.DrawImage(invader[this.invaderType, ani], new Rectangle(base.getX(), base.getY(), invader[this.invaderType, ani].Width, invader[this.invaderType, ani].Height), 0, 0, invader[this.invaderType, ani].Width, invader[this.invaderType, ani].Height, GraphicsUnit.Pixel, ImageAtt);

                if (ship_abducted)
                {
                    Destination.DrawImage(clsShared._clsPlayer.player[0],
                        new Rectangle(base.getX()+30, base.getY()-30,
                        clsShared._clsPlayer.player[0].Width,
                        clsShared._clsPlayer.player[0].Height),
                        0, 0, clsShared._clsPlayer.player[0].Width, clsShared._clsPlayer.player[0].Height, GraphicsUnit.Pixel,
                        clsShared._clsPlayer.ImagingAtt);

                }
            }

            // Sync collision rect ...
            base.setRectW(base.getW());
            base.setRectH(base.getH());
            base.setRectX(base.getX());
            base.setRectY(base.getY());
        }

        public Point RotatePoint(Point p, double angle)
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method rotates a point around the origin by the specified angle (in radians)
            // 1 radians = 57.2957795 degrees
            //
            // Rotation method obtained from:
            // http://jelle.druyts.net/2004/05/26/RotatingAnImageAroundItsCenterInNET.aspx
            //------------------------------------------------------------------------------------------------------------------

            // Fetch coords
            int x = Convert.ToInt32(p.X * Math.Cos(angle) + p.Y * Math.Sin(angle));
            int y = Convert.ToInt32(-p.X * Math.Sin(angle) + p.Y * Math.Cos(angle));

            // return them ...
            return new Point(x + base.getX() + (base.getW() / 2), y + base.getY() + (base.getH() / 2));
        }

        public void resetAll()
        {
            //------------------------------------------------------------------------------------------------------------------
            // Purpose: Method to null all properties for a new level ...
            // Creating entirely new instances of this class for every new level is very ineffecient, taking around 500mS on a P4
            //------------------------------------------------------------------------------------------------------------------

            // Super class
            base.setX(-50);
            base.setY(0);
            base.setRectX(base.getX());
            base.setRectY(base.getY());

            // This class
            this.diveFrame = 0;
            this.playerX = 0;
            this.diveX = 0;
            this.lockedOn = false;
            this.lockOnX1 = false;
            this.lockOnX2 = false;
            this.shoot = false;
            this.docked = false;
            this.docking = false;
            this.reDocking = false;
            this.rotate = false;
            this.dive = false;
            this.hasCell = false;
            this.twirl = false;
            this.angle = 0;
            this.dockingCell = 0;
        }
    }
}


text:
package org.jasig.cas.monitor;

import org.jasig.cas.util.LdapUtils;
import org.ldaptive.Connection;
import org.ldaptive.ConnectionFactory;
import org.ldaptive.LdapException;
import org.ldaptive.pool.Validator;

/**
 * Monitors an ldaptive {@link ConnectionFactory}.  While this class can be used with instances of
 * {@link org.ldaptive.pool.PooledConnectionFactory}, the {@link PooledConnectionFactoryMonitor} class is preferable.
 *
 * @author Marvin S. Addison
 * @since 4.0.0
 */
public class ConnectionFactoryMonitor extends AbstractNamedMonitor<Status> {

    /** OK status. */
    private static final Status OK = new Status(StatusCode.OK);

    /** Error status. */
    private static final Status ERROR = new Status(StatusCode.ERROR);

    /** Source of connections to validate. */
    private final ConnectionFactory connectionFactory;

    /** Connection validator. */
    private final Validator<Connection> validator;

    /**
     * Creates a new instance that monitors the given connection factory.
     *
     * @param  factory  Connection factory to monitor.
     * @param  validator  Validates connections from the factory.
     */
    public ConnectionFactoryMonitor(final ConnectionFactory factory, final Validator<Connection> validator) {
        this.connectionFactory = factory;
        this.validator = validator;
    }

    /**
     * Gets a connection from the underlying connection factory and attempts to validate it.
     *
     * @return  Status with code {@link StatusCode#OK} on success otherwise {@link StatusCode#ERROR}.
     */
    @Override
    public Status observe() {
        Connection conn = null;
        try {
            conn = this.connectionFactory.getConnection();
            if (!conn.isOpen()) {
                conn.open();
            }
            return this.validator.validate(conn) ? OK : ERROR;
        } catch (final LdapException e) {
            logger.warn("Validation failed with error.", e);
        } finally {
            LdapUtils.closeConnection(conn);
        }
        return ERROR;
    }
}


text:
<?php

namespace Acme\BlogBundle\Form\Type;

use Acme\BlogBundle\Form\Extension\DataTransformer\ArrayToStringTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;

class TextListType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addViewTransformer(new ArrayToStringTransformer($options['separator'], $options['unique_values']));
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'separator' => ', ',
                'unique_values' => true,
            )
        );
    }

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

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


text:
<?php

class Snowcode_GoogleCloudPrint_Model_System_Config_Source_Printers
{
    /**
     * Get Printers from GCP
     *
     * @return array
     */
    private function _getPrinters()
    {
        $connector = Mage::helper('scgooglecloudprint/connector');
        $printers = $connector->search();
        return (!empty($printers)) ? $printers : array();
    }

    /**
     * Options getter
     *
     * @return array
     */
    public function toOptionArray()
    {
        $printers = $this->_getPrinters();
        $resultPrinters = array();
        if (!empty($printers)) {
            foreach ($printers as $printer) {
                $resultPrinters[] = array(
                    'value' => $printer->id,
                    'label' => (!empty($printer->defaultDisplayName)) ? $printer->defaultDisplayName : $printer->name
                );
            }
        }
        return $resultPrinters;
    }

    /**
     * Get options in "key-value" format
     *
     * @return array
     */
    public function toArray()
    {
        $printers = $printers = $this->_getPrinters();
        $resultPrinters = array();
        if (!empty($printers)) {
            foreach ($printers as $printer) {
                $resultPrinters[] = array(
                    $printer->id => (!empty($printer->defaultDisplayName)) ?
                            $printer->defaultDisplayName : $printer->name
                );
            }
        }
        return $resultPrinters;
    }
}


text: extern NSString* gRKCatalogBaseURL;


text:
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Input;
using LogService;

namespace WinFormsMvvm.Controls
{
    [System.ComponentModel.DesignerCategory("")]
    [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
    public class ToolStripCommandMenuItem : ToolStripMenuItem, IBindableComponent
    {
        private ICommand _command;
        private ControlBindingsCollection _dataBindings;
        private BindingContext _bindingContext;

        [DefaultValue(null)]
        [Browsable(false)]
        [Bindable(true)]
        public ICommand Command
        {
            get { return _command; }
            set
            {
                if (_command == value)
                    return;
                SetCommand(value);
            }
        }

        private void SetCommand(ICommand command)
        {
            if (_command != null)
            {
                _command.CanExecuteChanged -= CommandOnCanExecuteChanged;
            }

            _command = command;

            if (_command != null)
            {
                Enabled = command.CanExecute(null);
                _command.CanExecuteChanged += CommandOnCanExecuteChanged;
            }
        }

        protected override void OnClick(EventArgs e)
        {

            base.OnClick(e);
            if (_command != null && _command.CanExecute(null))
            {
                try
                {
                    Log.Information("Execute {0} in {1}", CallerInfo.Create(), this.Name, this.GetType().FullName);

                    _command.Execute(null);

                }
                catch (Exception ex)
                {
                    Log.Error(ex,CallerInfo.Create(),"OnClick: "+this.Name);
                }
            }
        }

        private void CommandOnCanExecuteChanged(object sender, EventArgs eventArgs)
        {
            if (_command != null)
            {
                Enabled = _command.CanExecute(null);
            }
        }

        #region IBindableComponent

        [Category("Data")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [RefreshProperties(RefreshProperties.All)]
        [ParenthesizePropertyName(true)]
        [Description("The data bindings for the controls.")]
        public ControlBindingsCollection DataBindings
        {
            get
            {
                return _dataBindings = _dataBindings ?? new ControlBindingsCollection(this);
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public BindingContext BindingContext
        {
            get
            {
                return _bindingContext = _bindingContext ?? new BindingContext();
            }
            set { _bindingContext = value; }
        }

        #endregion
    }
}


text:
$partial("templates/post-item.html")$
$partial("templates/comments.html")$


text:
namespace capnp {
namespace _ {
namespace {

using Thing = test::TestMembrane::Thing;

class ThingImpl final: public Thing::Server {
public:
  ThingImpl(kj::StringPtr text): text(text) {}

protected:
  kj::Promise<void> passThrough(PassThroughContext context) override {
    context.getResults().setText(text);
    return kj::READY_NOW;
  }

  kj::Promise<void> intercept(InterceptContext context) override {
    context.getResults().setText(text);
    return kj::READY_NOW;
  }

private:
  kj::StringPtr text;
};

class TestMembraneImpl final: public test::TestMembrane::Server {
protected:
  kj::Promise<void> makeThing(MakeThingContext context) override {
    context.getResults().setThing(kj::heap<ThingImpl>("inside"));
    return kj::READY_NOW;
  }

  kj::Promise<void> callPassThrough(CallPassThroughContext context) override {
    auto params = context.getParams();
    auto req = params.getThing().passThroughRequest();
    if (params.getTailCall()) {
      return context.tailCall(kj::mv(req));
    } else {
      return req.send().then(
          [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable {
        context.setResults(result);
      });
    }
  }

  kj::Promise<void> callIntercept(CallInterceptContext context) override {
    auto params = context.getParams();
    auto req = params.getThing().interceptRequest();
    if (params.getTailCall()) {
      return context.tailCall(kj::mv(req));
    } else {
      return req.send().then(
          [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable {
        context.setResults(result);
      });
    }
  }

  kj::Promise<void> loopback(LoopbackContext context) override {
    context.getResults().setThing(context.getParams().getThing());
    return kj::READY_NOW;
  }
};

class MembranePolicyImpl: public MembranePolicy, public kj::Refcounted {
public:
  kj::Maybe<Capability::Client> inboundCall(uint64_t interfaceId, uint16_t methodId,
                                            Capability::Client target) override {
    if (interfaceId == capnp::typeId<Thing>() && methodId == 1) {
      return Capability::Client(kj::heap<ThingImpl>("inbound"));
    } else {
      return nullptr;
    }
  }

  kj::Maybe<Capability::Client> outboundCall(uint64_t interfaceId, uint16_t methodId,
                                             Capability::Client target) override {
    if (interfaceId == capnp::typeId<Thing>() && methodId == 1) {
      return Capability::Client(kj::heap<ThingImpl>("outbound"));
    } else {
      return nullptr;
    }
  }

  kj::Own<MembranePolicy> addRef() override {
    return kj::addRef(*this);
  }
};

void testThingImpl(kj::WaitScope& waitScope, test::TestMembrane::Client membraned,
                   kj::Function<Thing::Client()> makeThing,
                   kj::StringPtr localPassThrough, kj::StringPtr localIntercept,
                   kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) {
  KJ_EXPECT(makeThing().passThroughRequest().send().wait(waitScope).getText() == localPassThrough);
  KJ_EXPECT(makeThing().interceptRequest().send().wait(waitScope).getText() == localIntercept);

  {
    auto req = membraned.callPassThroughRequest();
    req.setThing(makeThing());
    req.setTailCall(false);
    KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough);
  }
  {
    auto req = membraned.callInterceptRequest();
    req.setThing(makeThing());
    req.setTailCall(false);
    KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept);
  }
  {
    auto req = membraned.callPassThroughRequest();
    req.setThing(makeThing());
    req.setTailCall(true);
    KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough);
  }
  {
    auto req = membraned.callInterceptRequest();
    req.setThing(makeThing());
    req.setTailCall(true);
    KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept);
  }
}

struct TestEnv {
  kj::EventLoop loop;
  kj::WaitScope waitScope;
  kj::Own<MembranePolicyImpl> policy;
  test::TestMembrane::Client membraned;

  TestEnv()
      : waitScope(loop),
        policy(kj::refcounted<MembranePolicyImpl>()),
        membraned(membrane(kj::heap<TestMembraneImpl>(), policy->addRef())) {}

  void testThing(kj::Function<Thing::Client()> makeThing,
                 kj::StringPtr localPassThrough, kj::StringPtr localIntercept,
                 kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) {
    testThingImpl(waitScope, membraned, kj::mv(makeThing),
                  localPassThrough, localIntercept, remotePassThrough, remoteIntercept);
  }
};

KJ_TEST("call local object inside membrane") {
  TestEnv env;
  env.testThing([&]() {
    return env.membraned.makeThingRequest().send().wait(env.waitScope).getThing();
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call local promise inside membrane") {
  TestEnv env;
  env.testThing([&]() {
    return env.membraned.makeThingRequest().send().getThing();
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call local resolved promise inside membrane") {
  TestEnv env;
  env.testThing([&]() {
    auto thing = env.membraned.makeThingRequest().send().getThing();
    thing.whenResolved().wait(env.waitScope);
    return thing;
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call local object outside membrane") {
  TestEnv env;
  env.testThing([&]() {
    return kj::heap<ThingImpl>("outside");
  }, "outside", "outside", "outside", "outbound");
}

KJ_TEST("call local capability that has passed into and back out of membrane") {
  TestEnv env;
  env.testThing([&]() {
    auto req = env.membraned.loopbackRequest();
    req.setThing(kj::heap<ThingImpl>("outside"));
    return req.send().wait(env.waitScope).getThing();
  }, "outside", "outside", "outside", "outbound");
}

KJ_TEST("call local promise pointing into membrane that eventually resolves to outside") {
  TestEnv env;
  env.testThing([&]() {
    auto req = env.membraned.loopbackRequest();
    req.setThing(kj::heap<ThingImpl>("outside"));
    return req.send().getThing();
  }, "outside", "outside", "outside", "outbound");
}

KJ_TEST("apply membrane using copyOutOfMembrane() on struct") {
  TestEnv env;

  env.testThing([&]() {
    MallocMessageBuilder outsideBuilder;
    auto root = outsideBuilder.initRoot<test::TestContainMembrane>();
    root.setCap(kj::heap<ThingImpl>("inside"));
    MallocMessageBuilder insideBuilder;
    insideBuilder.adoptRoot(copyOutOfMembrane(
        root.asReader(), insideBuilder.getOrphanage(), env.policy->addRef()));
    return insideBuilder.getRoot<test::TestContainMembrane>().getCap();
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("apply membrane using copyOutOfMembrane() on list") {
  TestEnv env;

  env.testThing([&]() {
    MallocMessageBuilder outsideBuilder;
    auto list = outsideBuilder.initRoot<test::TestContainMembrane>().initList(1);
    list.set(0, kj::heap<ThingImpl>("inside"));
    MallocMessageBuilder insideBuilder;
    insideBuilder.initRoot<test::TestContainMembrane>().adoptList(copyOutOfMembrane(
        list.asReader(), insideBuilder.getOrphanage(), env.policy->addRef()));
    return insideBuilder.getRoot<test::TestContainMembrane>().getList()[0];
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("apply membrane using copyOutOfMembrane() on AnyPointer") {
  TestEnv env;

  env.testThing([&]() {
    MallocMessageBuilder outsideBuilder;
    auto ptr = outsideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField();
    ptr.setAs<test::TestMembrane::Thing>(kj::heap<ThingImpl>("inside"));
    MallocMessageBuilder insideBuilder;
    insideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField().adopt(copyOutOfMembrane(
        ptr.asReader(), insideBuilder.getOrphanage(), env.policy->addRef()));
    return insideBuilder.getRoot<test::TestAnyPointer>().getAnyPointerField()
        .getAs<test::TestMembrane::Thing>();
  }, "inside", "inbound", "inside", "inside");
}

struct TestRpcEnv {
  kj::AsyncIoContext io;
  kj::TwoWayPipe pipe;
  TwoPartyClient client;
  TwoPartyClient server;
  test::TestMembrane::Client membraned;

  TestRpcEnv()
      : io(kj::setupAsyncIo()),
        pipe(io.provider->newTwoWayPipe()),
        client(*pipe.ends[0]),
        server(*pipe.ends[1],
               membrane(kj::heap<TestMembraneImpl>(), kj::refcounted<MembranePolicyImpl>()),
               rpc::twoparty::Side::SERVER),
        membraned(client.bootstrap().castAs<test::TestMembrane>()) {}

  void testThing(kj::Function<Thing::Client()> makeThing,
                 kj::StringPtr localPassThrough, kj::StringPtr localIntercept,
                 kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) {
    testThingImpl(io.waitScope, membraned, kj::mv(makeThing),
                  localPassThrough, localIntercept, remotePassThrough, remoteIntercept);
  }
};

KJ_TEST("call remote object inside membrane") {
  TestRpcEnv env;
  env.testThing([&]() {
    return env.membraned.makeThingRequest().send().wait(env.io.waitScope).getThing();
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call remote promise inside membrane") {
  TestRpcEnv env;
  env.testThing([&]() {
    return env.membraned.makeThingRequest().send().getThing();
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call remote resolved promise inside membrane") {
  TestEnv env;
  env.testThing([&]() {
    auto thing = env.membraned.makeThingRequest().send().getThing();
    thing.whenResolved().wait(env.waitScope);
    return thing;
  }, "inside", "inbound", "inside", "inside");
}

KJ_TEST("call remote object outside membrane") {
  TestRpcEnv env;
  env.testThing([&]() {
    return kj::heap<ThingImpl>("outside");
  }, "outside", "outside", "outside", "outbound");
}

KJ_TEST("call remote capability that has passed into and back out of membrane") {
  TestRpcEnv env;
  env.testThing([&]() {
    auto req = env.membraned.loopbackRequest();
    req.setThing(kj::heap<ThingImpl>("outside"));
    return req.send().wait(env.io.waitScope).getThing();
  }, "outside", "outside", "outside", "outbound");
}

KJ_TEST("call remote promise pointing into membrane that eventually resolves to outside") {
  TestRpcEnv env;
  env.testThing([&]() {
    auto req = env.membraned.loopbackRequest();
    req.setThing(kj::heap<ThingImpl>("outside"));
    return req.send().getThing();
  }, "outside", "outside", "outside", "outbound");
}

}  // namespace
}  // namespace _
}  // namespace capnp