text:
<?php

final class Mage_Connect_Command_Install extends Mage_Connect_Command
{
    /**
     * Install action callback
     *
     * @throws Exception
     * @param string $command
     * @param array $options
     * @param array $params
     * @param array $objects
     * @return array|null
     */
    public function doInstall($command, $options, $params, $objects = array())
    {
        $this->cleanupParams($params);

        $installFileMode = $command === 'install-file';

        /** @var $ftpObj Mage_Connect_Ftp */
        $ftpObj=null;
        $ftp = empty($options['ftp']) ? false : $options['ftp'];
        /** @var $packager Mage_Connect_Packager */
        $packager = $this->getPackager();
        /** @var $cache Mage_Connect_Singleconfig */
        /** @var $config Mage_Connect_Config */
        if ($ftp) {
            list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp);
        } else {
            $cache = $this->getSconfig();
            $config = $this->config();
        }

        try {
            $forceMode = isset($options['force']);
            $upgradeAllMode = $command == 'upgrade-all';
            $upgradeMode = $command == 'upgrade' || $command == 'upgrade-all';
            $noFilesInstall = isset($options['nofiles']);
            $withDepsMode = !isset($options['nodeps']);
            $ignoreModifiedMode = true || !isset($options['ignorelocalmodification']);
            $clearInstallMode = $command == 'install' && !$forceMode;
            $installAll = isset($options['install_all']);
            $channelAuth = isset($options['auth'])?$options['auth']:array();

            $rest = $this->rest();
            if (empty($config->magento_root)) {
                $config->magento_root=dirname(dirname($_SERVER['SCRIPT_FILENAME']));
            }
            chdir($config->magento_root);
            $dirCache = DIRECTORY_SEPARATOR . $config->downloader_path . DIRECTORY_SEPARATOR
                . Mage_Connect_Config::DEFAULT_CACHE_PATH;
            $dirTmp = DIRECTORY_SEPARATOR . Mage_Connect_Package_Reader::PATH_TO_TEMPORARY_DIRECTORY;
            $dirMedia = DIRECTORY_SEPARATOR . 'media';
            $isWritable = true;
            if ($ftp) {
                $cwd=$ftpObj->getcwd();
                $ftpObj->mkdirRecursive($cwd . $dirCache,0777);
                $ftpObj->chdir($cwd);
                $ftpObj->mkdirRecursive($cwd . $dirTmp,0777);
                $ftpObj->chdir($cwd);
                $ftpObj->mkdirRecursive($cwd . $dirMedia,0777);
                $ftpObj->chdir($cwd);
                $err = "Please check for sufficient ftp write file permissions.";
            } else {
                @mkdir($config->magento_root . $dirCache,0777,true);
                @mkdir($config->magento_root . $dirTmp,0777,true);
                @mkdir($config->magento_root . $dirMedia,0777,true);
                $isWritable = is_writable($config->magento_root)
                    && is_writable($config->magento_root . DIRECTORY_SEPARATOR . $config->downloader_path)
                    && is_writable($config->magento_root . $dirCache)
                    && is_writable($config->magento_root . $dirTmp)
                    && is_writable($config->magento_root . $dirMedia);
                $err = "Please check for sufficient write file permissions.";
            }
            $isWritable = $isWritable && is_writable($config->magento_root . $dirMedia)
                && is_writable($config->magento_root . $dirCache)
                && is_writable($config->magento_root . $dirTmp);
            if (!$isWritable) {
                $this->doError($command, $err);
                throw new Exception(
                    'Your Magento folder does not have sufficient write permissions, which downloader requires.'
                );
            }
            if (!empty($channelAuth)) {
                $rest->getLoader()->setCredentials($channelAuth['username'], $channelAuth['password']);
            }

            if ($installFileMode) {
                if (count($params) < 1) {
                    throw new Exception("Argument should be: filename");
                }
                $filename = $params[0];
                if (!@file_exists($filename)) {
                    throw new Exception("File '{$filename}' not found");
                }
                if (!@is_readable($filename)) {
                    throw new Exception("File '{$filename}' is not readable");
                }

                $package = new Mage_Connect_Package($filename);
                $package->setConfig($config);
                $package->validate();
                $errors = $package->getErrors();
                if (count($errors)) {
                    throw new Exception("Package file is invalid\n" . implode("\n", $errors));
                }

                $pChan = $package->getChannel();
                $pName = $package->getName();
                $pVer = $package->getVersion();

                if (!($cache->isChannelName($pChan) || $cache->isChannelAlias($pChan))) {
                    throw new Exception("The '{$pChan}' channel is not installed. Please use the MAGE shell "
                        . "script to install the '{$pChan}' channel.");
                }

                $conflicts = $cache->hasConflicts($pChan, $pName, $pVer);

                if (false !== $conflicts) {
                    $conflicts = implode(", ",$conflicts);
                    if ($forceMode) {
                        $this->doError($command, "Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts);
                    } else {
                        throw new Exception("Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts);
                    }
                }

                $conflicts = $package->checkPhpDependencies();
                if (true !== $conflicts) {
                    $conflicts = implode(",",$conflicts);
                    $err = "Package {$pChan}/{$pName} {$pVer} depends on PHP extensions: " . $conflicts;
                    if ($forceMode) {
                        $this->doError($command, $err);
                    } else {
                        throw new Exception($err);
                    }
                }

                $conflicts = $package->checkPhpVersion();
                if (true !== $conflicts) {
                    $err = "Package {$pChan}/{$pName} {$pVer}: " . $conflicts;
                    if ($forceMode) {
                        $this->doError($command, $err);
                    } else {
                        throw new Exception($err);
                    }
                }

                if (!$noFilesInstall) {
                    if ($ftp) {
                        $packager->processInstallPackageFtp($package, $filename, $config, $ftpObj);
                    } else {
                        $packager->processInstallPackage($package, $filename, $config);
                    }
                }
                $cache->addPackage($package);
                $installedDeps = array();
                $installedDepsAssoc = array();
                $installedDepsAssoc[] = array('channel'=>$pChan, 'name'=>$pName, 'version'=>$pVer);
                $installedDeps[] = array($pChan, $pName, $pVer);

                $title = isset($options['title']) ? $options['title'] : "Package installed: ";
                $out = array($command => array('data'=>$installedDeps, 'assoc'=>$installedDepsAssoc,  'title'=>$title));

                if ($ftp) {
                    $packager->writeToRemoteCache($cache, $ftpObj);
                    @unlink($config->getFilename());
                }

                $this->ui()->output($out);
                return $out[$command]['data'];
            }

            if (!$upgradeAllMode) {
                if (count($params) < 2) {
                    throw new Exception("Argument should be: channelName packageName");
                }
                $channel = $params[0];
                $package = $params[1];
                $argVersionMax = isset($params[2]) ? $params[2]: false;
                $argVersionMin = isset($params[3]) ? $params[3]: false;

                $cache->checkChannel($channel, $config, $rest);
                $channelName = $cache->chanName($channel);
                $this->ui()->output("Checking dependencies of packages");
                $packagesToInstall = $packager->getDependenciesList($channelName, $package, $cache, $config,
                    $argVersionMax, $argVersionMin, $withDepsMode, false, $rest
                );
                /*
                 * process 'failed' results
                 */
                if (count($packagesToInstall['failed'])) {
                    $showError=!count($packagesToInstall['result']);
                    foreach ($packagesToInstall['failed'] as $failed) {
                        $msg="Package {$failed['channel']}/{$failed['name']} failed: " . $failed['reason'];
                        if ($showError) {
                            $this->doError($command, $msg);
                        } else {
                            $this->ui()->output($msg);
                        }
                    }
                }
                $packagesToInstall = $packagesToInstall['result'];
            } else {
                if (empty($params[0])) {
                    $channels = $cache->getChannelNames();
                } else {
                    $channel = $params[0];
                    if (!$cache->isChannel($channel)) {
                        throw new Exception("'{$channel}' is not existant channel name / valid uri");
                    }
                    $channels = $cache->chanName($channel);
                }
                $packagesToInstall = array();
                $neededToUpgrade = $packager->getUpgradesList($channels, $cache, $config, $rest);
                foreach ($neededToUpgrade as $chan=>$packages) {
                    foreach ($packages as $name=>$data) {
                        $versionTo = $data['to'];
                        $tmp = $packager->getDependenciesList($chan, $name, $cache, $config, $versionTo, $versionTo,
                            $withDepsMode, false, $rest
                        );
                        if (count($tmp['result'])) {
                            $packagesToInstall = array_merge($packagesToInstall, $tmp['result']);
                        }
                    }
                }
            }

            /**
             * Make installation
             */
            $installedDeps = array();
            $installedDepsAssoc = array();

            foreach ($packagesToInstall as $package) {
                try {
                    $pName = $package['name'];
                    $pChan = $package['channel'];
                    $pVer = $package['downloaded_version'];
                    $pInstallState = $package['install_state'];
                    $rest->setChannel($cache->chanUrl($pChan));

                    /**
                     * Skip existing packages
                     */
                    if ($upgradeMode && $cache->hasPackage($pChan, $pName, $pVer, $pVer)
                        || ('already_installed' == $pInstallState && !$forceMode)
                    ) {
                        $this->ui()->output("Already installed: {$pChan}/{$pName} {$pVer}, skipping");
                        continue;
                    }

                    if ('incompartible' == $pInstallState) {
                        $this->ui()->output(
                            "Package incompartible with installed Magento: {$pChan}/{$pName} {$pVer}, skipping"
                        );
                        continue;
                    }

                    $conflicts = $cache->hasConflicts($pChan, $pName, $pVer);

                    if (false !== $conflicts) {
                        $conflicts = implode(", ",$conflicts);
                        if ($forceMode) {
                            $this->doError($command, "Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts);
                        } else {
                            throw new Exception("Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts);
                        }
                    }

                    /**
                     * Modifications
                     */
                    if (($upgradeMode || ($pInstallState == 'upgrade')) && !$ignoreModifiedMode) {
                        if ($ftp) {
                            $modifications = $packager->getRemoteModifiedFiles($pChan, $pName, $cache, $config, $ftp);
                        } else {
                            $modifications = $packager->getLocalModifiedFiles($pChan, $pName, $cache, $config);
                        }
                        if (count($modifications) > 0) {
                            $this->ui()->output('Changed locally: ');
                            foreach ($modifications as $row) {
                                if (!$ftp) {
                                    $this->ui()->output($config->magento_root . DS . $row);
                                } else {
                                    $this->ui()->output($row);
                                }
                            }
                        }
                    }

                    if ($ftp) {
                        $cwd=$ftpObj->getcwd();
                        $dir=$cwd . DIRECTORY_SEPARATOR .$config->downloader_path . DIRECTORY_SEPARATOR
                            . Mage_Connect_Config::DEFAULT_CACHE_PATH . DIRECTORY_SEPARATOR . trim( $pChan, "\\/");
                        $ftpObj->mkdirRecursive($dir,0777);
                        $ftpObj->chdir($cwd);
                    } else {
                        $dir = $config->getChannelCacheDir($pChan);
                        @mkdir($dir, 0777, true);
                    }
                    $dir = $config->getChannelCacheDir($pChan);
                    $packageFileName = $pName . "-" . $pVer . ".tgz";
                    $file = $dir . DIRECTORY_SEPARATOR . $packageFileName;
                    if (!@file_exists($file)) {
                        $this->ui()->output("Starting to download $packageFileName ...");
                        $rest->downloadPackageFileOfRelease($pName, $pVer, $file);
                        $this->ui()->output(sprintf("...done: %s bytes", number_format(filesize($file))));
                    }

                    /**
                     * Remove old version package before install new
                     */
                    if ($cache->hasPackage($pChan, $pName)) {
                        if ($ftp) {
                            $packager->processUninstallPackageFtp($pChan, $pName, $cache, $ftpObj);
                        } else {
                            $packager->processUninstallPackage($pChan, $pName, $cache, $config);
                        }
                        $cache->deletePackage($pChan, $pName);
                    }

                    $package = new Mage_Connect_Package($file);
                    if ($clearInstallMode && $pInstallState != 'upgrade' && !$installAll) {
                        $contents = $package->getContents();
                        $this->backup()->setFileTypes(array('csv', 'html'));
                        $typesToBackup = $this->backup()->getFileTypes();
                        $this->validator()->validateContents($contents, $config, $typesToBackup);
                        $errors = $this->validator()->getErrors();
                        if (count($errors)) {
                            throw new Exception("Package '{$pName}' is invalid\n" . implode("\n", $errors));
                        }

                        $targetPath = rtrim($config->magento_root, "\\/");
                        foreach ($contents as $filePath) {
                            $this->backup()->addFile($filePath, $targetPath);
                        }

                        if ($this->backup()->getFilesCount() > 0) {
                            $this->ui()->output('
');
                            $this->ui()->output('Backup of following files will be created :');
                            $this->ui()->output('
');
                            $this->backup()->run();
                            $this->ui()->output(implode('
', $this->backup()->getAllFiles()));
                            $this->ui()->output('
');
                            $this->ui()->output(
                                $this->backup()->getFilesCount() . ' files was overwritten by installed extension.'
                            );
                            $this->ui()->output('
');
                            $this->backup()->unsetAllFiles();
                        }
                    }

                    $conflicts = $package->checkPhpDependencies();
                    if (true !== $conflicts) {
                        $conflicts = implode(",",$conflicts);
                        $err = "Package {$pChan}/{$pName} {$pVer} depends on PHP extensions: " . $conflicts;
                        if ($forceMode) {
                            $this->doError($command, $err);
                        } else {
                            throw new Exception($err);
                        }
                    }

                    $conflicts = $package->checkPhpVersion();
                    if (true !== $conflicts) {
                        $err = "Package {$pChan}/{$pName} {$pVer}: " . $conflicts;
                        if ($forceMode) {
                            $this->doError($command, $err);
                        } else {
                            throw new Exception($err);
                        }
                    }

                    if (!$noFilesInstall) {
                        $this->ui()->output("Installing package {$pChan}/{$pName} {$pVer}");
                        if ($ftp) {
                            $packager->processInstallPackageFtp($package, $file, $config, $ftpObj);
                        } else {
                            $packager->processInstallPackage($package, $file, $config);
                        }
                        $this->ui()->output("Package {$pChan}/{$pName} {$pVer} installed successfully");
                    }
                    $cache->addPackage($package);

                    $installedDepsAssoc[] = array('channel'=>$pChan, 'name'=>$pName, 'version'=>$pVer);
                    $installedDeps[] = array($pChan, $pName, $pVer);

                } catch(Exception $e) {
                    $this->doError($command, $e->getMessage());
                }
            }

            $title = isset($options['title']) ? $options['title'] : "Package installed: ";
            $out = array($command => array('data'=>$installedDeps, 'assoc'=>$installedDepsAssoc,  'title'=>$title));

            if ($ftp) {
                $packager->writeToRemoteCache($cache, $ftpObj);
                @unlink($config->getFilename());
            }

            $this->ui()->output($out);
            return $out[$command]['data'];
        } catch (Exception $e) {
            if ($ftp) {
                $packager->writeToRemoteCache($cache, $ftpObj);
                @unlink($config->getFilename());
            }
            return $this->doError($command, $e->getMessage());
        }
    }

    /**
     * Upgrade action callback
     *
     * @param string $command
     * @param array $options
     * @param array $params
     * @return array|null
     */
    public function doUpgrade($command, $options, $params)
    {
        $options['title'] = "Package upgraded: ";
        return $this->doInstall($command, $options, $params);
    }

    /**
     * Updgrade action callback
     *
     * @param string $command
     * @param array $options
     * @param array $params
     * @return array|null
     */
    public function doUpgradeAll($command, $options, $params)
    {
        $options['title'] = "Package upgraded: ";
        return $this->doInstall($command, $options, $params);
    }

    /**
     * Uninstall package callback
     *
     * @param string $command
     * @param array $options
     * @param array $params
     * @return array|null
     */
    public function doUninstall($command, $options, $params)
    {
        $this->cleanupParams($params);

        try {
            if (count($params) != 2) {
                throw new Exception("Argument count should be = 2");
            }

            $channel = $params[0];
            $package = $params[1];
            /** @var $packager Mage_Connect_Packager */
            $packager = $this->getPackager();
            $withDepsMode = !isset($options['nodeps'])? false : (boolean)$options['nodeps'];
            $forceMode = isset($options['force']);

            $ftp = empty($options['ftp']) ? false : $options['ftp'];
            /** @var $cache Mage_Connect_Singleconfig */
            /** @var $config Mage_Connect_Config */
            /** @var $ftpObj Mage_Connect_Ftp */
            if ($ftp) {
                list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp);
            } else {
                $cache = $this->getSconfig();
                $config = $this->config();
            }

            $channel = $cache->chanName($channel);
            if (!$cache->hasPackage($channel, $package)) {
                throw new Exception("Package is not installed");
            }

            $deletedPackages = array();
            $list = $packager->getUninstallList($channel, $package, $cache, $config, $withDepsMode);
            foreach ($list['list'] as $packageData) {
                try {
                    $reqd = $cache->requiredByOtherPackages(
                        $packageData['channel'],
                        $packageData['name'],
                        $list['list']
                    );
                    if (count($reqd)) {
                        $errMessage = "{$packageData['channel']}/{$packageData['name']} "
                            . "{$packageData['version']} is required by: ";
                        $t = array();
                        foreach ($reqd as $r) {
                            $t[] = $r['channel'] . "/" . $r['name'] . " " . $r['version'];
                        }
                        $errMessage .= implode(", ", $t);
                        if ($forceMode) {
                            $this->ui()->output("Warning: " . $errMessage);
                        } else {
                            throw new Exception($errMessage);
                        }
                    }
                } catch(Exception $e) {
                    if ($forceMode) {
                        $this->doError($command, $e->getMessage());
                    } else {
                        throw new Exception($e->getMessage());
                    }
                }
            }
            foreach ($list['list'] as $packageData) {
                try {
                    list($chan, $pack) = array($packageData['channel'], $packageData['name']);
                    $packageName = $packageData['channel'] . "/" . $packageData['name'];
                    $this->ui()->output("Starting to uninstall $packageName ");
                    if ($ftp) {
                        $packager->processUninstallPackageFtp($chan, $pack, $cache, $ftpObj);
                    } else {
                        $packager->processUninstallPackage($chan, $pack, $cache, $config);
                    }
                    $cache->deletePackage($chan, $pack);
                    $deletedPackages[] = array($chan, $pack);
                    $this->ui()->output("Package {$packageName} uninstalled");
                } catch(Exception $e) {
                    if ($forceMode) {
                        $this->doError($command, $e->getMessage());
                    } else {
                        throw new Exception($e->getMessage());
                    }
                }
            }
            if ($ftp) {
                $packager->writeToRemoteCache($cache, $ftpObj);
                @unlink($config->getFilename());
            }
            $out = array($command=>array('data'=>$deletedPackages, 'title'=>'Package deleted: '));
            $this->ui()->output($out);
            return $out[$command]['data'];
        } catch (Exception $e) {
            return $this->doError($command, $e->getMessage());
        }
    }
}


text:
<security-constraint>
	<web-resource-collection>
		<web-resource-name>Decision Service</web-resource-name>
		<url-pattern>/ws/*</url-pattern>
		<url-pattern>/rest/*</url-pattern>
	</web-resource-collection>
	<auth-constraint>
		<role-name>resExecutors</role-name>
	</auth-constraint>
</security-constraint>

<login-config>
	<auth-method>BASIC</auth-method>
	<realm-name>Decision Service</realm-name>
</login-config>

<security-role>
	<description>The role that is required to use Decision Server Runtime - resExecutors</description>
	<role-name>resExecutors</role-name>
</security-role>

redpajama_set_name: RedPajamaGithub


text:
    <mdl-select [(ngModel)]="currentDatabase">
      <mdl-option *ngFor="let database of databases" [value]="database">{{database}}</mdl-option>
    </mdl-select>
    <mdl-checkbox [(ngModel)]="entitiesOnly">
      Entities Only
    </mdl-checkbox>

    <form (submit)="doSearch()" flex layout-align="center center" layout="row">
      <input type="search" name="searchText" [(ngModel)]="searchText" placeholder="Enter you search query here...">
      <button type="submit" mdl-colored="primary" mdl-button mdl-button-type="raised">Search</button>
    </form>

    <app-pagination [start]="searchResponse.start"
          [total]="searchResponse.total"
          [pageLength]="searchResponse['page-length']"
          (pageChanged)="pageChanged($event)"></app-pagination>

No Data

        <app-facets
          [facets]="searchResponse.facets"
          [(activeFacets)]="activeFacets"
          (activeFacetsChange)="updateFacets($event)"></app-facets>

 0">

              {{ result.label || result.uri }}

                    {{ text.highlight }}
                    {{ text }}

Searching...

      <mdl-spinner single-color active></mdl-spinner>


text:
"""Parsed source code checkers for docstring violations."""

import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple

from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
                     Method, Function, NestedFunction, Parser, StringIO,
                     ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem

__all__ = ('check', )

# If possible (python >= 3.2) use tokenize.open to open files, so PEP 263
# encoding markers are interpreted.
try:
    tokenize_open = tk.open
except AttributeError:
    tokenize_open = open

def check_for(kind, terminal=False):
    def decorator(f):
        f._check_for = kind
        f._terminal = terminal
        return f
    return decorator

class ConventionChecker(object):
    """Checker for PEP 257 and numpy conventions.

    D10x: Missing docstrings
    D20x: Whitespace issues
    D30x: Docstring formatting
    D40x: Docstring content issues

    """

    SECTION_NAMES = ['Short Summary',
                     'Extended Summary',
                     'Parameters',
                     'Returns',
                     'Yields',
                     'Other Parameters',
                     'Raises',
                     'See Also',
                     'Notes',
                     'References',
                     'Examples',
                     'Attributes',
                     'Methods']

    def check_source(self, source, filename, ignore_decorators=None):
        module = parse(StringIO(source), filename)
        for definition in module:
            for this_check in self.checks:
                terminate = False
                if isinstance(definition, this_check._check_for):
                    skipping_all = (definition.skipped_error_codes == 'all')
                    decorator_skip = ignore_decorators is not None and any(
                        len(ignore_decorators.findall(dec.name)) > 0
                        for dec in definition.decorators)
                    if not skipping_all and not decorator_skip:
                        error = this_check(self, definition,
                                           definition.docstring)
                    else:
                        error = None
                    errors = error if hasattr(error, '__iter__') else [error]
                    for error in errors:
                        if error is not None and error.code not in \
                                definition.skipped_error_codes:
                            partition = this_check.__doc__.partition('.\n')
                            message, _, explanation = partition
                            error.set_context(explanation=explanation,
                                              definition=definition)
                            yield error
                            if this_check._terminal:
                                terminate = True
                                break
                if terminate:
                    break

    @property
    def checks(self):
        all = [this_check for this_check in vars(type(self)).values()
               if hasattr(this_check, '_check_for')]
        return sorted(all, key=lambda this_check: not this_check._terminal)

    @check_for(Definition, terminal=True)
    def check_docstring_missing(self, definition, docstring):
        """D10{0,1,2,3}: Public definitions should have docstrings.

        All modules should normally have docstrings.  [...] all functions and
        classes exported by a module should also have docstrings. Public
        methods (including the __init__ constructor) should also have
        docstrings.

        Note: Public (exported) definitions are either those with names listed
              in __all__ variable (if present), or those that do not start
              with a single underscore.

        """
        if (not docstring and definition.is_public or
                docstring and is_blank(ast.literal_eval(docstring))):
            codes = {Module: violations.D100,
                     Class: violations.D101,
                     NestedClass: violations.D106,
                     Method: (lambda: violations.D105() if definition.is_magic
                              else (violations.D107() if definition.is_init
                              else violations.D102())),
                     Function: violations.D103,
                     NestedFunction: violations.D103,
                     Package: violations.D104}
            return codes[type(definition)]()

    @check_for(Definition)
    def check_one_liners(self, definition, docstring):
        """D200: One-liner docstrings should fit on one line with quotes.

        The closing quotes are on the same line as the opening quotes.
        This looks better for one-liners.

        """
        if docstring:
            lines = ast.literal_eval(docstring).split('\n')
            if len(lines) > 1:
                non_empty_lines = sum(1 for l in lines if not is_blank(l))
                if non_empty_lines == 1:
                    return violations.D200(len(lines))

    @check_for(Function)
    def check_no_blank_before(self, function, docstring):  # def
        """D20{1,2}: No blank lines allowed around function/method docstring.

        There's no blank line either before or after the docstring.

        """
        if docstring:
            before, _, after = function.source.partition(docstring)
            blanks_before = list(map(is_blank, before.split('\n')[:-1]))
            blanks_after = list(map(is_blank, after.split('\n')[1:]))
            blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
            blanks_after_count = sum(takewhile(bool, blanks_after))
            if blanks_before_count != 0:
                yield violations.D201(blanks_before_count)
            if not all(blanks_after) and blanks_after_count != 0:
                yield violations.D202(blanks_after_count)

    @check_for(Class)
    def check_blank_before_after_class(self, class_, docstring):
        """D20{3,4}: Class docstring should have 1 blank line around them.

        Insert a blank line before and after all docstrings (one-line or
        multi-line) that document a class -- generally speaking, the class's
        methods are separated from each other by a single blank line, and the
        docstring needs to be offset from the first method by a blank line;
        for symmetry, put a blank line between the class header and the
        docstring.

        """
        # NOTE: this gives false-positive in this case
        # class Foo:
        #
        #     """Docstring."""
        #
        #
        # # comment here
        # def foo(): pass
        if docstring:
            before, _, after = class_.source.partition(docstring)
            blanks_before = list(map(is_blank, before.split('\n')[:-1]))
            blanks_after = list(map(is_blank, after.split('\n')[1:]))
            blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
            blanks_after_count = sum(takewhile(bool, blanks_after))
            if blanks_before_count != 0:
                yield violations.D211(blanks_before_count)
            if blanks_before_count != 1:
                yield violations.D203(blanks_before_count)
            if not all(blanks_after) and blanks_after_count != 1:
                yield violations.D204(blanks_after_count)

    @check_for(Definition)
    def check_blank_after_summary(self, definition, docstring):
        """D205: Put one blank line between summary line and description.

        Multi-line docstrings consist of a summary line just like a one-line
        docstring, followed by a blank line, followed by a more elaborate
        description. The summary line may be used by automatic indexing tools;
        it is important that it fits on one line and is separated from the
        rest of the docstring by a blank line.

        """
        if docstring:
            lines = ast.literal_eval(docstring).strip().split('\n')
            if len(lines) > 1:
                post_summary_blanks = list(map(is_blank, lines[1:]))
                blanks_count = sum(takewhile(bool, post_summary_blanks))
                if blanks_count != 1:
                    return violations.D205(blanks_count)

    @staticmethod
    def _get_docstring_indent(definition, docstring):
        """Return the indentation of the docstring's opening quotes."""
        before_docstring, _, _ = definition.source.partition(docstring)
        _, _, indent = before_docstring.rpartition('\n')
        return indent

    @check_for(Definition)
    def check_indent(self, definition, docstring):
        """D20{6,7,8}: The entire docstring should be indented same as code.

        The entire docstring is indented the same as the quotes at its
        first line.

        """
        if docstring:
            indent = self._get_docstring_indent(definition, docstring)
            lines = docstring.split('\n')
            if len(lines) > 1:
                lines = lines[1:]  # First line does not need indent.
                indents = [leading_space(l) for l in lines if not is_blank(l)]
                if set(' \t') == set(''.join(indents) + indent):
                    yield violations.D206()
                if (len(indents) > 1 and min(indents[:-1]) > indent or
                        indents[-1] > indent):
                    yield violations.D208()
                if min(indents) < indent:
                    yield violations.D207()

    @check_for(Definition)
    def check_newline_after_last_paragraph(self, definition, docstring):
        """D209: Put multi-line docstring closing quotes on separate line.

        Unless the entire docstring fits on a line, place the closing
        quotes on a line by themselves.

        """
        if docstring:
            lines = [l for l in ast.literal_eval(docstring).split('\n')
                     if not is_blank(l)]
            if len(lines) > 1:
                if docstring.split("\n")[-1].strip() not in ['"""', "'''"]:
                    return violations.D209()

    @check_for(Definition)
    def check_surrounding_whitespaces(self, definition, docstring):
        """D210: No whitespaces allowed surrounding docstring text."""
        if docstring:
            lines = ast.literal_eval(docstring).split('\n')
            if lines[0].startswith(' ') or \
                    len(lines) == 1 and lines[0].endswith(' '):
                return violations.D210()

    @check_for(Definition)
    def check_multi_line_summary_start(self, definition, docstring):
        """D21{2,3}: Multi-line docstring summary style check.

        A multi-line docstring summary should start either at the first,
        or separately at the second line of a docstring.

        """
        if docstring:
            start_triple = [
                '"""', "'''",
                'u"""', "u'''",
                'r"""', "r'''",
                'ur"""', "ur'''"
            ]

            lines = ast.literal_eval(docstring).split('\n')
            if len(lines) > 1:
                first = docstring.split("\n")[0].strip().lower()
                if first in start_triple:
                    return violations.D212()
                else:
                    return violations.D213()

    @check_for(Definition)
    def check_triple_double_quotes(self, definition, docstring):
        r'''D300: Use """triple double quotes""".

        For consistency, always use """triple double quotes""" around
        docstrings. Use r"""raw triple double quotes""" if you use any
        backslashes in your docstrings. For Unicode docstrings, use
        u"""Unicode triple-quoted strings""".

        Note: Exception to this is made if the docstring contains
              """ quotes in its body.

        '''
        if docstring:
            if '"""' in ast.literal_eval(docstring):
                # Allow ''' quotes if docstring contains """, because
                # otherwise """ quotes could not be expressed inside
                # docstring. Not in PEP 257.
                regex = re(r"[uU]?[rR]?'''[^'].*")
            else:
                regex = re(r'[uU]?[rR]?"""[^"].*')

            if not regex.match(docstring):
                illegal_matcher = re(r"""[uU]?[rR]?("+|'+).*""")
                illegal_quotes = illegal_matcher.match(docstring).group(1)
                return violations.D300(illegal_quotes)

    @check_for(Definition)
    def check_backslashes(self, definition, docstring):
        r'''D301: Use r""" if any backslashes in a docstring.

        Use r"""raw triple double quotes""" if you use any backslashes
        (\) in your docstrings.

        '''
        # Just check that docstring is raw, check_triple_double_quotes
        # ensures the correct quotes.
        if docstring and '\\' in docstring and not docstring.startswith(
                ('r', 'ur')):
            return violations.D301()

    @check_for(Definition)
    def check_unicode_docstring(self, definition, docstring):
        r'''D302: Use u""" for docstrings with Unicode.

        For Unicode docstrings, use u"""Unicode triple-quoted strings""".

        '''
        if 'unicode_literals' in definition.module.future_imports:
            return

        # Just check that docstring is unicode, check_triple_double_quotes
        # ensures the correct quotes.
        if docstring and sys.version_info[0] <= 2:
            if not is_ascii(docstring) and not docstring.startswith(
                    ('u', 'ur')):
                return violations.D302()

    @check_for(Definition)
    def check_ends_with_period(self, definition, docstring):
        """D400: First line should end with a period.

        The [first line of a] docstring is a phrase ending in a period.

        """
        if docstring:
            summary_line = ast.literal_eval(docstring).strip().split('\n')[0]
            if not summary_line.endswith('.'):
                return violations.D400(summary_line[-1])

    @check_for(Function)
    def check_imperative_mood(self, function, docstring):  # def context
        """D401: First line should be in imperative mood: 'Do', not 'Does'.

        [Docstring] prescribes the function or method's effect as a command:
        ("Do this", "Return that"), not as a description; e.g. don't write
        "Returns the pathname ...".

        """
        if docstring and not function.is_test:
            stripped = ast.literal_eval(docstring).strip()
            if stripped:
                first_word = stripped.split()[0]
                check_word = first_word.lower()

                if check_word in IMPERATIVE_BLACKLIST:
                    return violations.D401b(first_word)

                try:
                    correct_form = IMPERATIVE_VERBS.get(stem(check_word))
                except UnicodeDecodeError:
                    # This is raised when the docstring contains unicode
                    # characters in the first word, but is not a unicode
                    # string. In which case D302 will be reported. Ignoring.
                    return

                if correct_form and correct_form != check_word:
                    return violations.D401(
                        correct_form.capitalize(),
                        first_word
                    )

    @check_for(Function)
    def check_no_signature(self, function, docstring):  # def context
        """D402: First line should not be function's or method's "signature".

        The one-line docstring should NOT be a "signature" reiterating the
        function/method parameters (which can be obtained by introspection).

        """
        if docstring:
            first_line = ast.literal_eval(docstring).strip().split('\n')[0]
            if function.name + '(' in first_line.replace(' ', ''):
                return violations.D402()

    @check_for(Function)
    def check_capitalized(self, function, docstring):
        """D403: First word of the first line should be properly capitalized.

        The [first line of a] docstring is a phrase ending in a period.

        """
        if docstring:
            first_word = ast.literal_eval(docstring).split()[0]
            if first_word == first_word.upper():
                return
            for char in first_word:
                if char not in string.ascii_letters and char != "'":
                    return
            if first_word != first_word.capitalize():
                return violations.D403(first_word.capitalize(), first_word)

    @check_for(Definition)
    def check_starts_with_this(self, function, docstring):
        """D404: First word of the docstring should not be `This`.

        Docstrings should use short, simple language. They should not begin
        with "This class is [..]" or "This module contains [..]".

        """
        if docstring:
            first_word = ast.literal_eval(docstring).split()[0]
            if first_word.lower() == 'this':
                return violations.D404()

    @staticmethod
    def _get_leading_words(line):
        """Return any leading set of words from `line`.

        For example, if `line` is "  Hello world!!!", returns "Hello world".
        """
        result = re("[A-Za-z ]+").match(line.strip())
        if result is not None:
            return result.group()

    @staticmethod
    def _is_a_docstring_section(context):
        """Check if the suspected context is really a section header.

        Lets have a look at the following example docstring:
            '''Title.

            Some part of the docstring that specifies what the function
            returns. <----- Not a real section name. It has a suffix and the
                            previous line is not empty and does not end with
                            a punctuation sign.

            This is another line in the docstring. It describes stuff,
            but we forgot to add a blank line between it and the section name.
            Returns  <----- A real section name. The previous line ends with
            -------         a period, therefore it is in a new
                            grammatical context.
            Bla.

            '''

        To make sure this is really a section we check these conditions:
            * There's no suffix to the section name.
            * The previous line ends with punctuation.
            * The previous line is empty.

        If one of the conditions is true, we will consider the line as
        a section name.
        """
        section_name_suffix = context.line.lstrip(context.section_name).strip()

        punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
        prev_line_ends_with_punctuation = \
            any(context.previous_line.strip().endswith(x) for x in punctuation)

        return (is_blank(section_name_suffix) or
                prev_line_ends_with_punctuation or
                is_blank(context.previous_line))

    @classmethod
    def _check_section_underline(cls, section_name, context, indentation):
        """D4{07,08,09,12}, D215: Section underline checks.

        Check for correct formatting for docstring sections. Checks that:
            * The line that follows the section name contains
              dashes (D40{7,8}).
            * The amount of dashes is equal to the length of the section
              name (D409).
            * The section's content does not begin in the line that follows
              the section header (D412).
            * The indentation of the dashed line is equal to the docstring's
              indentation (D215).
        """
        blank_lines_after_header = 0

        for line in context.following_lines:
            if not is_blank(line):
                break
            blank_lines_after_header += 1
        else:
            # There are only blank lines after the header.
            yield violations.D407(section_name)
            return

        non_empty_line = context.following_lines[blank_lines_after_header]
        dash_line_found = ''.join(set(non_empty_line.strip())) == '-'

        if not dash_line_found:
            yield violations.D407(section_name)
            if blank_lines_after_header > 0:
                yield violations.D412(section_name)
        else:
            if blank_lines_after_header > 0:
                yield violations.D408(section_name)

            if non_empty_line.strip() != "-" * len(section_name):
                yield violations.D409(len(section_name),
                                      section_name,
                                      len(non_empty_line.strip()))

            if leading_space(non_empty_line) > indentation:
                yield violations.D215(section_name)

            line_after_dashes_index = blank_lines_after_header + 1
            # If the line index after the dashes is in range (perhaps we have
            # a header + underline followed by another section header).
            if line_after_dashes_index < len(context.following_lines):
                line_after_dashes = \
                    context.following_lines[line_after_dashes_index]
                if is_blank(line_after_dashes):
                    rest_of_lines = \
                        context.following_lines[line_after_dashes_index:]
                    if not is_blank(''.join(rest_of_lines)):
                        yield violations.D412(section_name)
                    else:
                        yield violations.D414(section_name)
            else:
                yield violations.D414(section_name)

    @classmethod
    def _check_section(cls, docstring, definition, context):
        """D4{05,06,10,11,13}, D214: Section name checks.

        Check for valid section names. Checks that:
            * The section name is properly capitalized (D405).
            * The section is not over-indented (D214).
            * The section name has no superfluous suffix to it (D406).
            * There's a blank line after the section (D410, D413).
            * There's a blank line before the section (D411).

        Also yields all the errors from `_check_section_underline`.
        """
        capitalized_section = context.section_name.title()
        indentation = cls._get_docstring_indent(definition, docstring)

        if (context.section_name not in cls.SECTION_NAMES and
                capitalized_section in cls.SECTION_NAMES):
            yield violations.D405(capitalized_section, context.section_name)

        if leading_space(context.line) > indentation:
            yield violations.D214(capitalized_section)

        suffix = context.line.strip().lstrip(context.section_name)
        if suffix:
            yield violations.D406(capitalized_section, context.line.strip())

        if (not context.following_lines or
                not is_blank(context.following_lines[-1])):
            if context.is_last_section:
                yield violations.D413(capitalized_section)
            else:
                yield violations.D410(capitalized_section)

        if not is_blank(context.previous_line):
            yield violations.D411(capitalized_section)

        for err in cls._check_section_underline(capitalized_section,
                                                context,
                                                indentation):
            yield err

    @check_for(Definition)
    def check_docstring_sections(self, definition, docstring):
        """D21{4,5}, D4{05,06,07,08,09,10}: Docstring sections checks.

        Check the general format of a sectioned docstring:
            '''This is my one-liner.

            Short Summary
            -------------
            This is my summary.

            Returns
            -------
            None.

            '''

        Section names appear in `SECTION_NAMES`.
        """
        if not docstring:
            return

        lines = docstring.split("\n")
        if len(lines) < 2:
            return

        lower_section_names = [s.lower() for s in self.SECTION_NAMES]

        def _suspected_as_section(_line):
            result = self._get_leading_words(_line.lower())
            return result in lower_section_names

        # Finding our suspects.
        suspected_section_indices = [i for i, line in enumerate(lines) if
                                     _suspected_as_section(line)]

        SectionContext = namedtuple('SectionContext', ('section_name',
                                                       'previous_line',
                                                       'line',
                                                       'following_lines',
                                                       'original_index',
                                                       'is_last_section'))

        # First - create a list of possible contexts. Note that the
        # `following_linex` member is until the end of the docstring.
        contexts = (SectionContext(self._get_leading_words(lines[i].strip()),
                                   lines[i - 1],
                                   lines[i],
                                   lines[i + 1:],
                                   i,
                                   False)
                    for i in suspected_section_indices)

        # Now that we have manageable objects - rule out false positives.
        contexts = (c for c in contexts if self._is_a_docstring_section(c))

        # Now we shall trim the `following lines` field to only reach the
        # next section name.
        for a, b in pairwise(contexts, None):
            end = -1 if b is None else b.original_index
            new_ctx = SectionContext(a.section_name,
                                     a.previous_line,
                                     a.line,
                                     lines[a.original_index + 1:end],
                                     a.original_index,
                                     b is None)
            for err in self._check_section(docstring, definition, new_ctx):
                yield err

parse = Parser()

def check(filenames, select=None, ignore=None, ignore_decorators=None):
    """Generate docstring errors that exist in `filenames` iterable.

    By default, the PEP-257 convention is checked. To specifically define the
    set of error codes to check for, supply either `select` or `ignore` (but
    not both). In either case, the parameter should be a collection of error
    code strings, e.g., {'D100', 'D404'}.

    When supplying `select`, only specified error codes will be reported.
    When supplying `ignore`, all error codes which were not specified will be
    reported.

    Note that ignored error code refer to the entire set of possible
    error codes, which is larger than just the PEP-257 convention. To your
    convenience, you may use `pydocstyle.violations.conventions.pep257` as
    a base set to add or remove errors from.

    Examples
    ---------
    >>> check(['pydocstyle.py'])
    <generator object check at 0x...>

    >>> check(['pydocstyle.py'], select=['D100'])
    <generator object check at 0x...>

    >>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
    <generator object check at 0x...>

    """
    if select is not None and ignore is not None:
        raise IllegalConfiguration('Cannot pass both select and ignore. '
                                   'They are mutually exclusive.')
    elif select is not None:
        checked_codes = select
    elif ignore is not None:
        checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
                             set(ignore))
    else:
        checked_codes = violations.conventions.pep257

    for filename in filenames:
        log.info('Checking file %s.', filename)
        try:
            with tokenize_open(filename) as file:
                source = file.read()
            for error in ConventionChecker().check_source(source, filename,
                                                          ignore_decorators):
                code = getattr(error, 'code', None)
                if code in checked_codes:
                    yield error
        except (EnvironmentError, AllError, ParseError) as error:
            log.warning('Error in file %s: %s', filename, error)
            yield error
        except tk.TokenError:
            yield SyntaxError('invalid syntax in file %s' % filename)

def is_ascii(string):
    return all(ord(char) < 128 for char in string)

def leading_space(string):
    return re('\s*').match(string).group()


text:
  static const int ddLogLevel = LOG_LEVEL_WARN;
#else
  static const int ddLogLevel = LOG_LEVEL_WARN;
#endif

@interface VKVideoPlayerView()
@property (nonatomic, strong) NSMutableArray* customControls;
@property (nonatomic, strong) NSMutableArray* portraitControls;
@property (nonatomic, strong) NSMutableArray* landscapeControls;
@end

@implementation VKVideoPlayerView

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [self.scrubber removeObserver:self forKeyPath:@"maximumValue"];
  [self.rewindButton removeObserver:self forKeyPath:@"hidden"];
  [self.nextButton removeObserver:self forKeyPath:@"hidden"];
}

- (void)initialize {

  self.customControls = [NSMutableArray array];
  self.portraitControls = [NSMutableArray array];
  self.landscapeControls = [NSMutableArray array];
  [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
  self.view.frame = self.frame;
  self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
  [self addSubview:self.view];

  self.titleLabel.font = THEMEFONT(@"fontRegular", DEVICEVALUE(22.0f, 14.0f));
  self.titleLabel.textColor = THEMECOLOR(@"colorFont4");
  self.titleLabel.text = @"";

  self.captionButton.titleLabel.font = THEMEFONT(@"fontRegular", 13.0f);
  [self.captionButton setTitleColor:THEMECOLOR(@"colorFont4") forState:UIControlStateNormal];

  self.videoQualityButton.titleLabel.font = THEMEFONT(@"fontRegular", 13.0f);
  [self.videoQualityButton setTitleColor:THEMECOLOR(@"colorFont4") forState:UIControlStateNormal];

  self.currentTimeLabel.font = THEMEFONT(@"fontRegular", DEVICEVALUE(16.0f, 10.0f));
  self.currentTimeLabel.textColor = THEMECOLOR(@"colorFont4");
  self.totalTimeLabel.font = THEMEFONT(@"fontRegular", DEVICEVALUE(16.0f, 10.0f));
  self.totalTimeLabel.textColor = THEMECOLOR(@"colorFont4");

  [self.scrubber addObserver:self forKeyPath:@"maximumValue" options:0 context:nil];

  NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  [defaultCenter addObserver:self selector:@selector(durationDidLoad:) name:kVKVideoPlayerDurationDidLoadNotification object:nil];
  [defaultCenter addObserver:self selector:@selector(scrubberValueUpdated:) name:kVKVideoPlayerScrubberValueUpdatedNotification object:nil];

  [self.scrubber addTarget:self action:@selector(updateTimeLabels) forControlEvents:UIControlEventValueChanged];

  UIView* overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bottomControlOverlay.frame.size.width, self.bottomControlOverlay.frame.size.height)];
  overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  overlay.backgroundColor = THEMECOLOR(@"colorBackground8");
  overlay.alpha = 0.6f;
  [self.bottomControlOverlay addSubview:overlay];
  [self.bottomControlOverlay sendSubviewToBack:overlay];

  overlay = [[UIView alloc] initWithFrame:self.topControlOverlay.frame];
  overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  overlay.backgroundColor = THEMECOLOR(@"colorBackground8");
  overlay.alpha = 0.6f;
  [self.topControlOverlay addSubview:overlay];
  [self.topControlOverlay sendSubviewToBack:overlay];

  [self.captionButton setTitle:[VKSharedVideoPlayerSettingsManager.subtitleLanguageCode uppercaseString] forState:UIControlStateNormal];

  [self.videoQualityButton setTitle:[VKSharedVideoPlayerSettingsManager videoQualityShortDescription:[VKSharedVideoPlayerSettingsManager streamKey]] forState:UIControlStateNormal];

  self.externalDeviceLabel.adjustsFontSizeToFitWidth = YES;

  [self.rewindButton addObserver:self forKeyPath:@"hidden" options:0 context:nil];
  [self.nextButton addObserver:self forKeyPath:@"hidden" options:0 context:nil];

  self.fullscreenButton.hidden = NO;

  for (UIButton* button in @[
    self.topPortraitCloseButton
  ]) {
    [button setBackgroundImage:[[UIImage imageWithColor:THEMECOLOR(@"colorBackground8")] imageByApplyingAlpha:0.6f] forState:UIControlStateNormal];
    button.layer.cornerRadius = 4.0f;
    button.clipsToBounds = YES;
  }

  [self.topPortraitCloseButton addTarget:self action:@selector(doneButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

  self.playerControlsAutoHideTime = @5;
}

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self initialize];
  }
  return self;
}

- (void) awakeFromNib {
  [super awakeFromNib];
  [self initialize];
}

- (void)layoutSubviews {
  [super layoutSubviews];
}

#pragma - VKVideoPlayerViewDelegates

- (IBAction)playButtonTapped:(id)sender {

  UIButton* playButton;
  if ([sender isKindOfClass:[UIButton class]]) {
    playButton = (UIButton*)sender;
  }

  if (playButton.selected)  {
    [self.delegate playButtonPressed];
    [self setPlayButtonsSelected:NO];
  } else {
    [self.delegate pauseButtonPressed];
    [self setPlayButtonsSelected:YES];
  }
}

- (IBAction)nextTrackButtonPressed:(id)sender {
  [self.delegate nextTrackButtonPressed];
}

- (IBAction)previousTrackButtonPressed:(id)sender {
  [self.delegate previousTrackButtonPressed];
}

- (IBAction)rewindButtonPressed:(id)sender {
  [self.delegate rewindButtonPressed];
}

- (IBAction)fullscreenButtonTapped:(id)sender {
  self.fullscreenButton.selected = !self.fullscreenButton.selected;
  [self.delegate fullScreenButtonTapped];
}

- (IBAction)captionButtonTapped:(id)sender {
  [self.delegate captionButtonTapped];
}

- (IBAction)videoQualityButtonTapped:(id)sender {
  [self.delegate videoQualityButtonTapped];
}

- (IBAction)doneButtonTapped:(id)sender {
  [self.delegate doneButtonTapped];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  if (object == self.scrubber) {
    if ([keyPath isEqualToString:@"maximumValue"]) {
      DDLogVerbose(@"scrubber Value change: %f", self.scrubber.value);
      RUN_ON_UI_THREAD(^{
        [self updateTimeLabels];
      });
    }
  }

  if ([object isKindOfClass:[UIButton class]]) {
    UIButton* button = object;
    if ([button isDescendantOfView:self.topControlOverlay]) {
      [self layoutTopControls];
    }
  }
}

- (void)setDelegate:(id<VKVideoPlayerViewDelegate>)delegate {
  _delegate = delegate;
  self.scrubber.delegate = delegate;
}

- (void)durationDidLoad:(NSNotification *)notification {
  NSDictionary *info = [notification userInfo];
  NSNumber* duration = [info objectForKey:@"duration"];
  [self.delegate videoTrack].totalVideoDuration = duration;
  RUN_ON_UI_THREAD(^{
    self.scrubber.maximumValue = [duration floatValue];
    self.scrubber.hidden = NO;
  });
}

- (void)scrubberValueUpdated:(NSNotification *)notification {
  NSDictionary *info = [notification userInfo];
  RUN_ON_UI_THREAD(^{
    DDLogVerbose(@"scrubberValueUpdated: %@", [info objectForKey:@"scrubberValue"]);
    [self.scrubber setValue:[[info objectForKey:@"scrubberValue"] floatValue] animated:YES];
    [self updateTimeLabels];
  });
}

- (void)updateTimeLabels {
  DDLogVerbose(@"Updating TimeLabels: %f", self.scrubber.value);

  [self.currentTimeLabel setFrameWidth:100.0f];
  [self.totalTimeLabel setFrameWidth:100.0f];

  self.currentTimeLabel.text = [VKSharedUtility timeStringFromSecondsValue:(int)self.scrubber.value];
  [self.currentTimeLabel sizeToFit];
  [self.currentTimeLabel setFrameHeight:CGRectGetHeight(self.bottomControlOverlay.frame)];

  self.totalTimeLabel.text = [VKSharedUtility timeStringFromSecondsValue:(int)self.scrubber.maximumValue];
  [self.totalTimeLabel sizeToFit];
  [self.totalTimeLabel setFrameHeight:CGRectGetHeight(self.bottomControlOverlay.frame)];

  [self layoutSlider];
}

- (void)layoutSliderForOrientation:(UIInterfaceOrientation)interfaceOrientation {
  if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) {
    [self.totalTimeLabel setFrameOriginX:CGRectGetMinX(self.fullscreenButton.frame) - self.totalTimeLabel.frame.size.width];
  } else {
    [self.totalTimeLabel setFrameOriginX:CGRectGetMinX(self.captionButton.frame) - self.totalTimeLabel.frame.size.width - PADDING];
  }

  [self.scrubber setFrameOriginX:self.currentTimeLabel.frame.origin.x + self.currentTimeLabel.frame.size.width + 4];
  [self.scrubber setFrameWidth:self.totalTimeLabel.frame.origin.x - self.scrubber.frame.origin.x - 4];
  [self.scrubber setFrameOriginY:CGRectGetHeight(self.bottomControlOverlay.frame)/2 - CGRectGetHeight(self.scrubber.frame)/2];
}

- (void)layoutSlider {
  [self layoutSliderForOrientation:self.delegate.visibleInterfaceOrientation];
}

- (void)layoutTopControls {

  CGFloat rightMargin = CGRectGetMaxX(self.topControlOverlay.frame);
  for (UIView* button in self.topControlOverlay.subviews) {
    if ([button isKindOfClass:[UIButton class]] && button != self.doneButton && !button.hidden) {
      rightMargin = MIN(CGRectGetMinX(button.frame), rightMargin);
    }
  }

  [self.titleLabel setFrameWidth:rightMargin - CGRectGetMinX(self.titleLabel.frame) - 20];
}

- (void)setPlayButtonsSelected:(BOOL)selected {
  self.playButton.selected = selected;
  self.bigPlayButton.selected = selected;
}

- (void)setPlayButtonsEnabled:(BOOL)enabled {
  self.playButton.enabled = enabled;
  self.bigPlayButton.enabled = enabled;
}

- (void)setControlsEnabled:(BOOL)enabled {

  self.captionButton.enabled = enabled;
  self.videoQualityButton.enabled = enabled;
  self.topSettingsButton.enabled = enabled;

  [self setPlayButtonsEnabled:enabled];

  self.previousButton.enabled = enabled && self.delegate.videoTrack.hasPrevious;
  self.nextButton.enabled = enabled && self.delegate.videoTrack.hasNext;
  self.scrubber.enabled = enabled;
  self.rewindButton.enabled = enabled;
  self.fullscreenButton.enabled = enabled;

  self.isControlsEnabled = enabled;

  NSMutableArray *controlList = self.customControls.mutableCopy;
  [controlList addObjectsFromArray:self.portraitControls];
  [controlList addObjectsFromArray:self.landscapeControls];
  for (UIView *control in controlList) {
    if ([control isKindOfClass:[UIButton class]]) {
      UIButton *button = (UIButton*)control;
      button.enabled = enabled;
    }
  }
}

- (IBAction)handleSingleTap:(id)sender {
  [self setControlsHidden:!self.isControlsHidden];
  if (!self.isControlsHidden) {
    self.controlHideCountdown = [self.playerControlsAutoHideTime integerValue];
  }
  [self.delegate playerViewSingleTapped];
}

- (IBAction)handleSwipeLeft:(id)sender {
  [self.delegate nextTrackBySwipe];
}

- (IBAction)handleSwipeRight:(id)sender {
  [self.delegate previousTrackBySwipe];
}

- (void)setControlHideCountdown:(NSInteger)controlHideCountdown {
  if (controlHideCountdown == 0) {
    [self setControlsHidden:YES];
  } else {
    [self setControlsHidden:NO];
  }
  _controlHideCountdown = controlHideCountdown;
}

- (void)hideControlsIfNecessary {
  if (self.isControlsHidden) return;
  if (self.controlHideCountdown == -1) {
    [self setControlsHidden:NO];
  } else if (self.controlHideCountdown == 0) {
    [self setControlsHidden:YES];
  } else {
    self.controlHideCountdown--;
  }
}

- (void)setControlsHidden:(BOOL)hidden {
  DDLogVerbose(@"Controls: %@", hidden ? @"hidden" : @"visible");

  if (self.isControlsHidden != hidden) {
    self.isControlsHidden = hidden;
    self.controls.hidden = hidden;

    if (UIInterfaceOrientationIsLandscape(self.delegate.visibleInterfaceOrientation)) {
      for (UIView *control in self.landscapeControls) {
        control.hidden = hidden;
      }
    }
    if (UIInterfaceOrientationIsPortrait(self.delegate.visibleInterfaceOrientation)) {
      for (UIView *control in self.portraitControls) {
        control.hidden = hidden;
      }
    }
    for (UIView *control in self.customControls) {
      control.hidden = hidden;
    }
  }

  [self layoutTopControls];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  if ([touch.view isKindOfClass:[VKScrubber class]] ||
      [touch.view isKindOfClass:[UIButton class]]) {
    // prevent recognizing touches on the slider
    return NO;
  }
  return YES;
}

- (void)layoutForOrientation:(UIInterfaceOrientation)interfaceOrientation {
  if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) {
    self.topControlOverlay.hidden = YES;
    self.topPortraitControlOverlay.hidden = NO;

    [self.buttonPlaceHolderView setFrameOriginY:PADDING/2];
    self.buttonPlaceHolderView.hidden = YES;

    self.captionButton.hidden = YES;
    self.videoQualityButton.hidden = YES;

    [self.bigPlayButton setFrameOriginY:CGRectGetMinY(self.bottomControlOverlay.frame)/2 - CGRectGetHeight(self.bigPlayButton.frame)/2];

    for (UIView *control in self.portraitControls) {
      control.hidden = self.isControlsHidden;
    }
    for (UIView *control in self.landscapeControls) {
      control.hidden = YES;
    }

  } else {
    [self.topControlOverlay setFrameOriginY:0.0f];
    self.topControlOverlay.hidden = NO;
    self.topPortraitControlOverlay.hidden = YES;

    [self.buttonPlaceHolderView setFrameOriginY:PADDING/2 + CGRectGetMaxY(self.topControlOverlay.frame)];
    self.buttonPlaceHolderView.hidden = NO;

    self.captionButton.hidden = NO;
    self.videoQualityButton.hidden = NO;

    [self.bigPlayButton setFrameOriginY:(CGRectGetMinY(self.bottomControlOverlay.frame) - CGRectGetMaxY(self.topControlOverlay.frame))/2 + CGRectGetMaxY(self.topControlOverlay.frame) - CGRectGetHeight(self.bigPlayButton.frame)/2];

    for (UIView *control in self.portraitControls) {
      control.hidden = YES;
    }
    for (UIView *control in self.landscapeControls) {
      control.hidden = self.isControlsHidden;
    }
  }

  [self layoutTopControls];
  [self layoutSliderForOrientation:interfaceOrientation];
}

- (void)addSubviewForControl:(UIView *)view {
  [self addSubviewForControl:view toView:self];
}
- (void)addSubviewForControl:(UIView *)view toView:(UIView*)parentView {
  [self addSubviewForControl:view toView:parentView forOrientation:UIInterfaceOrientationMaskAll];
}
- (void)addSubviewForControl:(UIView *)view toView:(UIView*)parentView forOrientation:(UIInterfaceOrientationMask)orientation {
  view.hidden = self.isControlsHidden;
  if (orientation == UIInterfaceOrientationMaskAll) {
    [self.customControls addObject:view];
  } else if (orientation == UIInterfaceOrientationMaskPortrait) {
    [self.portraitControls addObject:view];
  } else if (orientation == UIInterfaceOrientationMaskLandscape) {
    [self.landscapeControls addObject:view];
  }
  [parentView addSubview:view];
}
- (void)removeControlView:(UIView*)view {
  [view removeFromSuperview];
  [self.customControls removeObject:view];
  [self.landscapeControls removeObject:view];
  [self.portraitControls removeObject:view];
}

@end


text:
.. rn:: 5.1.47-rel11.2

===============================
|Percona Server| 5.1.47-rel11.2
===============================

Percona is glad to announce the release of |Percona Server| 5.1.47-rel11.2 on July 12th, 2010 (Downloads are available `here <http://www.percona.com/downloads/Percona-Server-5.1/Percona-Server-5.1.47-11.2/>`_ and from the `Percona Software Repositories <http://www.percona.com/doc/percona-server/5.1/installation.html>`_).

Fixed bugs
==========

  * ``/*!...*/`` processing (:bug:`603618`)

  * Insert space instead of empty (:bug:`603618`)

  * Query cache insert to cache, but not found on it (MySQL bug `#55032 <http://bugs.mysql.com/bug.php?id=55032>`_)


text:
"""Creates an Instance VM with common defaults."""
# pylint: disable=g-import-not-at-top
import copy
import common
import default

# Properties for this component
BOOTDISKTYPE = default.BOOTDISK
BOOTDISKSIZE = default.BOOTDISKSIZE
CAN_IP_FWD = default.CAN_IP_FWD
DEVIMAGE = 'devImage'
DISK = default.DISK
DISKTYPE = default.DISKTYPE
DISK_RESOURCES = default.DISK_RESOURCES
ENDPOINT_NAME = default.ENDPOINT_NAME
GUEST_ACCELERATORS = default.GUEST_ACCELERATORS
INSTANCE_NAME = default.INSTANCE_NAME
MACHINETYPE = default.MACHINETYPE
METADATA = default.METADATA
NETWORK = default.NETWORK
SUBNETWORK = default.SUBNETWORK
NO_SCOPE = default.NO_SCOPE
PROJECT = default.PROJECT
PROVIDE_BOOT = default.PROVIDE_BOOT
SERVICE_ACCOUNTS = default.SERVICE_ACCOUNTS
SRCIMAGE = default.SRCIMAGE
TAGS = default.TAGS
ZONE = default.ZONE
AUTODELETE_BOOTDISK = 'bootDiskAutodelete'
STATIC_IP = 'staticIP'
NAT_IP = 'natIP'
HAS_EXTERNAL_IP = 'hasExternalIP'

# Defaults used for modules that imports this one
DEFAULT_DISKTYPE = 'pd-standard'
DEFAULT_IP_FWD = False
DEFAULT_MACHINETYPE = 'n1-standard-1'
DEFAULT_NETWORK = 'default'
DEFAULT_PROVIDE_BOOT = True
DEFAULT_BOOTDISKSIZE = 10
DEFAULT_AUTODELETE_BOOTDISK = True
DEFAULT_STATIC_IP = False
DEFAULT_HAS_EXTERNAL_IP = True
DEFAULT_DATADISKSIZE = 500
DEFAULT_ZONE = 'us-central1-f'
DEFAULT_PERSISTENT = 'PERSISTENT'
DEFAULT_SERVICE_ACCOUNT = [{
    'email': 'default',
    'scopes': [
        'https://www.googleapis.com/auth/cloud.useraccounts.readonly',
        'https://www.googleapis.com/auth/devstorage.read_only',
        'https://www.googleapis.com/auth/logging.write',
        'https://www.googleapis.com/auth/monitoring.write',
    ]
}]

# Set Metadata Value
ATTACHED_DISKS = 'ATTACHED_DISKS'

# Used for SSD special treatment
SCRATCH = 'SCRATCH'

# Blank image used when sourceImage property is not provided.
BLANK_IMAGE = 'empty10gb'

def MakeVMName(context):
  """Generates the VM name."""
  name = context.env['name']
  prop = context.properties
  named = INSTANCE_NAME in prop
  return prop[INSTANCE_NAME] if named else common.AutoName(name,
                                                           default.INSTANCE)

def GenerateComputeVM(context, create_disks_separately=True):
  """Generates one VM instance resource.

  Args:
    context: Template context dictionary.
    create_disks_separately: When true (default), all new disk resources are
      created as separate resources. This is legacy behaviour from when multiple
      disks creation was not allowed in the disks property.
  Returns:
    dictionary representing instance resource.
  """
  prop = context.properties
  boot_disk_type = prop.setdefault(BOOTDISKTYPE, DEFAULT_DISKTYPE)
  prop[default.DISKTYPE] = boot_disk_type
  can_ip_fwd = prop.setdefault(CAN_IP_FWD, DEFAULT_IP_FWD)
  disks = prop.setdefault(default.DISKS, list())
  local_ssd = prop.setdefault(default.LOCAL_SSD, 0)

  if disks:
    if create_disks_separately:
      # Legacy alternative from when multiple disks on creation were not allowed
      new_disks = prop.setdefault(default.DISK_RESOURCES, list())
      SetDiskProperties(context, disks)
      disks, prop[DISK_RESOURCES] = GenerateDisks(context, disks, new_disks)
    else:
      # All new disks (except local ssd) must provide a sourceImage or existing
      # source. Add blank source image if non provided.
      SetDiskProperties(context, disks, add_blank_src_img=True)

  machine_type = prop.setdefault(MACHINETYPE, DEFAULT_MACHINETYPE)
  metadata = prop.setdefault(METADATA, dict())
  network = prop.setdefault(NETWORK, DEFAULT_NETWORK)
  vm_name = MakeVMName(context)
  provide_boot = prop.setdefault(PROVIDE_BOOT, DEFAULT_PROVIDE_BOOT)
  tags = prop.setdefault(TAGS, dict([('items', [])]))
  zone = prop.setdefault(ZONE, DEFAULT_ZONE)
  has_external_ip = prop.get(HAS_EXTERNAL_IP, DEFAULT_HAS_EXTERNAL_IP)
  static_ip = prop.get(STATIC_IP, DEFAULT_STATIC_IP)
  nat_ip = prop.get(NAT_IP, None)

  if provide_boot:
    dev_mode = DEVIMAGE in prop and prop[DEVIMAGE]
    src_image = common.MakeC2DImageLink(prop[SRCIMAGE], dev_mode)
    boot_name = common.AutoName(context.env['name'], default.DISK, 'boot')
    disk_size = prop.get(BOOTDISKSIZE, DEFAULT_BOOTDISKSIZE)
    disk_type = common.MakeLocalComputeLink(context, DISKTYPE)
    autodelete = prop.get(AUTODELETE_BOOTDISK, DEFAULT_AUTODELETE_BOOTDISK)
    disks = PrependBootDisk(disks, boot_name, disk_type, disk_size, src_image,
                            autodelete)
  if local_ssd:
    disks = AppendLocalSSDDisks(context, disks, local_ssd)
  machine_type = common.MakeLocalComputeLink(context, default.MACHINETYPE)
  network = common.MakeGlobalComputeLink(context, default.NETWORK)
  subnetwork = ''
  if default.SUBNETWORK in prop:
    subnetwork = common.MakeSubnetworkComputeLink(context, default.SUBNETWORK)

  # To be consistent with Dev console and gcloud, service accounts need to be
  #  explicitly disabled
  remove_scopes = prop[NO_SCOPE] if NO_SCOPE in prop else False
  if remove_scopes and SERVICE_ACCOUNTS in prop:
    prop.pop(SERVICE_ACCOUNTS)
  else:  # Make sure there is a default service account
    prop.setdefault(SERVICE_ACCOUNTS, copy.deepcopy(DEFAULT_SERVICE_ACCOUNT))

  resource = []

  access_configs = []
  if has_external_ip:
    access_config = {'name': default.EXTERNAL, 'type': default.ONE_NAT}
    access_configs.append(access_config)
    if static_ip and nat_ip:
      raise common.Error(
          'staticIP=True and natIP cannot be specified at the same time')
    if static_ip:
      address_resource, nat_ip = MakeStaticAddress(vm_name, zone)
      resource.append(address_resource)
    if nat_ip:
      access_config['natIP'] = nat_ip
  else:
    if static_ip:
      raise common.Error('staticIP cannot be True when hasExternalIP is False')
    if nat_ip:
      raise common.Error(
          'natIP must not be specified when hasExternalIP is False')

  network_interfaces = []
  if subnetwork:
    network_interfaces.insert(0, {
        'network': network,
        'subnetwork': subnetwork,
        'accessConfigs': access_configs
    })
  else:
    network_interfaces.insert(0, {
        'network': network,
        'accessConfigs': access_configs
    })

  resource.insert(0, {
      'name': vm_name,
      'type': default.INSTANCE,
      'properties': {
          'zone': zone,
          'machineType': machine_type,
          'canIpForward': can_ip_fwd,
          'disks': disks,
          'networkInterfaces': network_interfaces,
          'tags': tags,
          'metadata': metadata,
      }
  })

  # Pass through any additional properties to the VM
  if SERVICE_ACCOUNTS in prop:
    resource[0]['properties'].update({SERVICE_ACCOUNTS: prop[SERVICE_ACCOUNTS]})
  if GUEST_ACCELERATORS in prop:
    for accelerators in prop[GUEST_ACCELERATORS]:
      accelerators['acceleratorType'] = common.MakeAcceleratorTypeLink(
          context, accelerators['acceleratorType'])
    resource[0]['properties'].update(
        {GUEST_ACCELERATORS: prop[GUEST_ACCELERATORS]})
    # GPUs cannot be attached to live migratable instances. See:
    # https://cloud.google.com/compute/docs/gpus/#restrictions
    resource[0]['properties'].update(
        {'scheduling': {'onHostMaintenance': 'terminate'}})
  return resource

def MakeStaticAddress(vm_name, zone):
  """Creates a static IP address resource; returns it and the natIP."""
  address_name = vm_name + '-address'
  address_resource = {
      'name': address_name,
      'type': default.ADDRESS,
      'properties': {
          'name': address_name,
          'region': common.ZoneToRegion(zone),
      },
  }
  return (address_resource, '$(ref.%s.address)' % address_name)

def PrependBootDisk(disk_list, name, disk_type, disk_size, src_image,
                    autodelete):
  """Appends the boot disk."""
  # Request boot disk creation (mark for autodelete)
  boot_disk = [{
      'autoDelete': autodelete,
      'boot': True,
      'deviceName': name,
      'initializeParams': {
          'diskType': disk_type,
          'diskSizeGb': disk_size,
          'sourceImage': src_image
      },
      'type': DEFAULT_PERSISTENT,
  }]
  return boot_disk + disk_list

def AppendLocalSSDDisks(context, disk_list, num_of_local_ssd):
  """Apends local ssds."""
  project = context.env[default.PROJECT]
  prop = context.properties
  zone = prop.setdefault(ZONE, DEFAULT_ZONE)
  local_ssd_disks = []
  for i in range(0, num_of_local_ssd):
    local_ssd_disks.append({
        'deviceName': 'local-ssd-%s' % i,
        'type': SCRATCH,
        'interface': 'SCSI',
        'mode': 'READ_WRITE',
        'autoDelete': True,
        'initializeParams': {'diskType': common.LocalComputeLink(
            project, zone, 'diskTypes', 'local-ssd')}
    })
  return disk_list + local_ssd_disks

def SetDiskProperties(context, disks, add_blank_src_img=False):
  """Set properties on each disk to required format.

  Sets default values, and moves properties passed directly into
  initializeParams where required.

  Args:
    context: Template context dictionary.
    disks: List of disks to set properties on.
    add_blank_src_img: When true, link to blank source image is added for new
    disks where a source image is not specified.
  """

  project = context.env[default.PROJECT]
  zone = context.properties.setdefault(ZONE, DEFAULT_ZONE)

  for disk in disks:
    disk.setdefault(default.AUTO_DELETE, True)
    disk.setdefault('boot', False)
    disk.setdefault(default.TYPE, DEFAULT_PERSISTENT)

    # If disk already exists, no properties to change.
    if default.DISK_SOURCE in disk:
      continue

    else:
      disk_init = disk.setdefault(default.INITIALIZEP, dict())
      if disk[default.TYPE] == SCRATCH:
        disk_init.setdefault(DISKTYPE, 'local-ssd')
      else:
        # In the Instance API reference, size and type are within this property
        if disk_init:
          disk_init.setdefault(default.DISK_SIZE, DEFAULT_DATADISKSIZE)
          disk_init.setdefault(default.DISKTYPE, DEFAULT_DISKTYPE)
        # You can also simply pass the size and type properties directly
        else:
          disk_init[default.DISK_SIZE] = disk.pop(default.DISK_SIZE,
                                                  DEFAULT_DATADISKSIZE)
          disk_init[default.DISKTYPE] = disk.pop(default.DISKTYPE,
                                                 DEFAULT_DISKTYPE)

        # If disk name was given as a direct property, move to initializeParams
        if default.DISK_NAME in disk:
          disk_init[default.DISK_NAME] = disk.pop(default.DISK_NAME)

        # Add link to a blank source image where non-specified
        if add_blank_src_img and default.SRCIMAGE not in disk_init:
          disk_init[default.SRCIMAGE] = common.MakeC2DImageLink(BLANK_IMAGE)

      # Change disk type names into URLs
      disk_init[default.DISKTYPE] = common.LocalComputeLink(
          project, zone, 'diskTypes', disk_init[default.DISKTYPE])

def GenerateDisks(context, disk_list, new_disks):
  """Generates as many disks as passed in the disk_list."""
  prop = context.properties
  zone = prop.setdefault(ZONE, DEFAULT_ZONE)
  sourced_disks = []
  disk_names = []
  for disk in disk_list:
    if default.DISK_SOURCE in disk or disk[default.TYPE] == SCRATCH:
      # These disks do not need to be created as separate resources
      sourced_disks.append(disk)
    else:
      # Extract disk parameters and create as separate resource
      disk_init = disk[default.INITIALIZEP]
      if default.DEVICE_NAME in disk:
        d_name = disk[default.DEVICE_NAME]
      elif default.DISK_NAME in disk_init:
        d_name = disk_init[default.DISK_NAME]
      else:
        raise common.Error('deviceName or diskName is needed for each disk in '
                           'this module implemention of multiple disks per vm.')
      new_disks.append({
          'name': d_name,
          'type': default.DISK,
          'properties': {
              'type': disk_init[default.DISKTYPE],
              'sizeGb': disk_init[default.DISK_SIZE],
              'zone': zone
          }
      })
      disk_names.append(d_name)
      source = common.Ref(d_name)
      sourced_disks.append({
          'deviceName': d_name,
          'autoDelete': disk[default.AUTO_DELETE],
          'boot': False,
          'source': source,
          'type': disk[default.TYPE],
      })
  items = prop[METADATA].setdefault('items', list())
  items.append({'key': ATTACHED_DISKS, 'value': ','.join(disk_names)})
  return sourced_disks, new_disks

def AddServiceEndpointIfNeeded(context):
  """If the endpoint property is present, it will add a service endpoint."""
  prop = context.properties
  if ENDPOINT_NAME not in prop:
    return []
  network = common.MakeGlobalComputeLink(context, default.NETWORK)
  reference = '$(ref.' + MakeVMName(context) + '.name)'
  address = common.MakeFQHN(context, reference)
  name = prop[ENDPOINT_NAME]
  resource = [
      {
          'name': name,
          'type': default.ENDPOINT,
          'properties': {
              'addresses': [
                  {'address': address}
              ],
              'dnsIntegration': {
                  'networks': [network]
              }
          }
      }
  ]
  return resource

def GenerateResourceList(context, **kwargs):
  """Returns list of resources generated by this module."""
  resources = GenerateComputeVM(context, **kwargs)
  resources += common.AddDiskResourcesIfNeeded(context)
  resources += AddServiceEndpointIfNeeded(context)
  return resources

def GenerateOutputList(context, resource_list):
  """Returns list of outputs generated by this module."""
  vm_res = resource_list[0]
  outputs = [{
      'name': 'internalIP',
      'value': '$(ref.%s.networkInterfaces[0].networkIP)' % vm_res['name'],
  }]
  has_external_ip = context.properties.get(HAS_EXTERNAL_IP,
                                           DEFAULT_HAS_EXTERNAL_IP)
  if has_external_ip:
    outputs.append({
        'name': 'ip',
        'value': ('$(ref.%s.networkInterfaces[0].accessConfigs[0].natIP)' %
                  vm_res['name']),
    })
  return outputs

@common.FormatErrorsDec
def GenerateConfig(context):
  """Generates YAML resource configuration."""
  resource_list = GenerateResourceList(context)
  output_list = GenerateOutputList(context, resource_list)
  return common.MakeResource(resource_list, output_list)


text:
namespace MassTransit
{
    using System;

    public interface IEndpointConventionCache<in TMessage>
        where TMessage : class
    {
        /// <summary>
        /// Returns the endpoint address for the message
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        bool TryGetEndpointAddress(out Uri address);
    }
}


text:
package com.stickycoding.rokon.audio;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.stickycoding.rokon.Debug;
import com.stickycoding.rokon.Rokon;

/**
 * RokonMusic.java
 * A class optimized for longer audio files - using MediaPlayer
 * Shouldn't be used for sound effects, use RokonAudio for that.
 *
 * If wanting to use callbacks (for things like onCompletion
 * use the standard MediaPlayer listeners. See MediaPlayer for
 * information - use RokonMusic.getMediaPlayer() to get the object.
 *
 * @author Richard
 */

public class RokonMusic {

	protected static MediaPlayer mediaPlayer;
	protected static boolean mustResume = false;

	private static void prepareMediaPlayer() {
		if(mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
		}
	}

	/**
	 * Plays a file from assets, no looping
	 *
	 * @param file valid path to a file in assets
	 */
	public static void play(String file) {
		play(file, false);
	}

	/**
	 * Plays a file from assets
	 *
	 * @param file valid path to a file in assets
	 * @param loop TRUE to loop the file, FALSE to play once
	 */
	public static void play(String file, boolean loop) {
		prepareMediaPlayer();
		mediaPlayer.setLooping(loop);
		AssetFileDescriptor afd = null;
		try {
			afd = Rokon.getActivity().getAssets().openFd(file);
		} catch (Exception e) {
			e.printStackTrace();
			Debug.error("Tried creating RokonMusic with missing asset ... " + file);
			Debug.forceExit();
			return;
		}
		try {
			mediaPlayer.reset();
			mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			afd.close();
		} catch (IOException e) {
			e.printStackTrace();
			Debug.error("Error setting data source in RokonMusic.play, IO exception");
			Debug.forceExit();
			return;
		} catch (IllegalStateException e) {
			e.printStackTrace();
			Debug.error("Error setting data source in RokonMusic.play, fail ...");
			return;
		}
		try {
			mediaPlayer.prepare();
		} catch (Exception e) {
			e.printStackTrace();
			Debug.error("Error preparing MediaPlayer");
			Debug.forceExit();
			return;
		}
		mediaPlayer.start();
	}

	/**
	 * Plays the current music file, if paused or stopped
	 */
	public static void play() {
		if(mediaPlayer == null) return;
		mediaPlayer.start();
	}

	/**
	 * Stops the current music file from playing
	 */
	public static void stop() {
		if(mediaPlayer == null) return;
		mediaPlayer.stop();
	}

	/**
	 * Pauses the current music file, resume with start()
	 */
	public static void pause() {
		if(mediaPlayer == null) return;
		mediaPlayer.pause();
	}

	/**
	 * Call when RokonActivity is paused
	 */
	public static void onPause() {
		if(mediaPlayer == null) return;
		if(mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			mustResume = true;
		}
	}

	/**
	 * Call when RokonActivity is resumed
	 */
	public static void onResume() {
		if(mediaPlayer == null) return;
		if(mustResume) {
			mediaPlayer.start();
			mustResume = false;
		}
	}

	/**
	 * Fetches the associated MediaPlayer object, so you can make your own changes or hook your own Listeners
	 *
	 * @return MediaPlayer object, NULL if none used
	 */
	public static MediaPlayer getMediaPlayer() {
		return mediaPlayer;
	}

}


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

-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<FrameLayout
		android:layout_width="fill_parent"
	    android:layout_height="0dip"
	    android:layout_weight="1"
   		android:padding="10dip">

		<FrameLayout
			android:id="@+id/frame"
			android:layout_width="fill_parent"
		    android:layout_height="fill_parent"
		    android:background="@drawable/picture_frame"
		    />
	</FrameLayout>

	<Button
    	android:id="@+id/go"
 		android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center_horizontal"

	    android:text="@string/go"
	    android:minWidth="150dip"
	    android:layout_marginBottom="2dip"
	    />

</LinearLayout>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jena. Z. , 15, 434.

#### Original name
null

### Remarks
null


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello using JSX</title>
    <link rel="stylesheet" type="text/css" href="../styles/hello-styles.css">
    <script src="../../vendor/maquette/maquette.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
	<script type="text/babel" src="helloJSX.jsx"></script>
  </head>
  <body>
  </body>
</html>


text:
import models.Note
import org.junit.runner._
import org.specs2.mutable._
import org.specs2.runner._
import _root_.anorm.SqlParser._
import _root_.anorm._
import _root_.anorm.~
import play.api.db.DB
import play.api.test.FakeApplication
import play.api.test.Helpers._
import play.api.Play.current

@RunWith(classOf[JUnitRunner])
class DraftSpec extends Specification {

  // -- Date helpers

  // --

  //val c = Computer.findById(1)
  //println(list)

  "Application" should {

    "redirect to the computer list on /" in {
      running(FakeApplication()) {

        val id = 5l;

        val note = DB.withConnection { implicit connection =>
          SQL("select * from note where id = {id}").on('id -> id).as(Note.simple.singleOpt)
        }

        //print("id = " + note.get.id)

        note must be not
      }
    }
  }
}


text:
import * as util from '/lib/util.js';

var rand = new Phaser.RandomDataGenerator([Date.now()]);

var Shape = util.extend(Object, 'Shape', {
  constructor: function Shape(name, texture) {
    this.name = name;
    this.texture = texture;
    this.next = null;
    this.prev = null;
    Shape.shapes.push(this);
  }
});
Shape.shapes = [];
Shape.shapes = [];
Shape.triangle = new Shape('triangle', 'images/triangle');
Shape.square = new Shape('square', 'images/square');
Shape.circle = new Shape('circle', 'images/circle');
Shape.pentagon = new Shape('pentagon', 'images/pentagon');
for(var i = 0; i < Shape.shapes.length; i++) {
  var shape = Shape.shapes[i];
  shape.next = Shape.shapes[(i + 1) % Shape.shapes.length];
  shape.prev = Shape.shapes[i == 0 ? Shape.shapes.length - 1 :
    (i - 1) % Shape.shapes.length];
}

Shape.randomShape = function randomShape() {
  return rand.pick(Shape.shapes);
};

var Color = util.extend(Object, 'Color', {
  constructor: function Color(name, shade) {
    this.name = name;
    this.shade = shade;
  }
});
Color.colors = [
  new Color('red', '#FF0000'),
  new Color('blue', '#0000FF'),
  new Color('yellow', '#FFFF00'),
  new Color('green', '#00FF00')
];
Color.randomColor = function randomColor() {
  return rand.pick(Color.colors);
};

function getTextureName(shape, color) {
  return 'piece-' + shape.name + '-' + color.name;
}

export {
  rand,
  Shape,
  Color,
  getTextureName
};


text:
class HttpAuthBackend(object):
    """
    Authenticates
    """


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rasa_core.interpreter import RegexInterpreter
from rasa_core.training_utils.dsl import StoryFileReader, STORY_START, \
    TrainingsDataExtractor
from rasa_core.training_utils.story_graph import StoryGraph

def extract_training_data_from_file(filename,
                                    augmentation_factor=20,
                                    max_history=1,
                                    remove_duplicates=True,
                                    domain=None,
                                    featurizer=None,
                                    interpreter=RegexInterpreter(),
                                    max_number_of_trackers=2000):
    graph = extract_story_graph_from_file(filename, domain)
    extractor = TrainingsDataExtractor(graph, domain, featurizer, interpreter)
    return extractor.extract_trainings_data(remove_duplicates,
                                            augmentation_factor,
                                            max_history,
                                            max_number_of_trackers)

def extract_stories_from_file(filename,
                              domain,
                              remove_duplicates=True,
                              interpreter=RegexInterpreter(),
                              max_number_of_trackers=2000):
    graph = extract_story_graph_from_file(filename, domain)
    return graph.build_stories(domain,
                               interpreter,
                               remove_duplicates,
                               max_number_of_trackers)

def extract_story_graph_from_file(filename, domain):
    story_steps = StoryFileReader.read_from_file(filename, domain)
    return StoryGraph(story_steps)


text:
<!DOCTYPE html>

    <title> Raymond Chan </title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="title" content="Raymond Chan's Site">
    <meta name="description" content="">
    <meta name="author" content="Raymond Chan">

    <link rel="shortcut icon" type="image/png" href="/assets/images/favicon.ico"/>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="/assets/css/style.css" rel="stylesheet">
    <link href="/assets/css/sidebar.css" rel="stylesheet">

    <link href="/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Hi, I am finishing up my Computer Science and Business Administration studies at UC Berkeley. Past summers, I have interned at ZapLabs and Google. At school, I work with Capital Investments at Berkeley in applying deep and reinforcement learning on finance markets. This semester I teach Efficient Algorithms and Intractable Problems (CS 170) as an undergraduate student instructor. You can find my résumé here and teaching materials below.

          Course
          Course Name
          Semester
          Resource

          CS 170

              Efficient Algorithms and
Intractable Problems

            Fall 2017
 (Head TA)

            Link

          CS 170

              Efficient Algorithms and
Intractable Problems

          Spring 2017

            Link

          CS 61A

              The Structure and Interpretation
of Computer Programs

          Fall 2016

            Link

          CS 61A

              The Structure and Interpretation
of Computer Programs

          Spring 2016

            Link

Copyright © Raymond Chan 2017. All Rights Reserved.


text:
<order xmlns="http://www.openehealth.org/tutorial">
    <customer>123</customer>
    <category>books</category>
    <item>eating ozelots</item>
    <count>3</count>
</order>


text:
namespace OmniXaml.Services.Mvvm
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    public class ViewFactory : IViewFactory
    {
        private readonly ITypeFactory typeFactory;

        public ViewFactory(ITypeFactory typeFactory)
        {
            this.typeFactory = typeFactory;
        }

        private readonly Dictionary<string, Type> viewRegistrations = new Dictionary<string, Type>();

        public void RegisterView(ViewRegistration viewRegistration)
        {
            viewRegistrations.Add(viewRegistration.Token, viewRegistration.ViewType);
        }

        public void Show(string token)
        {
            var view = CreateUsingToken(token);
            TryInjectViewModel(view);
            view.Show();
        }

        private void TryInjectViewModel(IView view)
        {
            var viewType = view.GetType();
            var viewModelType = GetViewModelType(viewType);

            if (viewModelType != null)
            {
                var viewModel = typeFactory.Create(viewModelType);
                view.SetViewModel(viewModel);
            }
        }

        private static Type GetViewModelType(Type viewType)
        {
            var name = viewType.Namespace + "." + viewType.Name + "ViewModel";
            var viewModelType = viewType.GetTypeInfo().Assembly.GetType(name);
            return viewModelType;
        }

        private IView CreateUsingToken(string token)
        {
            var type = viewRegistrations[token];
            var view = (IView) typeFactory.Create(type);
            return view;
        }

        public void RegisterViews(IEnumerable<ViewRegistration> viewRegistrations)
        {
            foreach (var viewRegistration in viewRegistrations)
            {
                RegisterView(viewRegistration);
            }
        }

        public void ShowDialog(string token)
        {
            var view = CreateUsingToken(token);
            TryInjectViewModel(view);
            view.ShowDialog();
        }

        public IView GetWindow(string token)
        {
            var view = CreateUsingToken(token);
            TryInjectViewModel(view);
            return view;
        }
    }
}