text:
<?php
namespace Platformsh\Cli\Command\Local;

use Platformsh\Cli\Command\PlatformCommand;
use Platformsh\Cli\Exception\RootNotFoundException;
use Platformsh\Cli\Local\LocalBuild;
use Platformsh\Cli\Local\LocalProject;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class LocalBuildCommand extends PlatformCommand
{

    protected $defaultDrushConcurrency = 4;

    protected function configure()
    {
        $this
          ->setName('local:build')
          ->setAliases(array('build'))
          ->addArgument('app', InputArgument::IS_ARRAY, 'Specify application(s) to build')
          ->setDescription('Build the current project locally')
          ->addOption(
            'abslinks',
            'a',
            InputOption::VALUE_NONE,
            'Use absolute links'
          )
          ->addOption(
            'source',
            null,
            InputOption::VALUE_OPTIONAL,
            'The source directory. Default: ' . LocalProject::REPOSITORY_DIR
          )
          ->addOption(
            'destination',
            null,
            InputOption::VALUE_OPTIONAL,
            'The destination, to which the web root of each app will be symlinked. Default: ' . LocalProject::WEB_ROOT
          )
          ->addOption(
            'copy',
            null,
            InputOption::VALUE_NONE,
            'Copy to a build directory, instead of symlinking from the source'
          )
          ->addOption(
            'no-clean',
            null,
            InputOption::VALUE_NONE,
            'Do not remove old builds'
          )
          ->addOption(
            'no-archive',
            null,
            InputOption::VALUE_NONE,
            'Do not create or use a build archive'
          )
          ->addOption(
            'no-cache',
            null,
            InputOption::VALUE_NONE,
            'Disable caching'
          )
          ->addOption(
            'no-build-hooks',
            null,
            InputOption::VALUE_NONE,
            'Do not run post-build hooks'
          )
          ->addOption(
            'working-copy',
            null,
            InputOption::VALUE_NONE,
            'Drush: use git to clone a repository of each Drupal module rather than simply downloading a version'
          )
          ->addOption(
            'concurrency',
            null,
            InputOption::VALUE_OPTIONAL,
            'Drush: set the number of concurrent projects that will be processed at the same time',
            $this->defaultDrushConcurrency
          )
          ->addOption(
            'lock',
            null,
            InputOption::VALUE_NONE,
            'Drush: create or update a lock file (only available with Drush version 7+)'
          );
        $this->addExample('Build the current project');
        $this->addExample('Build the app "example" without symlinking the source files', 'example --copy');
        $this->addExample('Rebuild the current project without using an archive', '--no-archive');
    }

    public function isLocal()
    {
        return true;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $projectRoot = $this->getProjectRoot();

        /** @var \Platformsh\Cli\Helper\PlatformQuestionHelper $questionHelper */
        $questionHelper = $this->getHelper('question');

        $sourceDirOption = $input->getOption('source');

        // If no project root is found, ask the user for a source directory.
        if (!$projectRoot && !$sourceDirOption && $input->isInteractive()) {
            $sourceDirOption = $questionHelper->askInput('Source directory', $input, $this->stdErr);
        }

        if ($sourceDirOption) {
            $sourceDir = realpath($sourceDirOption);
            if (!is_dir($sourceDir)) {
                throw new \InvalidArgumentException('Source directory not found: ' . $sourceDirOption);
            }
            // Sensible handling if the user provides a project root as the
            // source directory.
            elseif (file_exists($sourceDir . '/.platform-project')) {
                $projectRoot = $sourceDir;
                $sourceDir = $projectRoot . '/' . LocalProject::REPOSITORY_DIR;
            }
        }
        elseif (!$projectRoot) {
            throw new RootNotFoundException('Project root not found. Specify --source or go to a project directory.');
        }
        else {
            $sourceDir = $projectRoot . '/' . LocalProject::REPOSITORY_DIR;
        }

        $destination = $input->getOption('destination');

        // If no project root is found, ask the user for a destination path.
        if (!$projectRoot && !$destination && $input->isInteractive()) {
            $destination = $questionHelper->askInput('Build destination', $input, $this->stdErr);
        }

        if ($destination) {
            /** @var \Platformsh\Cli\Helper\FilesystemHelper $fsHelper */
            $fsHelper = $this->getHelper('fs');
            $destination = $fsHelper->makePathAbsolute($destination);
        }
        elseif (!$projectRoot) {
            throw new RootNotFoundException('Project root not found. Specify --destination or go to a project directory.');
        }
        else {
            $destination = $projectRoot . '/' . LocalProject::WEB_ROOT;
        }

        // Ensure no conflicts between source and destination.
        if (strpos($sourceDir, $destination) === 0) {
            throw new \InvalidArgumentException("The destination '$destination' conflicts with the source '$sourceDir'");
        }

        // Ask the user about overwriting the destination, if a project root was
        // not found.
        if (!$projectRoot && file_exists($destination)) {
            if (!is_writable($destination)) {
                $this->stdErr->writeln("The destination exists and is not writable: <error>$destination</error>");
                return 1;
            }
            $default = is_link($destination);
            if (!$questionHelper->confirm("The destination exists: <comment>$destination</comment>. Overwrite?", $input, $this->stdErr, $default)) {
                return 1;
            }
        }

        $settings = array();

        $settings['projectRoot'] = $projectRoot;

        $settings['environmentId'] = $this->determineEnvironmentId($sourceDir, $projectRoot);

        $settings['verbosity'] = $output->getVerbosity();

        $settings['drushConcurrency'] = $input->hasOption('concurrency') ? $input->getOption('concurrency') : $this->defaultDrushConcurrency;

        // Some simple settings flags.
        $settingsMap = array(
          'absoluteLinks' => 'abslinks',
          'copy' => 'copy',
          'drushWorkingCopy' => 'working-copy',
          'drushUpdateLock' => 'lock',
          'noArchive' => 'no-archive',
          'noCache' => 'no-cache',
          'noClean' => 'no-clean',
          'noBuildHooks' => 'no-build-hooks',
        );
        foreach ($settingsMap as $setting => $option) {
            $settings[$setting] = $input->hasOption($option) && $input->getOption($option);
        }

        $apps = $input->getArgument('app');

        $builder = new LocalBuild($settings, $this->stdErr);
        $success = $builder->build($sourceDir, $destination, $apps);

        return $success ? 0 : 1;
    }

    /**
     * Find out the environment ID, if possible.
     *
     * This is appended to the build directory name.
     *
     * @param string $sourceDir
     * @param string|false $projectRoot
     *
     * @return string|false
     */
    protected function determineEnvironmentId($sourceDir, $projectRoot = null)
    {
        // Find out the real environment ID, if possible.
        if ($projectRoot && $this->isLoggedIn()) {
            try {
                $project = $this->getCurrentProject();
            }
            catch (\Exception $e) {
                // An exception may be thrown if the user no longer has access
                // to the project, or perhaps if there is no network access. We
                // can still let the user build the project locally.
                $project = false;
            }
            if ($project && ($environment = $this->getCurrentEnvironment($project))) {
                return $environment['id'];
            }
        }

        // Fall back to the Git branch name.
        if (is_dir($sourceDir . '/.git')) {
            /** @var \Platformsh\Cli\Helper\GitHelper $gitHelper */
            $gitHelper = $this->getHelper('git');
            return $gitHelper->getCurrentBranch($sourceDir);
        }

        return false;
    }
}


text:
set -e
pushd bootstrap-3.2.0
grunt dist
cp dist/css/bootstrap.min.css ../css/
popd

redpajama_set_name: RedPajamaGithub


text:
            {% if not termination and perms.circuits.add_circuittermination %}

                     Add

            {% endif %}
            {% if termination and perms.circuits.change_circuittermination %}

                     Edit

                     Swap

            {% endif %}
            {% if termination and perms.circuits.delete_circuittermination %}

                     Delete

            {% endif %}

        Termination - {{ side }} Side

    {% if termination %}

                Site

                    {% if termination.site.region %}
                        {{ termination.site.region }}

                    {% endif %}
                    {{ termination.site }}

                Termination

                    {% if termination.interface %}
                        {{ termination.interface.device }}
                         {{ termination.interface }}
                    {% else %}
                        Not defined
                    {% endif %}

                Speed

                    {% if termination.upstream_speed %}
                         {{ termination.port_speed_human }}
                         {{ termination.upstream_speed_human }}
                    {% else %}
                        {{ termination.port_speed_human }}
                    {% endif %}

                IP Addressing

                    {% if termination.interface %}
                        {% for ip in termination.interface.ip_addresses.all %}
                            {% if not forloop.first %}
{% endif %}
                            {{ ip }} ({{ ip.vrf|default:"Global" }})
                        {% empty %}
                            None
                        {% endfor %}
                    {% else %}
                        N/A
                    {% endif %}

                Cross-Connect

                    {% if termination.xconnect_id %}
                        {{ termination.xconnect_id }}
                    {% else %}
                        N/A
                    {% endif %}

                Patch Panel/Port

                    {% if termination.pp_info %}
                        {{ termination.pp_info }}
                    {% else %}
                        N/A
                    {% endif %}

    {% else %}

            None

    {% endif %}


text:
'use strict'

var yeoman = require('yeoman-generator')
var chalk = require('chalk')
var yosay = require('yosay')

module.exports = yeoman.Base.extend({
  prompting: function () {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the wicked ' + chalk.green('generator-george-sails') + ' generator!'
    ))

    var prompts = [
      // {
      //   type: 'input',
      //   name: 'user',
      //   message: 'What is the name of your component',
      //   default: 'User'
      // }
    ]

    return this.prompt(prompts).then(function (props) {
      this.props = props
    }.bind(this))
  },

  app: function () {
    // Server file
    // purdy(this.props)
    // this.fs.copyTpl(
    //   this.templatePath('server.js'),
    //   this.destinationPath('server.js'),
    //   this.destinationPath('/views/index.ejs'), {
    //     name: this.props.name
    //   }
    // )
  },

  // Writing Logic here
  writing: {
    // Copy the configuration files
    config: function () {
      // this.fs.copyTpl(
      //     this.templatePath('_package.json'),
      //     this.destinationPath('package.json'), {
      //         name: this.props.name
      //     }
      // )
      // this.fs.copyTpl(
      //     this.templatePath('_bower.json'),
      //     this.destinationPath('bower.json'), {
      //         name: this.props.name
      //     }
      // )
      this.fs.copy(
        this.templatePath('pre-commit.sh'),
        this.destinationPath('.git/hooks/pre-commit')
      )
    }

    // Copy application files

    // Install Dependencies
  },

  install: function () {
    // this.installDependencies()
  }
})


text:
.class public final Lcom/android/server/LightsService$Light;
.super Ljava/lang/Object;
.source "LightsService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/LightsService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x11
    name = "Light"
.end annotation

# instance fields
.field private mColor:I

.field private mFlashing:Z

.field private mId:I

.field private mMode:I

.field private mOffMS:I

.field private mOnMS:I

.field final synthetic this$0:Lcom/android/server/LightsService;

# direct methods
.method private constructor <init>(Lcom/android/server/LightsService;I)V
    .locals 0
    .parameter
    .parameter "id"

    .prologue
    .line 63
    iput-object p1, p0, Lcom/android/server/LightsService$Light;->this$0:Lcom/android/server/LightsService;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 64
    iput p2, p0, Lcom/android/server/LightsService$Light;->mId:I

    .line 65
    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/LightsService;ILcom/android/server/LightsService$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"

    .prologue
    .line 61
    invoke-direct {p0, p1, p2}, Lcom/android/server/LightsService$Light;-><init>(Lcom/android/server/LightsService;I)V

    return-void
.end method

.method static synthetic access$500(Lcom/android/server/LightsService$Light;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 61
    invoke-direct {p0}, Lcom/android/server/LightsService$Light;->stopFlashing()V

    return-void
.end method

.method private setLightLocked(IIIII)V
    .locals 8
    .parameter "color"
    .parameter "mode"
    .parameter "onMS"
    .parameter "offMS"
    .parameter "brightnessMode"

    .prologue
    const/4 v7, 0x0

    .line 118
    iget-object v0, p0, Lcom/android/server/LightsService$Light;->this$0:Lcom/android/server/LightsService;

    #getter for: Lcom/android/server/LightsService;->mContext:Landroid/content/Context;
    invoke-static {v0}, Lcom/android/server/LightsService;->access$100(Lcom/android/server/LightsService;)Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    const-string v1, "button_light_off"

    invoke-static {v0, v1, v7}, Landroid/provider/Settings$System;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I

    move-result v0

    if-eqz v0, :cond_0

    const/4 v7, 0x1

    .line 121
    .local v7, value:Z
    :cond_0
    iget v0, p0, Lcom/android/server/LightsService$Light;->mId:I

    const/4 v1, 0x2

    if-ne v0, v1, :cond_2

    if-eqz v7, :cond_2

    .line 134
    :cond_1
    :goto_0
    return-void

    .line 125
    :cond_2
    iget v0, p0, Lcom/android/server/LightsService$Light;->mColor:I

    if-ne p1, v0, :cond_3

    iget v0, p0, Lcom/android/server/LightsService$Light;->mMode:I

    if-ne p2, v0, :cond_3

    iget v0, p0, Lcom/android/server/LightsService$Light;->mOnMS:I

    if-ne p3, v0, :cond_3

    iget v0, p0, Lcom/android/server/LightsService$Light;->mOffMS:I

    if-eq p4, v0, :cond_1

    .line 128
    :cond_3
    iput p1, p0, Lcom/android/server/LightsService$Light;->mColor:I

    .line 129
    iput p2, p0, Lcom/android/server/LightsService$Light;->mMode:I

    .line 130
    iput p3, p0, Lcom/android/server/LightsService$Light;->mOnMS:I

    .line 131
    iput p4, p0, Lcom/android/server/LightsService$Light;->mOffMS:I

    .line 132
    iget-object v0, p0, Lcom/android/server/LightsService$Light;->this$0:Lcom/android/server/LightsService;

    #getter for: Lcom/android/server/LightsService;->mNativePointer:I
    invoke-static {v0}, Lcom/android/server/LightsService;->access$200(Lcom/android/server/LightsService;)I

    move-result v0

    iget v1, p0, Lcom/android/server/LightsService$Light;->mId:I

    move v2, p1

    move v3, p2

    move v4, p3

    move v5, p4

    move v6, p5

    #calls: Lcom/android/server/LightsService;->setLight_native(IIIIIII)V
    invoke-static/range {v0 .. v6}, Lcom/android/server/LightsService;->access$300(IIIIIII)V

    goto :goto_0
.end method

.method private stopFlashing()V
    .locals 6

    .prologue
    .line 112
    monitor-enter p0

    .line 113
    :try_start_0
    iget v1, p0, Lcom/android/server/LightsService$Light;->mColor:I

    const/4 v2, 0x0

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    move-object v0, p0

    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 114
    monitor-exit p0

    .line 115
    return-void

    .line 114
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

# virtual methods
.method public pulse()V
    .locals 2

    .prologue
    .line 93
    const v0, 0xffffff

    const/4 v1, 0x7

    invoke-virtual {p0, v0, v1}, Lcom/android/server/LightsService$Light;->pulse(II)V

    .line 94
    return-void
.end method

.method public pulse(II)V
    .locals 6
    .parameter "color"
    .parameter "onMS"

    .prologue
    .line 97
    monitor-enter p0

    .line 98
    :try_start_0
    iget v0, p0, Lcom/android/server/LightsService$Light;->mColor:I

    if-nez v0, :cond_0

    iget-boolean v0, p0, Lcom/android/server/LightsService$Light;->mFlashing:Z

    if-nez v0, :cond_0

    .line 99
    const/4 v2, 0x2

    const/16 v4, 0x3e8

    const/4 v5, 0x0

    move-object v0, p0

    move v1, p1

    move v3, p2

    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 100
    iget-object v0, p0, Lcom/android/server/LightsService$Light;->this$0:Lcom/android/server/LightsService;

    #getter for: Lcom/android/server/LightsService;->mH:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/server/LightsService;->access$000(Lcom/android/server/LightsService;)Landroid/os/Handler;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/LightsService$Light;->this$0:Lcom/android/server/LightsService;

    #getter for: Lcom/android/server/LightsService;->mH:Landroid/os/Handler;
    invoke-static {v1}, Lcom/android/server/LightsService;->access$000(Lcom/android/server/LightsService;)Landroid/os/Handler;

    move-result-object v1

    const/4 v2, 0x1

    invoke-static {v1, v2, p0}, Landroid/os/Message;->obtain(Landroid/os/Handler;ILjava/lang/Object;)Landroid/os/Message;

    move-result-object v1

    int-to-long v2, p2

    invoke-virtual {v0, v1, v2, v3}, Landroid/os/Handler;->sendMessageDelayed(Landroid/os/Message;J)Z

    .line 102
    :cond_0
    monitor-exit p0

    .line 103
    return-void

    .line 102
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public setBrightness(I)V
    .locals 1
    .parameter "brightness"

    .prologue
    .line 68
    const/4 v0, 0x0

    invoke-virtual {p0, p1, v0}, Lcom/android/server/LightsService$Light;->setBrightness(II)V

    .line 69
    return-void
.end method

.method public setBrightness(II)V
    .locals 6
    .parameter "brightness"
    .parameter "brightnessMode"

    .prologue
    .line 72
    monitor-enter p0

    .line 73
    and-int/lit16 v1, p1, 0xff

    .line 74
    .local v1, color:I
    const/high16 v0, -0x100

    shl-int/lit8 v2, v1, 0x10

    or-int/2addr v0, v2

    shl-int/lit8 v2, v1, 0x8

    or-int/2addr v0, v2

    or-int/2addr v1, v0

    .line 75
    const/4 v2, 0x0

    const/4 v3, 0x0

    const/4 v4, 0x0

    move-object v0, p0

    move v5, p2

    :try_start_0
    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 76
    monitor-exit p0

    .line 77
    return-void

    .line 76
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public setColor(I)V
    .locals 6
    .parameter "color"

    .prologue
    .line 80
    monitor-enter p0

    .line 81
    const/4 v2, 0x0

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    move-object v0, p0

    move v1, p1

    :try_start_0
    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 82
    monitor-exit p0

    .line 83
    return-void

    .line 82
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public setFlashing(IIII)V
    .locals 6
    .parameter "color"
    .parameter "mode"
    .parameter "onMS"
    .parameter "offMS"

    .prologue
    .line 86
    monitor-enter p0

    .line 87
    const/4 v5, 0x0

    move-object v0, p0

    move v1, p1

    move v2, p2

    move v3, p3

    move v4, p4

    :try_start_0
    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 88
    monitor-exit p0

    .line 89
    return-void

    .line 88
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public turnOff()V
    .locals 6

    .prologue
    .line 106
    monitor-enter p0

    .line 107
    const/4 v1, 0x0

    const/4 v2, 0x0

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    move-object v0, p0

    :try_start_0
    invoke-direct/range {v0 .. v5}, Lcom/android/server/LightsService$Light;->setLightLocked(IIIII)V

    .line 108
    monitor-exit p0

    .line 109
    return-void

    .line 108
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method


text:
<?php

require_once(dirname(__FILE__).'/sfPropelBaseTask.class.php');

/**
 * Delete all generated files associated with a Propel model. Forms, filters, etc.
 *
 * @package    symfony
 * @subpackage propel
 * @author     Jonathan H. Wage <jonwage@gmail.com>
 * @version    SVN: $Id: sfPropelDeleteModelFilesTask.class.php 29677 2010-05-30 14:19:33Z Kris.Wallsmith $
 */
class sfPropelDeleteModelFilesTask extends sfPropelBaseTask
{
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('name', sfCommandArgument::REQUIRED | sfCommandArgument::IS_ARRAY, 'The name of the model you wish to delete all related files for.'),
    ));

    $this->addOptions(array(
      new sfCommandOption('no-confirmation', null, sfCommandOption::PARAMETER_NONE, 'Do not ask for confirmation'),
      new sfCommandOption('prefix', null, sfCommandOption::PARAMETER_REQUIRED | sfCommandOption::IS_ARRAY, 'Class prefix to remove'),
      new sfCommandOption('suffix', null, sfCommandOption::PARAMETER_REQUIRED | sfCommandOption::IS_ARRAY, 'Class suffix to remove'),
      new sfCommandOption('extension', null, sfCommandOption::PARAMETER_REQUIRED | sfCommandOption::IS_ARRAY, 'Filename extension to remove'),
    ));

    $this->namespace = 'propel';
    $this->name = 'delete-model-files';
    $this->briefDescription = 'Delete all the related auto generated files for a given model name.';

    $this->detailedDescription = <<<EOF
The [propel:delete-model-files|INFO] task deletes all files associated with certain
models:

  [./symfony propel:delete-model-files Article Author|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $paths = array_merge(
      array(
        sfConfig::get('sf_lib_dir').'/model/propel',
        sfConfig::get('sf_lib_dir').'/form/propel',
        sfConfig::get('sf_lib_dir').'/filter/propel',
      ),
      $this->configuration->getPluginSubPaths('/lib/model/propel'),
      $this->configuration->getPluginSubPaths('/lib/form/propel'),
      $this->configuration->getPluginSubPaths('/lib/filter/propel')
    );

    $prefixPattern    = $this->valuesToRegex($options['prefix'] ? $options['prefix'] : array('', 'Base', 'Plugin'));
    $suffixPattern    = $this->valuesToRegex($options['suffix'] ? $options['suffix'] : array('', 'Table', 'Form', 'FormFilter'));
    $extensionPattern = $this->valuesToRegex($options['extension'] ? $options['extension'] : array('.php', '.class.php'));

    $total = 0;

    foreach ($arguments['name'] as $modelName)
    {
      $finder = sfFinder::type('file')->name('/^'.$prefixPattern.$modelName.$suffixPattern.$extensionPattern.'$/');
      $files = $finder->in($paths);

      if ($files)
      {
        if (!$options['no-confirmation'] && !$this->askConfirmation(array_merge(
          array('The following '.$modelName.' files will be deleted:', ''),
          array_map(create_function('$v', 'return \' - \'.sfDebug::shortenFilePath($v);'), $files),
          array('', 'Continue? (y/N)')
        ), 'QUESTION_LARGE', false))
        {
          $this->logSection('propel', 'Aborting delete of "'.$modelName.'" files');
          continue;
        }

        $this->logSection('propel', 'Deleting "'.$modelName.'" files');
        $this->getFilesystem()->remove($files);

        $total += count($files);
      }
      else
      {
        $this->logSection('propel', 'No files found for the model named "'.$modelName.'"');
      }
    }

    $this->logSection('propel', 'Deleted a total of '.$total.' file(s)');
  }

  /**
   * Converts an array of values to a regular expression pattern fragment.
   *
   * @param array  $values    An array of values for the pattern
   * @param string $delimiter The regular expression delimiter
   *
   * @return string A regular expression fragment
   */
  protected function valuesToRegex($values, $delimiter = '/')
  {
    if (false !== $pos = array_search('', $values))
    {
      $required = false;
      unset($values[$pos]);
    }
    else
    {
      $required = true;
    }

    if (count($values))
    {
      $regex = '(';
      foreach ($values as $i => $value)
      {
        $regex .= preg_quote($value, $delimiter);
        if (isset($values[$i + 1]))
        {
          $regex .= '|';
        }
      }
      $regex .= ')';

      if (!$required)
      {
        $regex .= '?';
      }

      return $regex;
    }
  }
}


text:
vBulletin версии 3.8.4 некорректно работает с интерпретатором php 5.3 и выше. В error_log попадает бесчетное количество бессмысленных deprecated warning'ов, что заставляет его моментально разрастаться.

# Решение
Данный скрипт позволяет в автоматическом режиме исправить некоторые проблемы vBulletin 3.8.4, проанализировав все входящие в дистрибутив php файлы и сделав автозамену устранить их. Пока что поддерживается только решение **Assigning the return value of new by reference is deprecated**.

Поиск ведется как в php файлах проекта, так и в коде модулей в mysql из таблицы **plugin**. Настройки подключения скрипт подхватит автоматически, если встретит валидный config.php от vBulletin. В случае, если такого конфига найдено не было, изменения в базе данных производиться не будут.

Использование скрипта осуществляется исключительно на свой страх и риск. Решение тестировалось на одном проекте, но нет никаких гарантий, что скрипт не поломает другой проект при бездумном использовании.

# Установка
Для работы скрипта необходим интерпретатор python версии 2.7. Вероятно он так же будет работать на третьей ветке, либо при минимальных правках, однако работа в третьей ветке не тестировалась.

Для ubuntu потребуется пакет `python-dev`, а так же пакет с хидерами mysqlclient: `libmysqlclient-dev` в ubuntu или `libmariadbclient` в ArchLinux.

Перед началом работы потребуется установить пакеты с зависимостями. Сделать это проще простого, поможет команда `pip install -r requirements.txt`

Сделать это можно либо под рутом, установив пакеты в основную систему (Не очень хорошее решение), либо используя [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/).

В целом процесс развертывания и использования скрипта выглядит примерно следующим образом:
```
ubuntu@domain:~$ cd /tmp
ubuntu@domain:/tmp$ git clone https://github.com/dumpedc/vbfixer.git
ubuntu@domain:/tmp$ cd vbfixer
ubuntu@domain:/tmp/vbfixer$ virtualenv env
ubuntu@domain:/tmp/vbfixer$ source env/bin/activate
(env)ubuntu@domain:/tmp/vbfixer$ pip install -r requirements.txt
(env)ubuntu@domain:/tmp/vbfixer$ python vbfixer.py /sites/domain.tld/public/
```
Где `/sites/domain.tld/public` - путь до вашей установки vBulletin.

# Использование
```
Usage: python vbfixer.py [OPTIONS] PATH

Options:
  -v                        Расширенный вывод
  -c TEXT                   Кодировка файлов. Если не указана, будет
                            определена через libmagic
  -s                        "Тихий" режим. Все замены будут произведены
                            автоматически. В каталогах будут созданы patch-
                            файлы с аналогичными именами
  -i [assign_by_reference]  Включает только конкретные проверки из заданного
                            списка
  --no-mysql                Не проверять модули в базе данных
  --help                    Show this message and exit.

```
По умолчанию скрипт запускается в интерактивном режиме, запрашивая подтверждение на каждое изменение.

Ключ `-s` включает "тихий" режим, производящий автоматические замены, но при этом оставляя рядом unix patch-файлы с описанием проделанных изменений, что позволяет быстро откатить нежелательные.

Ключ `--no-mysql` позволяет запустить скрипт без проверки модулей из таблицы plugin в базе данных, даже в том случае,е сли будет обнаружен валидный config.php.

`PATH` может быть как конкретным файлом (Например `python vbfixer.py /tmp/vbulletin/includes/init.php`), так и каталогом (Например `python vbfixer.py /tmp/vbulletin`).

В случае каталога скрипт будет осуществлять рекурсивный поиск во всех файлах с расширением `.php` внутри каталога.

# На будещее
Убедиться, что изменения поля phpcode в таблице plugin работает корректно.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.myrobotlab.service.PID</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.myrobotlab.service.PID

Packages that use PID

Package
Description

org.myrobotlab.control

org.myrobotlab.service

Uses of PID in org.myrobotlab.control

Methods in org.myrobotlab.control with parameters of type PID

Modifier and Type
Method and Description

void
PIDGUI.getState(PID pid)

Uses of PID in org.myrobotlab.service

Fields in org.myrobotlab.service declared as PID

Modifier and Type
Field and Description

PID
Sweety.pid

PID
InMoov.pid

PID
Tracking.xpid

PID
Tracking.ypid

Methods in org.myrobotlab.service that return PID

Modifier and Type
Method and Description

PID
Tracking.getXPID()

PID
Tracking.getYPID()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.juniversal.translator.core;

import org.eclipse.jdt.core.dom.*;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class ASTUtil {

    public static void parseJava(List<File> javaProjectDirectories) {

		/*
        ArrayList<File> files = new ArrayList<File>();
		for (File javaProjectDirectory : javaProjectDirectories)
			Util.getFilesRecursive(javaProjectDirectory, ".java", files);

		ArrayList<String> filePathsList = new ArrayList<String>();
		for (File file : files) {
			filePathsList.add(file.getPath());
		}

		String[] filePaths = filePathsList.toArray(new String[filePathsList.size()]);

		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);

		parser.createASTs(filePaths, encodings, bindingKeys, requestor, monitor)

		String source = readFile(args[0]);
		parser.setSource(source.toCharArray());

		CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null /xx* IProgressMonitor *xx/);

		TypeDeclaration typeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);

		StringWriter writer = new StringWriter();
		CPPProfile profile = new CPPProfile();
		// profile.setTabStop(4);

		CPPWriter cppWriter = new CPPWriter(writer, profile);

		Context context = new Context((CompilationUnit) compilationUnit.getRoot(), source, 8, profile, cppWriter,
				OutputType.SOURCE);

		context.setPosition(typeDeclaration.getStartPosition());

		ASTWriters astWriters = new ASTWriters();

		try {
			context.setPosition(typeDeclaration.getStartPosition());
			skipSpaceAndComments();

			astWriters.writeNode(typeDeclaration, context);
		} catch (UserViewableException e) {
			System.err.println(e.getMessage());
			System.exit(1);
		} catch (RuntimeException e) {
			if (e instanceof ContextPositionMismatchException)
				throw e;
			else
				throw new JUniversalException(e.getMessage() + "\nError occurred with context at position\n"
						+ context.getPositionDescription(context.getPosition()), e);
		}

		String cppOutput = writer.getBuffer().toString();

		System.out.println("Output:");
		System.out.println(cppOutput);
		*/

    }

    public static TypeDeclaration getFirstTypeDeclaration(CompilationUnit compilationUnit) {
        return (TypeDeclaration) compilationUnit.types().get(0);
    }

    public static Block getFirstMethodBlock(CompilationUnit compilationUnit) {
        return getFirstTypeDeclaration(compilationUnit).getMethods()[0].getBody();
    }

    /**
     * Return true is the specified modifier is an @Nullable annotation.   Currently we don't care about, nor even
     * support, fully qualified names for the @Nullable annotation.   Any non-qualified name that's @Nullable counts
     * here, but fully names currently never do currently.   The intention is that the programmer can pick between
     * several different @Nullable annotations, though JSimple code currently uses the IntelliJ one.
     *
     * @param extendedModifier modifier in question
     * @return true if modifier is an annotation for @Nullable, false otherwise
     */
    public static boolean isNullable(IExtendedModifier extendedModifier) {
        if (!(extendedModifier instanceof MarkerAnnotation))
            return false;

        Name typeName = ((MarkerAnnotation) extendedModifier).getTypeName();
        return typeName.isSimpleName() && ((SimpleName) typeName).getIdentifier().equals("Nullable");
    }

    /**
     * Return true is the specified modifier is an @Nullable annotation.   Currently we don't care about, nor even
     * support, fully qualified names for the @Nullable annotation.   Any non-qualified name that's @Nullable counts
     * here, but fully qualified names currently never do currently.   The intention is that the programmer can pick
     * between several different @Nullable annotations, though JSimple code currently uses the IntelliJ one.
     *
     * @param extendedModifier modifier in question
     * @return true if modifier is an annotation for @Nullable, false otherwise
     */
    public static boolean isFunctionalInterface(IExtendedModifier extendedModifier) {
        if (!(extendedModifier instanceof MarkerAnnotation))
            return false;

        Name typeName = ((MarkerAnnotation) extendedModifier).getTypeName();
        return typeName.isSimpleName() && ((SimpleName) typeName).getIdentifier().equals("FunctionalInterface");
    }

    /**
     * Return true is the specified modifier is "final".
     *
     * @param extendedModifier modifier in question
     * @return true if modifier is "final"
     */
    public static boolean isFinal(IExtendedModifier extendedModifier) {
        return extendedModifier instanceof Modifier && ((Modifier) extendedModifier).isFinal();
    }

    /**
     * Return true is the specified modifier is "final".
     *
     * @param extendedModifier modifier in question
     * @return true if modifier is "final"
     */
    public static boolean isAnnotation(IExtendedModifier extendedModifier) {
        return extendedModifier instanceof Annotation;
    }

    /**
     * Returns true if the list of extended modifiers (modifiers & annotations) includes "final".
     *
     * @param extendedModifiers extended modifiers to check
     * @return true if and only if list contains "final"
     */
    public static boolean containsFinal(List<?> extendedModifiers) {
        for (Object extendedModifierObject : extendedModifiers) {
            if (isFinal((IExtendedModifier) extendedModifierObject))
                return true;
        }
        return false;
    }

    /**
     * Returns true if the list of extended modifiers (modifiers & annotations) includes "static".
     *
     * @param extendedModifiers extended modifiers to check
     * @return true if and only if list contains "static"
     */
    public static boolean containsStatic(List extendedModifiers) {
        for (Object extendedModifierObject : extendedModifiers) {
            IExtendedModifier extendedModifier = (IExtendedModifier) extendedModifierObject;
            if (extendedModifier.isModifier() && ((Modifier) extendedModifier).isStatic())
                return true;
        }
        return false;
    }

    /**
     * Returns true if the list of extended modifiers (modifiers & annotations) includes "abstract".
     *
     * @param extendedModifiers extended modifiers to check
     * @return true if and only if list contains "static"
     */
    public static boolean containsAbstract(List<?> extendedModifiers) {
        for (Object extendedModifierObject : extendedModifiers) {
            IExtendedModifier extendedModifier = (IExtendedModifier) extendedModifierObject;
            if (extendedModifier.isModifier() && ((Modifier) extendedModifier).isAbstract())
                return true;
        }
        return false;
    }

    /**
     * Determines the access modifier specified in list of modifiers. If no access modifier is specified, the default
     * access of Package is returned.
     *
     * @param extendedModifiers extended modifiers to check
     * @return AccessModifier specified or Package by default
     */
    public static AccessLevel getAccessModifier(List<?> extendedModifiers) {
        for (Object extendedModifierObject : extendedModifiers) {
            IExtendedModifier extendedModifier = (IExtendedModifier) extendedModifierObject;
            if (extendedModifier.isModifier()) {
                Modifier modifier = (Modifier) extendedModifier;
                if (modifier.isPublic())
                    return AccessLevel.PUBLIC;
                else if (modifier.isProtected())
                    return AccessLevel.PROTECTED;
                else if (modifier.isPrivate())
                    return AccessLevel.PRIVATE;
            }
        }

        return AccessLevel.PACKAGE;
    }

    public static boolean isFinal(BodyDeclaration bodyDeclaration) {
        return containsFinal(bodyDeclaration.modifiers());
    }

    public static boolean isAbstract(BodyDeclaration bodyDeclaration) {
        return containsAbstract(bodyDeclaration.modifiers());
    }

    public static boolean isStatic(BodyDeclaration bodyDeclaration) {
        return containsStatic(bodyDeclaration.modifiers());
    }

    public static boolean isPrivate(BodyDeclaration bodyDeclaration) {
        return getAccessModifier(bodyDeclaration.modifiers()) == AccessLevel.PRIVATE;
    }

    public static boolean isFinal(AbstractTypeDeclaration typeDeclaration) {
        // Enums are implicitly final
        return typeDeclaration instanceof EnumDeclaration || containsFinal(typeDeclaration.modifiers());
    }

    public static boolean isInterface(AbstractTypeDeclaration typeDeclaration) {
        return typeDeclaration instanceof TypeDeclaration && ((TypeDeclaration) typeDeclaration).isInterface();
    }

    public static boolean isAbstract(TypeDeclaration typeDeclaration) {
        return containsAbstract(typeDeclaration.modifiers());
    }

    public static boolean isConstructor(MethodDeclaration methodDeclaration) {
        return methodDeclaration.isConstructor();
    }

    public static boolean isStatic(IMethodBinding methodBinding) {
        return (methodBinding.getModifiers() & Modifier.STATIC) != 0;
    }

    public static boolean isType(Type type, String qualifiedTypeName) {
        return isType(type.resolveBinding(), qualifiedTypeName);
    }

    public static boolean isType(@Nullable ITypeBinding typeBinding, String qualifiedTypeName) {
        return typeBinding != null && typeBinding.getQualifiedName().equals(qualifiedTypeName);
    }

    public static boolean isThisMethod(MethodDeclaration methodDeclaration, String methodName, String... parameterTypes) {
        // If the method names don't match, it's not the specified method
        if (!methodDeclaration.getName().getIdentifier().equals(methodName))
            return false;

        // If the method parameter counts don't match, it's not the specified method
        if (methodDeclaration.parameters().size() != parameterTypes.length)
            return false;

        // Ensure each parameter has the expected type
        int index = 0;
        for (Object parameterObject : methodDeclaration.parameters()) {
            SingleVariableDeclaration parameter = (SingleVariableDeclaration) parameterObject;

            if (!isType(parameter.getType(), parameterTypes[index]))
                return false;

            ++index;
        }

        return true;
    }

    public static boolean isThisName(Name name, String nameString) {
        // Check first, in the case of a qualified name, whether the name string has a suffix that's the simple name
        // portion of the qualified name.   This check is just an optimization, so in the typical case where there is
        // no match it won't allocate a new object & build the full name string to compare
        if (name instanceof QualifiedName) {
            if (!nameString.endsWith(((QualifiedName) name).getName().getIdentifier()))
                return false;
        }

        return name.getFullyQualifiedName().equals(nameString);
    }

    public static boolean isArrayLengthField(FieldAccess fieldAccess) {
        if (!fieldAccess.getName().getIdentifier().equals("length"))
            return false;
        @Nullable IVariableBinding variableBinding = fieldAccess.resolveFieldBinding();
        return variableBinding != null && variableBinding.getType().isArray();
    }

    public static boolean isArrayLengthField(QualifiedName qualifiedName) {
        if (!qualifiedName.getName().getIdentifier().equals("length"))
            return false;
        @Nullable ITypeBinding binding = qualifiedName.getQualifier().resolveTypeBinding();
        return binding != null;
    }

    /**
     * Returns the position following the last character in the node; just a shortcut for adding the length to the start
     * position. Note that the end position may be (one) past the end of the source.
     *
     * @param node ASTNode in question
     * @return last position in the node + 1
     */
    public static int getEndPosition(ASTNode node) {
        return node.getStartPosition() + node.getLength();
    }

    /**
     * Returns the position following the last character in the last node in the list. Note that the end position may be
     * (one) past the end of the source.
     *
     * @param nodes list of nodes; each item in the list should actually be of a type that's a subclass of ASTNode
     * @return last position of the last node in the list + 1
     */
    public static int getEndPosition(List<?> nodes) {
        Object lastNodeObject = null;
        for (Object node : nodes)
            lastNodeObject = node;

        return getEndPosition((ASTNode) lastNodeObject);
    }

    public static @Nullable String qualifierFromQualifiedName(String qualifiedName) {
        int lastPeriodIndex = qualifiedName.lastIndexOf('.');
        if (lastPeriodIndex == -1)
            return null;
        else return qualifiedName.substring(0, lastPeriodIndex);
    }

    public static String simpleNameFromQualifiedName(String qualifiedName) {
        int lastPeriodIndex = qualifiedName.lastIndexOf('.');
        if (lastPeriodIndex == -1)
            return qualifiedName;
        else return qualifiedName.substring(lastPeriodIndex + 1);
    }

    public static boolean directlyImplementsInterface(ITypeBinding typeBinding, String desiredInterfaceQualifiedName) {
        for (ITypeBinding interfaceTypeBinding : typeBinding.getInterfaces()) {
            if (interfaceTypeBinding.getQualifiedName().equals(desiredInterfaceQualifiedName))
                return true;
        }

        return false;
    }

    public static boolean implementsInterface(ITypeBinding typeBinding, String interfaceQualifiedName) {
        while (typeBinding != null) {
            if (directlyImplementsInterface(typeBinding, interfaceQualifiedName))
                return true;
            typeBinding = typeBinding.getSuperclass();
        }

        return false;
    }

    public static boolean isFunctionalInterface(TypeDeclaration typeDeclaration) {
        return anyMatch(typeDeclaration.modifiers(),
                (IExtendedModifier extendedModifier) -> isFunctionalInterface(extendedModifier));
    }

/*
    public static boolean isFunctionalInterface(ITypeBinding typeBinding) {
        typeBinding.

        boolean hasAnnotation = false;
        for (Object extendedModifierObject : typeDeclaration.modifiers()) {
            IExtendedModifier extendedModifier = (IExtendedModifier) extendedModifierObject;
            if (isFunctionalInterface(extendedModifier)) {
                hasAnnotation = true;
                break;
            }
        }

        return hasAnnotation;
    }
*/

    public static boolean isNumericPrimitiveType(Type type) {
        if (!(type instanceof PrimitiveType))
            return false;

        PrimitiveType.Code code = ((PrimitiveType) type).getPrimitiveTypeCode();
        return code == PrimitiveType.BYTE || code == PrimitiveType.SHORT || code == PrimitiveType.INT ||
               code == PrimitiveType.LONG || code == PrimitiveType.FLOAT || code == PrimitiveType.DOUBLE;
    }

    public static boolean isGenericImport(ImportDeclaration importDeclaration) {
        @Nullable IBinding binding = importDeclaration.resolveBinding();
        return binding != null && binding instanceof ITypeBinding && ((ITypeBinding) binding).isGenericType();
    }

    public static boolean isFunctionalInterface(ITypeBinding typeBinding) {
        if (!typeBinding.isInterface())
            return false;

        int methodCount = typeBinding.getDeclaredMethods().length;
        if (methodCount != 1)
            return false;

        // See if the type has the FunctionalInterface annotation
        return anyMatch(typeBinding.getAnnotations(),
                (IAnnotationBinding annotationBinding) -> annotationBinding.getAnnotationType().getQualifiedName().equals("java.lang.FunctionalInterface"));

        // TODO: Ensure no default implementation (I think) nor constants defined for the interface
    }

    public static boolean isFunctionalInterfaceImplementation(SourceFileWriter sourceFileWriter, Type type) {
        return isFunctionalInterface(sourceFileWriter.resolveTypeBinding(type));
    }

    /**
     * Add all the wildcards referenced from a given type, searching recursively in the type definition to add all of
     * them.   That is, for a type like this:
     *

     * "Foo< Bar<? extends Fizz>, <Blip <? super Pop>>, ? >"
     *

     * 3 wildcard types would be added (<? extends Fizz>, <? super Pop>, and ?) since essentially the ? appears 3 times
     * the in the type definition above.
     *
     * @param type
     * @param wildcardTypes
     */
    public static void addWildcardTypes(Type type, ArrayList<WildcardType> wildcardTypes) {
        if (type.isParameterizedType()) {
            ParameterizedType parameterizedType = (ParameterizedType) type;

            forEach(parameterizedType.typeArguments(), (Type typeArgument) -> {
                addWildcardTypes(typeArgument, wildcardTypes);
            });
        } else if (type.isWildcardType()) {
            WildcardType wildcardType = (WildcardType) type;

            wildcardTypes.add(wildcardType);
            @Nullable Type bound = wildcardType.getBound();

            if (bound != null)
                addWildcardTypes(bound, wildcardTypes);
        }
    }

    /**
     * Checks if the cast expression is creating an array (which in Java can never be generic) and then turns around and
     * casts it to an array of a generic type.   In Java, which doesn't allow directly creating a generic array,
     * creating a non-generic array and casting is the the only way to create an array of generic type.   However, in
     * other languages, like C#, that don't do type erasure for generics you can create a generic array directly--and in
     * fact you have to if that's what you want to end up with.   This method helps us map from the Java way (cast) to
     * target language (create directly, with no cast).
     *
     * @param castExpression cast expression in question
     * @return true if the expression creates an array then casts it to a generic array
     */
    public static boolean isGenericArrayCreation(CastExpression castExpression) {
        if (!(castExpression.getExpression() instanceof ArrayCreation))
            return false;

        Type type = castExpression.getType();
        return type instanceof ArrayType && isGenericType(((ArrayType) type).getElementType());
    }

    /**
     * Returns true if the specified type is generic in any way (that is, it has generic parameters, like
     * ArrayList<E>, is a type variable itself, like E, or is an array of a generic type, like E[]).
     *
     * @param type type in question
     * @return true if it's a generic type
     */
    public static boolean isGenericType(Type type) {
        if (type instanceof ParameterizedType)
            return true;

        if (type instanceof ArrayType)
            return isGenericType(((ArrayType) type).getElementType());

        if (type instanceof SimpleType) {
            ITypeBinding typeBinding = type.resolveBinding();
            if (typeBinding != null && typeBinding.isTypeVariable())
                return true;
        }

        return false;
    }

    @FunctionalInterface
    public interface ConsumerWithFirst<T> {
        public void accept(T elmt, boolean first);
    }

    public static <T> boolean forEach(List list, Consumer<T> consumer) {
        boolean hasItem = false;
        for (Object elmtObject : list) {
            T elmt = (T) elmtObject;
            consumer.accept(elmt);
            hasItem = true;
        }
        return hasItem;
    }

    public static <T> boolean forEach(List list, ConsumerWithFirst<T> consumerWithFirst) {
        boolean first = true;
        for (Object elmtObject : list) {
            T elmt = (T) elmtObject;
            consumerWithFirst.accept(elmt, first);
            first = false;
        }
        return !first;
    }

    public static <T> boolean anyMatch(List list, Predicate<? super T> predicate) {
        for (Object elmtObject : list) {
            T elmt = (T) elmtObject;
            if (predicate.test(elmt))
                return true;
        }
        return false;
    }

    public static <T> boolean anyMatch(T[] array, Predicate<? super T> predicate) {
        for (T elmt : array) {
            if (predicate.test(elmt))
                return true;
        }
        return false;
    }

    public static boolean anyTypeOrAncestorMatch(ITypeBinding typeBinding, Predicate<? super ITypeBinding> predicate) {
        if (predicate.test(typeBinding))
            return true;

        return anyAncestorMatch(typeBinding, predicate);
    }

    public static boolean anyAncestorMatch(ITypeBinding typeBinding, Predicate<? super ITypeBinding> predicate) {
        ITypeBinding superClassTypeBinding = typeBinding.getSuperclass();
        if (superClassTypeBinding != null && anyTypeOrAncestorMatch(superClassTypeBinding, predicate))
            return true;

        for (ITypeBinding interfaceTypeBinding : typeBinding.getInterfaces()) {
            if (anyTypeOrAncestorMatch(interfaceTypeBinding, predicate))
                return true;
        }

        return false;
    }

    /**
     * Check all the superclasses (all the way up the tree) for the given type, seeing if any of them match the
     * specified predicate.   Note that the type itself isn't checked, just its superclasses.   Interfaces aren't
     * checked either; use anyAncestorInterfaceMatch for that.
     *
     * @param typeBinding type (normally a class)
     * @param predicate   predicate to test against
     * @return true if any superclass matches the specified test
     */
    public static boolean anySuperclassMatch(ITypeBinding typeBinding, Predicate<? super ITypeBinding> predicate) {
        // See if this method doesn't have the @Override annotation but actually is an override, by iterating through
        // all ancestor classes/interfaces and checking methods on each to see if this method overrides
        ITypeBinding superclass = typeBinding.getSuperclass();

        while (superclass != null) {
            if (predicate.test(superclass))
                return true;
            superclass = superclass.getSuperclass();
        }

        return false;
    }

    /**
     * Check all the ancestor interfaces of the given type, to see if any of them match the specified predicate.
     * Ancestor interfaces include super interfaces for a type & their super interfaces, all the way up the tree. Super
     * interfaces implemented by are are also included.   Note that superclasses themselves aren't tested (use
     * anySuperclassMatch for that), but all interfaces implemented by superclasses are tested.
     *
     * @param typeBinding type (normally a class) in question
     * @param predicate   predicate to test against
     * @return true if any superinterface matches the specified test
     */
    public static boolean anyAncestorInterfaceMatch(ITypeBinding typeBinding, Predicate<? super ITypeBinding> predicate) {
        // See if this method doesn't have the @Override annotation but actually is an override, by iterating through
        // all ancestor classes/interfaces and checking methods on each to see if this method overrides
        for (ITypeBinding interfaceBinding : typeBinding.getInterfaces()) {
            if (predicate.test(interfaceBinding))
                return true;

            if (anyAncestorMatch(interfaceBinding, predicate))
                return true;
        }

        return anySuperclassMatch(typeBinding, superclass -> anyAncestorInterfaceMatch(superclass, predicate));
    }

    public static BigInteger getIntegerLiteralValue(NumberLiteral numberLiteral) {
        // Get the literal token string, normalizing by removing any _ delimiter characters and converting to upper case
        String token = numberLiteral.getToken().replace("_", "").toUpperCase();

        // Strip off any integer type suffix at the end
        if (token.endsWith("L"))
            token = token.substring(0, token.length() - 1);

        if (token.startsWith("0X"))
            return new BigInteger(token.substring(2), 16);
        else if (token.startsWith("0B"))
            return new BigInteger(token.substring(2), 2);
        else if (token.startsWith("0") && !token.equals("0"))
            return new BigInteger(token.substring(1), 8);
        else return new BigInteger(token, 10);
    }
}


text:
need_module! 'url_handler', 'http'

require 'multi_json'

register 'Fetch information from YouTube.'

url /\/\/(youtu\.be\/.+|(www\.)?youtube\.com\/.+[?&]v=.+)/ do
  $log.info('youtube.url') { @uri.inspect }

  link, vid = '', ''

  if @uri.host == 'youtu.be' or @uri.host == 'www.youtu.be'
    vid = @uri.path[1..@uri.path.length-1].split("&")[0]
  else
    query = @uri.query.split('&').select {|a| a.start_with? 'v='}[0]

    next if query == nil

    vid = query.split('=')[1]

    link = " - https://youtu.be/#{vid}" if get_config(:shorten_links, false)
  end

  api = URI('https://www.googleapis.com/youtube/v3/videos')

  opts = {
    :id   => vid,
    :part => 'contentDetails,statistics,snippet',
    :key  => 'AIzaSyDyoH7a9ABi-QJ3f5qS1PsLZJbnxvzKvxc'
  }

  http_get(api, opts, true) do |http|
    json = MultiJson.load(http.response)['items'].first

    if json['error']
      raise json['error']['errors'].first['message']
    end

    duration  = json['contentDetails']['duration'].match(/^PT((?<minutes>[0-9]+)M)?((?<seconds>[0-9]+)S)?$/)
    duration  = duration[:minutes].to_i * 60 + duration[:seconds].to_i

    reply_without_prefix 'YouTube' => json['snippet']['title'],
      'By'       => json['snippet']['channelTitle'],
      'Views'    => json['statistics']['viewCount'],
      'Duration' => Time.at(Time.now.to_i + duration).to_duration_s,
      'Likes'    => json['statistics']['likeCount'],
      'Dislikes' => json['statistics']['dislikeCount']

  end

end

# vim: set tabstop=2 expandtab:


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;

using AjaxPro;

using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Common.Contracts;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.FederatedLogin;
using ASC.Geolocation;
using ASC.Web.Core;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.UserControls.Management.SingleSignOnSettings;
using ASC.Web.Studio.UserControls.Statistics;
using ASC.Web.Studio.Utility;

using PhoneNumbers;

namespace ASC.Web.Studio.UserControls.Management
{
    [AjaxNamespace("TariffSaasController")]
    public partial class TariffSaas : UserControl
    {
        public static string Location
        {
            get { return "~/UserControls/Management/TariffSettings/TariffSaas.ascx"; }
        }

        protected readonly int MinUsersCount = TariffService.ACTIVE_USERS_MIN;
        protected readonly int MaxUsersCount = TariffService.ACTIVE_USERS_MAX;
        protected readonly string SalesEmail = AdditionalWhiteLabelSettings.Instance.SalesEmail;
        protected readonly RegionInfo RegionDefault = new RegionInfo("US");

        protected readonly int CurrentUsersCount = TenantStatisticsProvider.GetUsersCount();
        protected readonly long CurrentUsedSize = TenantStatisticsProvider.GetUsedSize();
        protected readonly Tariff CurrentTariff = TenantExtra.GetCurrentTariff();
        protected readonly TenantQuota CurrentQuota = TenantExtra.GetTenantQuota();
        protected readonly Guid CurrentOwnerId = CoreContext.TenantManager.GetCurrentTenant().OwnerId;

        protected TenantQuota StartupQuota;
        protected TenantQuota MonthQuota;
        protected TenantQuota YearQuota;
        protected TenantQuota ThreeYearsQuota;

        protected bool IsStartup;
        protected bool IsTrial;
        protected bool IsBusiness;
        protected bool IsExpired;

        protected bool StartupEnabled;

        protected RegionInfo CurrentRegion;
        protected List<RegionInfo> Regions = new List<RegionInfo>();

        private IDictionary<string, Dictionary<string, decimal>> priceInfo;
        private IEnumerable<TenantQuota> quotaList;
        private ILog Log = LogManager.GetLogger("ASC.Web.Billing");

        protected bool IsAdmin;
        protected bool IsPeopleModuleAvailable;
        protected int ActiveUsersPercent;
        protected int StorageSpacePercent;

        protected void Page_Load(object sender, EventArgs e)
        {
            Page
                .RegisterBodyScripts(
                    "~/UserControls/Management/TariffSettings/js/tariffsaas.js"
                )
                .RegisterStyle(
                    "~/UserControls/Management/TariffSettings/css/tariff.less",
                    "~/UserControls/Management/TariffSettings/css/tariffsaas.less"
                );

            priceInfo = CoreContext.TenantManager.GetProductPriceInfo(false);
            quotaList = TenantExtra.GetTenantQuotas();

            InitRegionInfo();

            StartupQuota = GetStartupQuota();
            MonthQuota = GetMonthQuota();
            YearQuota = GetYearQuota();
            ThreeYearsQuota = GetThreeYearsQuota();

            IsStartup = CurrentQuota.Free;
            IsTrial = CurrentQuota.Trial;
            IsBusiness = !CurrentQuota.Free;
            IsExpired = CurrentTariff.DueDate.Date != DateTime.MaxValue.Date && CurrentTariff.State >= TariffState.NotPaid;

            StartupEnabled = CheckStartupEnabled(CurrentQuota, StartupQuota, out string _);

            IsAdmin = CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID);

            var peopleProduct = WebItemManager.Instance[WebItemManager.PeopleProductID];
            IsPeopleModuleAvailable = peopleProduct != null && !peopleProduct.IsDisabled();

            ActiveUsersPercent = 100 * CurrentUsersCount / CurrentQuota.ActiveUsers;
            StorageSpacePercent = (int)(100 * CurrentUsedSize / CurrentQuota.MaxTotalSize);

            AjaxPro.Utility.RegisterTypeForAjax(GetType());
        }

        private void InitRegionInfo()
        {
            Regions.Add(RegionDefault);

            CurrentRegion = GetRegionInfoByRequestCurrency() ?? FindRegionInfo() ?? RegionDefault;

            if (!CurrentRegion.Equals(RegionDefault))
            {
                if (priceInfo.Values.Any(value => value.ContainsKey(CurrentRegion.ISOCurrencySymbol)))
                {
                    Regions.Add(CurrentRegion);
                }
                else
                {
                    CurrentRegion = RegionDefault;
                }
            }
        }

        private RegionInfo GetRegionInfoByRequestCurrency()
        {
            RegionInfo regionInfo = null;

            var requestCurrency = Request["cur"];

            if (!string.IsNullOrEmpty(requestCurrency))
            {
                try
                {
                    regionInfo = new RegionInfo(requestCurrency);
                }
                catch
                {
                }
            }

            return regionInfo;
        }

        private RegionInfo FindRegionInfo()
        {
            RegionInfo regionInfo = null;

            var owner = CoreContext.UserManager.GetUsers(CurrentOwnerId);

            if (!string.IsNullOrEmpty(owner.MobilePhone))
            {
                try
                {
                    var phoneUtil = PhoneNumberUtil.GetInstance();
                    var number = phoneUtil.Parse("+" + owner.MobilePhone.TrimStart('+'), "en-US");
                    var regionCode = phoneUtil.GetRegionCodeForNumber(number);
                    if (!string.IsNullOrEmpty(regionCode))
                    {
                        try
                        {
                            regionInfo = new RegionInfo(regionCode);
                        }
                        catch
                        {
                        }
                    }
                }
                catch (Exception err)
                {
                    LogManager.GetLogger("ASC.Web.Tariff").WarnFormat("Can not find country by phone {0}: {1}", owner.MobilePhone, err);
                }
            }

            if (regionInfo == null)
            {
                var geoinfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext();
                if (!string.IsNullOrEmpty(geoinfo.Key))
                {
                    try
                    {
                        regionInfo = new RegionInfo(geoinfo.Key);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return regionInfo;
        }

        private bool CheckStartupEnabled(TenantQuota currentQuota, TenantQuota startupQuota, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (!currentQuota.Trial)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorTrial;
                return false;
            }

            if (TenantStatisticsProvider.GetUsersCount() > startupQuota.ActiveUsers)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorUsers, startupQuota.ActiveUsers);
                return false;
            }

            if (TenantStatisticsProvider.GetVisitorsCount() > 0)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorGuests, 0);
                return false;
            }

            var currentTenant = CoreContext.TenantManager.GetCurrentTenant();

            var admins = WebItemSecurity.GetProductAdministrators(Guid.Empty);

            if (admins.Any(admin => admin.ID != currentTenant.OwnerId))
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorAdmins, 1);
                return false;
            }

            if (TenantStatisticsProvider.GetUsedSize() > startupQuota.MaxTotalSize)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorStorage, FileSizeComment.FilesSizeToString(startupQuota.MaxTotalSize));
                return false;
            }

            var authServiceList = new AuthorizationKeys().AuthServiceList.Where(x => x.CanSet);

            foreach (var service in authServiceList)
            {
                if (service.Props.Any(r => !string.IsNullOrEmpty(r.Value)))
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorThirparty;
                    return false;
                }
            }

            if (!TenantWhiteLabelSettings.Load().IsDefault)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorWhiteLabel;
                return false;
            }

            if (!string.IsNullOrEmpty(currentTenant.MappedDomain))
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorDomain;
                return false;
            }

            var accountLinker = new AccountLinker("webstudio");

            foreach (var user in CoreContext.UserManager.GetUsers(EmployeeStatus.All))
            {
                var linkedAccounts = accountLinker.GetLinkedProfiles(user.ID.ToString());

                if (linkedAccounts.Any())
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorOauth;
                    return false;
                }
            }

            if (SsoSettingsV2.Load().EnableSso)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorSso;
                return false;
            }

            if (ActiveDirectory.Base.Settings.LdapSettings.Load().EnableLdapAuthentication)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorLdap;
                return false;
            }

            using (var service = new BackupServiceClient())
            {
                var scheduleResponse = service.GetSchedule(currentTenant.TenantId);

                if (scheduleResponse != null)
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorAutoBackup;
                    return false;
                }
            }

            return true;
        }

        private TenantQuota GetStartupQuota()
        {
            var startupQuota = CoreContext.TenantManager.GetTenantQuotas(true).FirstOrDefault(q => q.Free && !q.Open);

            if (startupQuota == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorStartupTariffNotFound);
            }

            return startupQuota;
        }

        private TenantQuota GetMonthQuota()
        {
            var monthQuota = quotaList.FirstOrDefault(q => !q.Year && !q.Year3 && !q.Trial && !q.Free && !q.Open);

            if (monthQuota == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorMonthTariffNotFound);
            }

            return monthQuota;
        }

        private TenantQuota GetYearQuota()
        {
            var yearQuota = quotaList.FirstOrDefault(q => q.Year && !q.Trial && !q.Free && !q.Open);

            if (yearQuota == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorYearTariffNotFound);
            }

            return yearQuota;
        }

        private TenantQuota GetThreeYearsQuota()
        {
            var threeYearsQuota = quotaList.FirstOrDefault(q => q.Year3 && !q.Trial && !q.Free && !q.Open);

            if (threeYearsQuota == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorThreeYearsTariffNotFound);
            }

            return threeYearsQuota;
        }

        protected Tuple<string, string, string> GetShoppingData(TenantQuota quota, string currency, int quantity)
        {
            var getLink = true;
            var buttonText = Resource.TariffButtonBuy;
            var infoText = string.Empty;

            var currentUsersCount = TenantStatisticsProvider.GetUsersCount();
            var currentVisitorsCount = TenantStatisticsProvider.GetVisitorsCount();
            var currentUsedSize = TenantStatisticsProvider.GetUsedSize();
            var currentTariff = TenantExtra.GetCurrentTariff();
            var currentQuota = TenantExtra.GetTenantQuota();
            var language = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            var customerId = CoreContext.TenantManager.GetCurrentTenant().OwnerId.ToString();

            var quotaActiveUsers = quota.ActiveUsers == -1 ? quantity : quota.ActiveUsers;
            var quotaMaxTotalSize = quota.ActiveUsers == -1 ? quota.MaxTotalSize * quantity : quota.MaxTotalSize;

            if (quotaActiveUsers < currentUsersCount
                || quotaMaxTotalSize < currentUsedSize
                || (!currentQuota.Free && (quotaActiveUsers * Constants.CoefficientOfVisitors) < currentVisitorsCount))
            {
                getLink = false;
            }
            else if (Equals(quota.Id, currentQuota.Id)
                && quantity == currentTariff.Quantity)
            {
                buttonText = Resource.TariffButtonExtend;
                if (!currentTariff.Prolongable)
                {
                    getLink = false;
                }
                else if (currentTariff.Autorenewal)
                {
                    getLink = false;
                    buttonText = Resource.TariffEnabledAutorenew;
                    infoText = Resource.TariffRemarkProlongEnable;
                }
            }
            else if (currentTariff.Prolongable)
            {
                buttonText = Resource.TariffButtonBuy;
                infoText = Resource.TariffRemarkProlongDisable;
            }
            else if (currentTariff.State == TariffState.Paid && quotaActiveUsers < currentQuota.ActiveUsers)
            {
                getLink = false;
                buttonText = Resource.TariffButtonBuy;
                infoText = currentQuota.Year3 ? Resource.TariffRemarkDisabledYear : Resource.TariffRemarkDisabledMonth;
            }

            var link = getLink ? GetShoppingLink(quota, currency, language, customerId, quantity) : string.Empty;

            return new Tuple<string, string, string>(buttonText, infoText, link);
        }

        private string GetShoppingLink(TenantQuota quota, string currency, string language, string customerId, int quantity)
        {
            var link = string.Empty;
            if (quota != null)
            {
                try
                {
                    var uri = CoreContext.PaymentManager.GetShoppingUri(quota.Id, true, null, currency, language, customerId, quantity.ToString());
                    if (uri == null)
                    {
                        var message = string.Format("GetShoppingLink: return null for tenant {0} quota {1} currency {2} language {3} customerId {4} quantity {5}", TenantProvider.CurrentTenantID, quota.Id, currency, language, customerId, quantity);
                        Log.Info(message);
                    }
                    else
                    {
                        link = uri.ToString();
                    }
                }
                catch (Exception ex)
                {
                    var message = string.Format("GetShoppingLink: {0} tenant {1} quota {2} currency {3} language {4} customerId {5} quantity {6}", ex.Message, TenantProvider.CurrentTenantID, quota.Id, currency, language, customerId, quantity);
                    Log.Info(message, ex);
                }
            }
            return link;
        }

        private static string GetPriceString(decimal price, RegionInfo region)
        {
            var inEuro = "EUR".Equals(region.ISOCurrencySymbol);

            var priceString = inEuro && Math.Truncate(price) != price
                                  ? price.ToString(CultureInfo.InvariantCulture)
                                  : ((int)price).ToString(CultureInfo.InvariantCulture);

            return string.Format("{0}{1}", region.CurrencySymbol, priceString);
        }

        protected string GetPricePerMonthString(TenantQuota quota)
        {
            var length = quota.Year3 ? 36 : quota.Year ? 12 : 1;

            if (!string.IsNullOrEmpty(quota.AvangateId) && priceInfo.ContainsKey(quota.AvangateId))
            {
                var prices = priceInfo[quota.AvangateId];
                if (prices.ContainsKey(CurrentRegion.ISOCurrencySymbol))
                {
                    return GetPriceString(prices[CurrentRegion.ISOCurrencySymbol] / length, CurrentRegion);
                }
                return GetPriceString(quota.Price / length, RegionDefault);
            }
            return GetPriceString(quota.Price / length, CurrentRegion);
        }

        protected decimal GetPrice(TenantQuota quota, RegionInfo region)
        {
            if (priceInfo == null)
            {
                priceInfo = CoreContext.TenantManager.GetProductPriceInfo(false);
            }

            if (!string.IsNullOrEmpty(quota.AvangateId) && priceInfo.ContainsKey(quota.AvangateId))
            {
                var prices = priceInfo[quota.AvangateId];
                if (prices.ContainsKey(region.ISOCurrencySymbol))
                {
                    return prices[region.ISOCurrencySymbol];
                }
            }
            return quota.Price;
        }

        [AjaxMethod]
        public TariffDetails GetTariffDetails(int quotaId, int usersCount, string regionName)
        {
            var quotas = TenantExtra.GetTenantQuotas();
            var selectedQuota = quotas.FirstOrDefault(q => q.Id == quotaId);
            var monthQuota = quotas.FirstOrDefault(q => !q.Year && !q.Year3 && !q.Trial && !q.Free && !q.Open);

            if (selectedQuota == null || monthQuota == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorTariffNotFound);
            }

            if (usersCount < TariffService.ACTIVE_USERS_MIN || usersCount > TariffService.ACTIVE_USERS_MAX)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorInvalidNumberOfActiveUsers);
            }

            RegionInfo region = null;

            try
            {
                region = new RegionInfo(regionName);
            }
            catch
            {
            }

            if (region == null)
            {
                throw new NotSupportedException(UserControlsCommonResource.SaasTariffErrorRegionNotFound);
            }

            var period = selectedQuota.Year3
                    ? UserControlsCommonResource.SaasTariffThreeYears
                    : selectedQuota.Year
                        ? UserControlsCommonResource.SaasTariffOneYear
                        : UserControlsCommonResource.SaasTariffOneMonth;

            var length = selectedQuota.Year3 ? 36 : selectedQuota.Year ? 12 : 1;

            var sale = GetPrice(monthQuota, region) * usersCount * (selectedQuota.Year3 ? 36 : selectedQuota.Year ? 12 : 0);

            var total = GetPrice(selectedQuota, region) * usersCount;

            var result = new TariffDetails()
            {
                Price = GetPriceString(GetPrice(selectedQuota, region) / length, region),
                UsersCount = usersCount,
                Period = period,
                Sale = sale > 0 ? GetPriceString(sale, region) : string.Empty,
                TotalPrice = GetPriceString(total, region),
            };

            var shoppingData = GetShoppingData(selectedQuota, region.ISOCurrencySymbol, usersCount);

            result.ButtonText = shoppingData.Item1;
            result.InfoText = shoppingData.Item2;
            result.ShoppingUrl = shoppingData.Item3;

            return result;
        }

        [AjaxMethod]
        public TenantQuota ContinueStartup()
        {
            var currentQuota = TenantExtra.GetTenantQuota();
            var startupQuota = GetStartupQuota();

            if (!CheckStartupEnabled(currentQuota, startupQuota, out string message))
            {
                throw new NotSupportedException(message);
            }

            CoreContext.PaymentManager.SetTariff(TenantProvider.CurrentTenantID, new Tariff
            {
                QuotaId = startupQuota.Id,
                DueDate = DateTime.MaxValue
            });

            return startupQuota;
        }

        [Serializable]
        public class TariffDetails
        {
            public string Price;
            public int UsersCount;
            public string Period;
            public string Sale;
            public string TotalPrice;
            public string ButtonText;
            public string InfoText;
            public string ShoppingUrl;
        }
    }
}


text:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using Wargaming.WebAPI.Requests;

namespace Wargaming.WebAPI.WoT.Requests
{
	public class RegularTeamInformationRequest : RequestBase
	{
		/// <summary>
		/// Team ID's
		/// </summary>
		[JsonProperty("team_id")]
		private string RequestedTeamIdsValue
		{
			get { return string.Join(",", this.RequestedTeamIds); }
			set { this.RequestedTeamIds = value.Split(',').Select(x => int.Parse(x)).ToList(); }
		}

		/// <summary>
		/// Team ID's
		/// </summary>
		[JsonIgnore]
		public List<int> RequestedTeamIds { get; set; } = new List<int>();
	}
}


text:
namespace blink {

// The Interpolation class is an abstract class representing an animation effect
// between two keyframe values for the same property (CSS property, SVG
// attribute, etc), for example animating the CSS property 'left' from '100px'
// to '200px'.
//
// This is represented by a pair of keyframes, referred to as the start and end
// keyframes. Each keyframe contains a value for the given property, plus the
// value's 'composite mode', which indicates how the value applies on top of the
// element's existing value. For example, consider an element whose property
// 'left' computes to 50px before animations are applied, and which has an
// interpolation with start keyframe
//     {'left': '100px', composite: 'add'}
// and end keyframe
//     {'left': '200px', composite: 'replace'}
// This will produce an interpolated animation effect of the 'left' property of
// the element between the values 150px (i.e. 50px + 100px) and 200px.
//
// The subclasses of Interpolation store the start and end keyframes in
// different forms; see the description of each subclass for appropriate usage.
//
// At any given point in a keyframe animation effect, multiple interpolations
// may be in effect. These interpolations are referred to as the active
// interpolations, and are what are returned when sampling the effect model of
// an animation at a given local time (see EffectModel::Sample). Typically,
// there is only one active interpolation per property affected by the
// animation.
//
// Interpolations are used in two phases of animation computation:
//
// 1. Timing update phase:
//    To determine the value of a property at the current point in time, the
//    code calls the Interpolate function for each item in the list of active
//    interpolations. The arguments to this function specify how far through the
//    interpolation the animation currently is, and the function calculates the
//    value of the property at this point, storing the result in the
//    Interpolation object.
//
// 2. Effect application phase:
//    The interpolation's effect at its current timing state is applied to the
//    element. How this is done depends on the subclass of Interpolation. See
//    the subclass documentation for more.
class CORE_EXPORT Interpolation : public GarbageCollected<Interpolation> {
 public:
  Interpolation(const Interpolation&) = delete;
  Interpolation& operator=(const Interpolation&) = delete;
  virtual ~Interpolation() {}

  virtual void Interpolate(int iteration, double fraction) = 0;

  virtual bool IsInvalidatableInterpolation() const { return false; }
  virtual bool IsTransitionInterpolation() const { return false; }

  virtual const PropertyHandle& GetProperty() const = 0;

  // Indicates whether the cached current value (as calculated by Interpolate)
  // incorporates or replaces the property value that underlies the animation,
  // as in the case of additive animations. This tells us whether we can
  // optimise away computing underlying values.
  virtual bool DependsOnUnderlyingValue() const { return false; }

  virtual void Trace(Visitor*) const {}

 protected:
  Interpolation() = default;
};

using ActiveInterpolations = HeapVector<Member<Interpolation>, 1>;
using ActiveInterpolationsMap =
    HeapHashMap<PropertyHandle, Member<ActiveInterpolations>>;

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_INTERPOLATION_H_


text:
package org.ovirt.engine.core.vdsbroker.vdsbroker.predicates;

import org.apache.commons.lang.Validate;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.utils.linq.Predicate;

public final class IsNetworkOnInterfacePredicate implements Predicate<VdsNetworkInterface> {
    private final String networkName;

    public IsNetworkOnInterfacePredicate(String networkName) {
        Validate.notNull(networkName, "networkName can not be null");
        this.networkName = networkName;
    }

    @Override
    public boolean eval(VdsNetworkInterface vdsNetworkInterface) {
        return networkName.equals(vdsNetworkInterface.getNetworkName());
    }
}


text:
package geoptimize.swing;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

@SuppressWarnings("serial")
public class OpenBackgroundAction extends AbstractAction {
	MainWindow window;

	public OpenBackgroundAction(MainWindow window) {
		this.window = window;
		putValue(NAME, "Open");
		putValue(SHORT_DESCRIPTION, "Some short description");
	}
	public void actionPerformed(ActionEvent e) {

		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(new FileNameExtensionFilter("Image Formats (*.png, *.tif, *.bmp)","png","tif","bmp"));
		fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
		int result = fc.showOpenDialog(window);
		if(result == JFileChooser.APPROVE_OPTION) {
			File f = fc.getSelectedFile();
			try {
				window.context.loadBackground(f);
				window.toolbox.txtBackground.setText(f.getPath());
			}  catch (IOException e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(null, "Failed to load background image\n" + e1.getMessage());
			}
		}
	}
}


text:
using System.Runtime.Serialization;

namespace KeySndr.Common
{
    [DataContract]
    public class GridColor
    {
        [DataMember(Name = "red")]
        public int Red { get; set; }

        [DataMember(Name = "green")]
        public int Green { get; set; }

        [DataMember(Name = "blue")]
        public int Blue { get; set; }

        [DataMember(Name = "alpha")]
        public int Alpha { get; set; }

        public GridColor()
        {
            Red = 81;
            Green = 203;
            Blue = 238;
            Alpha = 1;
        }
    }
}


text:
<?php

namespace Zend\Mime\Exception;

/**
 * @category   Zend
 * @package    Zend_Mime
 */
interface ExceptionInterface
{}


text:
//Problem 8. Replace whole word

//Modify the solution of the previous problem to replace only whole words (not strings).

using System;
using System.IO;
using System.Text;

class ReplaceWholeWord
{
    static void Main()
    {
        StringBuilder sb = new StringBuilder();
        ReplaceWords(sb);
        WriteFileWithNewText(sb);
        Console.WriteLine("Words are now changed.");
    }

    private static void WriteFileWithNewText(StringBuilder sb)
    {
        using (StreamWriter writer = new StreamWriter(@"..\..\text.txt"))
        {
            writer.Write(sb);
        }
    }

    private static void ReplaceWords(StringBuilder sb)
    {
        using (StreamReader reader = new StreamReader(@"..\..\text.txt"))
        {
            string line = reader.ReadLine();

            while (line != null)
            {
                int index = line.IndexOf("start");

                while (index != -1)
                {
                    if (((index == 0) || (!Char.IsLetter(line[index - 1]))) &&
                        ((index >= (line.Length - 5)) || (!Char.IsLetter(line[index + 5]))))
                    {
                        line = line.Insert(index, "finish").Remove(index + 6, 5);
                        index = line.IndexOf("start");
                    }
                    else
                    {
                        index = line.IndexOf("start", index + 1);
                    }
                }

                sb.Append(line);

                if (!reader.EndOfStream)
                {
                    sb.Append("\r\n");
                }

                line = reader.ReadLine();
            }
        }
    }
}


text:
package com.speedment.common.tuple.internal.nullable.mapper;

import com.speedment.common.tuple.Tuple6;
import com.speedment.common.tuple.TupleMapper;
import com.speedment.common.tuple.TuplesOfNullables;
import com.speedment.common.tuple.internal.AbstractTupleMapper;
import com.speedment.common.tuple.nullable.Tuple6OfNullables;

import java.util.function.Function;

/**
 * An implementation class of a {@link TupleMapper } of degree 6
 * <p>
 * Generated by com.speedment.sources.pattern.tuple.TupleMapperImplPattern
 *
 * @param <T>  Type of the original object for the mapper to use when creating a
 *             {@code Tuple }
 * @param <T0> type of element 0
 * @param <T1> type of element 1
 * @param <T2> type of element 2
 * @param <T3> type of element 3
 * @param <T4> type of element 4
 * @param <T5> type of element 5
 *
 * @author Per Minborg
 */
public final class Tuple6OfNullablesMapperImpl<T, T0, T1, T2, T3, T4, T5>
extends AbstractTupleMapper<T, Tuple6OfNullables<T0, T1, T2, T3, T4, T5>>
implements TupleMapper<T, Tuple6OfNullables<T0, T1, T2, T3, T4, T5>> {

    /**
     * Constructs a {@link TupleMapper } that can create {@link Tuple6 }.
     *
     * @param m0 mapper to apply for element 0
     * @param m1 mapper to apply for element 1
     * @param m2 mapper to apply for element 2
     * @param m3 mapper to apply for element 3
     * @param m4 mapper to apply for element 4
     * @param m5 mapper to apply for element 5
     */
    public Tuple6OfNullablesMapperImpl(
            Function<T, T0> m0,
            Function<T, T1> m1,
            Function<T, T2> m2,
            Function<T, T3> m3,
            Function<T, T4> m4,
            Function<T, T5> m5) {
        super(6);
        set(0, m0);
        set(1, m1);
        set(2, m2);
        set(3, m3);
        set(4, m4);
        set(5, m5);
    }

    @Override
    public Tuple6OfNullables<T0, T1, T2, T3, T4, T5> apply(T t) {
        return TuplesOfNullables.ofNullables(
            get0().apply(t),
            get1().apply(t),
            get2().apply(t),
            get3().apply(t),
            get4().apply(t),
            get5().apply(t)
        );
    }

    public Function<T, T0> get0() {
        return getAndCast(0);
    }

    public Function<T, T1> get1() {
        return getAndCast(1);
    }

    public Function<T, T2> get2() {
        return getAndCast(2);
    }

    public Function<T, T3> get3() {
        return getAndCast(3);
    }

    public Function<T, T4> get4() {
        return getAndCast(4);
    }

    public Function<T, T5> get5() {
        return getAndCast(5);
    }
}


text:
package com.agileapes.webexport.io.impl.content;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author Mohammad Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (2013/2/13, 21:02)
 */
public class StreamContent extends BufferedContent {

    public StreamContent(InputStream stream) {
        this(stream, Charset.defaultCharset());
    }

    public StreamContent(InputStream stream, Charset charset) {
        super(new InputStreamReader(stream, charset));
    }

}


text:
<?php

namespace AppBundle\Controller\Admin;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Student;

class TeacherController extends Controller
{
    /**
     * @Template()
     * @Route("/admin/teachers", name="admin_teachers")
     *
     */
    public function indexAction(Request $request)
    {
        $teachers = $this
            ->get('doctrine')
            ->getRepository('AppBundle:Teacher')
            ->findAllTeachers();

        return ['teachers' => $teachers];
    }
}