text:
import * as fs from 'fs';
import * as path from 'path';
import * as webpack from 'webpack';
import chalk from 'chalk';

import { getAppFromConfig } from '../utilities/app-utils';
import { EjectTaskOptions } from '../commands/eject';
import { NgCliWebpackConfig } from '../models/webpack-config';
import { CliConfig } from '../models/config';
import { stripBom } from '../utilities/strip-bom';
import { AotPlugin, AngularCompilerPlugin } from '@ngtools/webpack';
import { PurifyPlugin } from '@angular-devkit/build-optimizer';
import { LicenseWebpackPlugin } from 'license-webpack-plugin';

import denodeify = require('denodeify');
import {oneLine, stripIndent} from 'common-tags';

const exists = (p: string) => Promise.resolve(fs.existsSync(p));
const writeFile = (denodeify(fs.writeFile) as (...args: any[]) => Promise<any>);
const angularCliPlugins = require('../plugins/webpack');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SubresourceIntegrityPlugin = require('webpack-subresource-integrity');
const SilentError = require('silent-error');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const ConcatPlugin = require('webpack-concat-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const Task = require('../ember-cli/lib/models/task');

const ProgressPlugin = require('webpack/lib/ProgressPlugin');

export const pluginArgs = Symbol('plugin-args');
export const postcssArgs = Symbol('postcss-args');

const yellow = chalk.yellow;
const pree2eNpmScript = `webdriver-manager update --standalone false --gecko false --quiet`;

class JsonWebpackSerializer {
  public imports: {[name: string]: string[]} = {};
  public variableImports: {[name: string]: string} = {
    'fs': 'fs',
    'path': 'path',
  };
  public variables: {[name: string]: string} = {
    'nodeModules': `path.join(process.cwd(), 'node_modules')`,
    'realNodeModules': `fs.realpathSync(nodeModules)`,
    'genDirNodeModules':
      `path.join(process.cwd(), '${this._appRoot}', '$$_gendir', 'node_modules')`,
  };
  private _postcssProcessed = false;

  constructor(private _root: string, private _dist: string, private _appRoot: string) {}

  private _escape(str: string) {
    return '\uFF01' + str + '\uFF01';
  }

  private _serializeRegExp(re: RegExp) {
    return this._escape(re.toString());
  }

  private _serializeFunction(fn: Function) {
    return this._escape(fn.toString());
  }

  private _relativePath(of: string, to: string) {
    return this._escape(`path.join(${of}, ${JSON.stringify(to)})`);
  }

  private _addImport(module: string, importName: string) {
    if (!this.imports[module]) {
      this.imports[module] = [];
    }
    if (this.imports[module].indexOf(importName) == -1) {
      this.imports[module].push(importName);
    }
  }

  private _globCopyWebpackPluginSerialize(value: any): any {
    let patterns = value.options.patterns;
    let globOptions = value.options.globOptions;
    return {
      patterns,
      globOptions: this._globReplacer(globOptions)
    };
  }

  private _insertConcatAssetsWebpackPluginSerialize(value: any): any {
    return value.entryNames;
  }

  private _commonsChunkPluginSerialize(value: any): any {
    let minChunks = value.minChunks;
    switch (typeof minChunks) {
      case 'function':
        minChunks = this._serializeFunction(value.minChunks);
        break;
    }

    return {
      name: value.chunkNames,
      filename: value.filenameTemplate,
      minChunks,
      chunks: value.selectedChunks,
      async: value.async,
      minSize: value.minSize
    };
  }

  private _extractTextPluginSerialize(value: any): any {
    return {
      filename: value.filename,
      disable: value.options.disable
    };
  }

  private _aotPluginSerialize(value: AotPlugin): any {
    const tsConfigPath = path.relative(this._root, value.options.tsConfigPath);
    const basePath = path.dirname(tsConfigPath);
    return Object.assign({}, value.options, {
      tsConfigPath,
      mainPath: path.relative(basePath, value.options.mainPath),
      hostReplacementPaths: Object.keys(value.options.hostReplacementPaths)
        .reduce((acc: any, key: string) => {
          const replacementPath = value.options.hostReplacementPaths[key];
          key = path.relative(basePath, key);
          acc[key] = path.relative(basePath, replacementPath);
          return acc;
        }, {}),
      exclude: Array.isArray(value.options.exclude)
        ? value.options.exclude.map((p: any) => {
          return p.startsWith('/') ? path.relative(basePath, p) : p;
        })
        : value.options.exclude
    });
  }

  private _htmlWebpackPlugin(value: any) {
    const chunksSortMode = value.options.chunksSortMode;
    this.variables['entryPoints'] = JSON.stringify(chunksSortMode.entryPoints);
    return Object.assign({}, value.options, {
      template: './' + path.relative(this._root, value.options.template),
      filename: './' + path.relative(this._dist, value.options.filename),
      chunksSortMode: this._serializeFunction(chunksSortMode)
    });
  }

  _environmentPlugin(plugin: any) {
    return plugin.defaultValues;
  }

  private _licenseWebpackPlugin(plugin: any) {
    return plugin.options;
  }

  private _concatPlugin(plugin: any) {
    const options = plugin.settings;
    if (!options || !options.filesToConcat) {
      return options;
    }

    const filesToConcat = options.filesToConcat
      .map((file: string) => path.relative(process.cwd(), file));

    return { ...options, filesToConcat };
  }

  private _uglifyjsPlugin(plugin: any) {
    return plugin.options;
  }

  private _pluginsReplacer(plugins: any[]) {
    return plugins.map(plugin => {
      let args = plugin.options || undefined;
      const serializer = (args: any) => JSON.stringify(args, (k, v) => this._replacer(k, v), 2);

      switch (plugin.constructor) {
        case ProgressPlugin:
          this.variableImports['webpack/lib/ProgressPlugin'] = 'ProgressPlugin';
          break;
        case webpack.NoEmitOnErrorsPlugin:
          this._addImport('webpack', 'NoEmitOnErrorsPlugin');
          break;
        case webpack.NamedModulesPlugin:
          this._addImport('webpack', 'NamedModulesPlugin');
          break;
        case (<any>webpack).HashedModuleIdsPlugin:
          this._addImport('webpack', 'HashedModuleIdsPlugin');
          break;
        case webpack.SourceMapDevToolPlugin:
          this._addImport('webpack', 'SourceMapDevToolPlugin');
          break;
        case webpack.optimize.UglifyJsPlugin:
          this._addImport('webpack.optimize', 'UglifyJsPlugin');
          break;
        case (webpack.optimize as any).ModuleConcatenationPlugin:
          this._addImport('webpack.optimize', 'ModuleConcatenationPlugin');
          break;
        case angularCliPlugins.BaseHrefWebpackPlugin:
        case angularCliPlugins.NamedLazyChunksWebpackPlugin:
        case angularCliPlugins.SuppressExtractedTextChunksWebpackPlugin:
          this._addImport('@angular/cli/plugins/webpack', plugin.constructor.name);
          break;
        case angularCliPlugins.GlobCopyWebpackPlugin:
          args = this._globCopyWebpackPluginSerialize(plugin);
          this._addImport('@angular/cli/plugins/webpack', 'GlobCopyWebpackPlugin');
          break;
        case angularCliPlugins.InsertConcatAssetsWebpackPlugin:
          args = this._insertConcatAssetsWebpackPluginSerialize(plugin);
          this._addImport('@angular/cli/plugins/webpack', 'InsertConcatAssetsWebpackPlugin');
          break;
        case webpack.optimize.CommonsChunkPlugin:
          args = this._commonsChunkPluginSerialize(plugin);
          this._addImport('webpack.optimize', 'CommonsChunkPlugin');
          break;
        case ExtractTextPlugin:
          args = this._extractTextPluginSerialize(plugin);
          this.variableImports['extract-text-webpack-plugin'] = 'ExtractTextPlugin';
          break;
        case CircularDependencyPlugin:
          this.variableImports['circular-dependency-plugin'] = 'CircularDependencyPlugin';
          break;
        case AotPlugin:
          args = this._aotPluginSerialize(plugin);
          this._addImport('@ngtools/webpack', 'AotPlugin');
          break;
        case PurifyPlugin:
          this._addImport('@angular-devkit/build-optimizer', 'PurifyPlugin');
          break;
        case AngularCompilerPlugin:
          args = this._aotPluginSerialize(plugin);
          this._addImport('@ngtools/webpack', 'AngularCompilerPlugin');
          break;
        case HtmlWebpackPlugin:
          args = this._htmlWebpackPlugin(plugin);
          this.variableImports['html-webpack-plugin'] = 'HtmlWebpackPlugin';
          break;
        case webpack.EnvironmentPlugin:
          args = this._environmentPlugin(plugin);
          this._addImport('webpack', 'EnvironmentPlugin');
          break;
        case LicenseWebpackPlugin:
          args = this._licenseWebpackPlugin(plugin);
          this._addImport('license-webpack-plugin', 'LicenseWebpackPlugin');
          break;
        case ConcatPlugin:
          args = this._concatPlugin(plugin);
          this.variableImports['webpack-concat-plugin'] = 'ConcatPlugin';
          break;
        case UglifyJSPlugin:
          args = this._uglifyjsPlugin(plugin);
          this.variableImports['uglifyjs-webpack-plugin'] = 'UglifyJsPlugin';
          break;
        case SubresourceIntegrityPlugin:
          this.variableImports['webpack-subresource-integrity'] = 'SubresourceIntegrityPlugin';
          break;

        default:
          if (plugin.constructor.name == 'AngularServiceWorkerPlugin') {
            this._addImport('@angular/service-worker/build/webpack', plugin.constructor.name);
          } else if (plugin['copyWebpackPluginPatterns']) {
            // CopyWebpackPlugin doesn't have a constructor nor save args.
            this.variableImports['copy-webpack-plugin'] = 'CopyWebpackPlugin';
            const patternOptions = plugin['copyWebpackPluginPatterns'].map((pattern: any) => {
              if (!pattern.context) {
                return pattern;
              }
              const context = path.relative(process.cwd(), pattern.context);
              return { ...pattern, context };
            });
            const patternsSerialized = serializer(patternOptions);
            const optionsSerialized = serializer(plugin['copyWebpackPluginOptions']) || 'undefined';
            return `\uFF02CopyWebpackPlugin(${patternsSerialized}, ${optionsSerialized})\uFF02`;
          }
          break;
      }

      const argsSerialized = serializer(args) || '';
      return `\uFF02${plugin.constructor.name}(${argsSerialized})\uFF02`;
    });
  }

  private _resolveReplacer(value: any) {
    return Object.assign({}, value, {
      modules: value.modules.map((x: string) => './' + path.relative(this._root, x))
    });
  }

  private _outputReplacer(value: any) {
    return Object.assign({}, value, {
      path: this._relativePath('process.cwd()', path.relative(this._root, value.path))
    });
  }

  private _path(l: string) {
    return l.split('!').map(x => {
      return path.isAbsolute(x) ? './' + path.relative(this._root, x) : x;
    }).join('!');
  }

  private _entryReplacer(value: any) {
    const newValue = Object.assign({}, value);
    for (const key of Object.keys(newValue)) {
      newValue[key] = newValue[key].map((l: string) => this._path(l));
    }
    return newValue;
  }

  private _loaderReplacer(loader: any) {
    if (typeof loader == 'string') {
      if (loader.match(/\/node_modules\/extract-text-webpack-plugin\//)) {
        return 'extract-text-webpack-plugin';
      } else if (loader.match(/@ngtools\/webpack\/src\/index.ts/)) {
        // return '@ngtools/webpack';
      }
    } else {
      if (loader.loader) {
        loader.loader = this._loaderReplacer(loader.loader);
      }
      if (loader.loader === 'postcss-loader' && !this._postcssProcessed) {
        const args: any = loader.options.plugins[postcssArgs];

        Object.keys(args.variableImports)
          .forEach(key => this.variableImports[key] = args.variableImports[key]);
        Object.keys(args.variables)
          .forEach(key => this.variables[key] = JSON.stringify(args.variables[key]));

        this.variables['postcssPlugins'] = loader.options.plugins;
        loader.options.plugins = this._escape('postcssPlugins');

        this._postcssProcessed = true;
      }
    }
    return loader;
  }

  private _ruleReplacer(value: any) {
    const replaceExcludeInclude = (v: any) => {
      if (typeof v == 'object') {
        if (v.constructor == RegExp) {
          return this._serializeRegExp(v);
        }
        return v;
      } else if (typeof v == 'string') {
        if (v === path.join(this._root, 'node_modules')) {
          return this._serializeRegExp(/(\\|\/)node_modules(\\|\/)/);
        }
        return this._relativePath('process.cwd()', path.relative(this._root, v));
      } else {
        return v;
      }
    };

    if (value[pluginArgs]) {
      return {
        include: Array.isArray(value.include)
          ? value.include.map((x: any) => replaceExcludeInclude(x))
          : replaceExcludeInclude(value.include),
        test: this._serializeRegExp(value.test),
        loaders: this._escape(
          `ExtractTextPlugin.extract(${JSON.stringify(value[pluginArgs], null, 2)})`)
      };
    }

    if (value.loaders) {
      value.loaders = value.loaders.map((loader: any) => this._loaderReplacer(loader));
    }
    if (value.loader) {
      value.loader = this._loaderReplacer(value.loader);
    }
    if (value.use) {
      if (Array.isArray(value.use)) {
        value.use = value.use.map((loader: any) => this._loaderReplacer(loader));
      } else {
        value.use = this._loaderReplacer(value.loader);
      }
    }

    if (value.exclude) {
      value.exclude = Array.isArray(value.exclude)
        ? value.exclude.map((x: any) => replaceExcludeInclude(x))
        : replaceExcludeInclude(value.exclude);
    }
    if (value.include) {
      value.include = Array.isArray(value.include)
        ? value.include.map((x: any) => replaceExcludeInclude(x))
        : replaceExcludeInclude(value.include);
    }

    return value;
  }

  private _moduleReplacer(value: any) {
    return Object.assign({}, value, {
      rules: value.rules && value.rules.map((x: any) => this._ruleReplacer(x))
    });
  }

  private _globReplacer(value: any) {
    return Object.assign({}, value, {
      cwd: this._relativePath('process.cwd()', path.relative(this._root, value.cwd))
    });
  }

  private _replacer(_key: string, value: any) {
    if (value === undefined) {
      return value;
    }
    if (value === null) {
      return null;
    }
    if (value.constructor === RegExp) {
      return this._serializeRegExp(value);
    }

    return value;
  }

  serialize(config: any): string {
    // config = Object.assign({}, config);
    config['plugins'] = this._pluginsReplacer(config['plugins']);
    // Routes using PathLocationStrategy break without this.
    config['devServer'] = {
      'historyApiFallback': true
    };
    config['resolve'] = this._resolveReplacer(config['resolve']);
    config['resolveLoader'] = this._resolveReplacer(config['resolveLoader']);
    config['entry'] = this._entryReplacer(config['entry']);
    config['output'] = this._outputReplacer(config['output']);
    config['module'] = this._moduleReplacer(config['module']);
    config['context'] = undefined;

    return JSON.stringify(config, (k, v) => this._replacer(k, v), 2)
      .replace(/"\uFF01(.*?)\uFF01"/g, (_, v) => {
        return JSON.parse(`"${v}"`);
      })
      .replace(/(\s*)(.*?)"\uFF02(.*?)\uFF02"(,?).*/g, (_, indent, key, value, comma) => {
        const ctor = JSON.parse(`"${value}"`).split(/\n+/g).join(indent);
        return `${indent}${key}new ${ctor}${comma}`;
      })
      .replace(/"\uFF01(.*?)\uFF01"/g, (_, v) => {
        return JSON.parse(`"${v}"`);
      });
  }

  generateVariables(): string {
    let variableOutput = '';
    Object.keys(this.variableImports)
      .forEach((key: string) => {
        const [module, name] = key.split(/\./);
        variableOutput += `const ${this.variableImports[key]} = require` + `('${module}')`;
        if (name) {
          variableOutput += '.' + name;
        }
        variableOutput += ';\n';
      });
    variableOutput += '\n';

    Object.keys(this.imports)
      .forEach((key: string) => {
        const [module, name] = key.split(/\./);
        variableOutput += `const { ${this.imports[key].join(', ')} } = require` + `('${module}')`;
        if (name) {
          variableOutput += '.' + name;
        }
        variableOutput += ';\n';
      });
    variableOutput += '\n';

    Object.keys(this.variables)
      .forEach((key: string) => {
        variableOutput += `const ${key} = ${this.variables[key]};\n`;
      });
    variableOutput += '\n\n';

    return variableOutput;
  }
}

export default Task.extend({
  run: function (runTaskOptions: EjectTaskOptions) {
    const project = this.project;
    const cliConfig = CliConfig.fromProject();
    const config = cliConfig.config;
    const appConfig = getAppFromConfig(runTaskOptions.app);

    const tsConfigPath = path.join(process.cwd(), appConfig.root, appConfig.tsconfig);
    const outputPath = runTaskOptions.outputPath || appConfig.outDir;
    const force = runTaskOptions.force;

    if (project.root === path.resolve(outputPath)) {
      throw new SilentError ('Output path MUST not be project root directory!');
    }
    if (appConfig.platform === 'server') {
      throw new SilentError('ng eject for platform server applications is coming soon!');
    }

    const webpackConfig = new NgCliWebpackConfig(runTaskOptions, appConfig).buildConfig();
    const serializer = new JsonWebpackSerializer(process.cwd(), outputPath, appConfig.root);
    const output = serializer.serialize(webpackConfig);
    const webpackConfigStr = `${serializer.generateVariables()}\n\nmodule.exports = ${output};\n`;

    return Promise.resolve()
      .then(() => exists('webpack.config.js'))
      .then(webpackConfigExists => {
        if (webpackConfigExists && !force) {
          throw new SilentError('The webpack.config.js file already exists.');
        }
      })
      // Read the package.json and update it to include npm scripts. We do this first so that if
      // an error already exists
      .then(() => stripBom(fs.readFileSync('package.json', 'utf-8')))
      .then((packageJson: string) => JSON.parse(packageJson))
      .then((packageJson: any) => {
        const scripts = packageJson['scripts'];
        if (scripts['build'] && scripts['build'] !== 'ng build' && !force) {
          throw new SilentError(oneLine`
            Your package.json scripts must not contain a build script as it will be overwritten.
          `);
        }
        if (scripts['start'] && scripts['start'] !== 'ng serve' && !force) {
          throw new SilentError(oneLine`
            Your package.json scripts must not contain a start script as it will be overwritten.
          `);
        }
        if (scripts['pree2e'] && scripts['pree2e'] !== pree2eNpmScript && !force) {
          throw new SilentError(oneLine`
            Your package.json scripts must not contain a pree2e script as it will be
            overwritten.
          `);
        }
        if (scripts['e2e'] && scripts['e2e'] !== 'ng e2e' && !force) {
          throw new SilentError(oneLine`
            Your package.json scripts must not contain a e2e script as it will be overwritten.
          `);
        }
        if (scripts['test'] && scripts['test'] !== 'ng test' && !force) {
          throw new SilentError(oneLine`
            Your package.json scripts must not contain a test script as it will be overwritten.
          `);
        }

        packageJson['scripts']['build'] = 'webpack';
        packageJson['scripts']['start'] = 'webpack-dev-server --port=4200';
        packageJson['scripts']['test'] = 'karma start ./karma.conf.js';
        packageJson['scripts']['pree2e'] = pree2eNpmScript;
        packageJson['scripts']['e2e'] = 'protractor ./protractor.conf.js';

        // Add new dependencies based on our dependencies.
        const ourPackageJson = require('../package.json');
        if (!packageJson['devDependencies']) {
          packageJson['devDependencies'] = {};
        }
        packageJson['devDependencies']['webpack-dev-server']
            = ourPackageJson['dependencies']['webpack-dev-server'];

        // Update all loaders from webpack, plus postcss plugins.
        [
          'webpack',
          'autoprefixer',
          'css-loader',
          'cssnano',
          'exports-loader',
          'file-loader',
          'html-webpack-plugin',
          'json-loader',
          'karma-sourcemap-loader',
          'less-loader',
          'postcss-loader',
          'postcss-url',
          'raw-loader',
          'sass-loader',
          'source-map-loader',
          'istanbul-instrumenter-loader',
          'style-loader',
          'stylus-loader',
          'url-loader',
          'circular-dependency-plugin',
          'webpack-concat-plugin',
          'copy-webpack-plugin',
          'uglifyjs-webpack-plugin',
        ].forEach((packageName: string) => {
          packageJson['devDependencies'][packageName] = ourPackageJson['dependencies'][packageName];
        });

        return writeFile('package.json', JSON.stringify(packageJson, null, 2) + '\n');
      })
      .then(() => JSON.parse(stripBom(fs.readFileSync(tsConfigPath, 'utf-8'))))
      .then((tsConfigJson: any) => {
        if (!tsConfigJson.exclude || force) {
          // Make sure we now include tests.  Do not touch otherwise.
          tsConfigJson.exclude = [
            'test.ts',
            '**/*.spec.ts'
          ];
        }
        return writeFile(tsConfigPath, JSON.stringify(tsConfigJson, null, 2) + '\n');
      })
      // Output the webpack.config.js.
      .then(() => writeFile('webpack.config.js', webpackConfigStr))
      .then(() => {
        // Update the CLI Config.
        config.project.ejected = true;
        cliConfig.save();
      })
      .then(() => {
        console.log(yellow(stripIndent`
          ==========================================================================================
          Ejection was successful.

          To run your builds, you now need to do the following commands:
             - "npm run build" to build.
             - "npm test" to run unit tests.
             - "npm start" to serve the app using webpack-dev-server.
             - "npm run e2e" to run protractor.

          Running the equivalent CLI commands will result in an error.

          ==========================================================================================
          Some packages were added. Please run "npm install".
        `));
      });
  }
});


text:
Novo Comentário

        <form method="post">

              Vídeo
              <input id="curso" type="text" class="validate" ng-model="comentariosCtrl.video.curso" disabled>
              <input id="video" type="text" class="validate" ng-model="comentariosCtrl.video.disciplina" disabled>

              Nota
              <select id="nota"class="browser-default" ng-model="comentario.nota">
                <option ng-repeat="index in [1,2,3,4,5]">{{index}}</option>
              </select>

              <textarea id="comentario" class="materialize-textarea" ng-model="comentario.comentario"></textarea>
              Comentário

          <button class="btn-large waves-effect waves-light indigo darken-3 right" type="submit" name="action" ng-click="newComentario(comentario)">Cadastrar
            send
          </button>
        </form>

redpajama_set_name: RedPajamaGithub


text:
<?php

if ( ! function_exists( 'kirki_show_upgrade_notification' ) ) :
	/**
	 * Fires at the end of the update message container in each
	 * row of the plugins list table.
	 * Allows us to add important notices about updates should they be needed.
	 * Notices should be added using "== Upgrade Notice ==" in readme.txt.
	 *
	 * @since 2.3.8
	 * @param array $plugin_data An array of plugin metadata.
	 * @param array $response    An array of metadata about the available plugin update.
	 */
	function kirki_show_upgrade_notification( $plugin_data, $response ) {

		// Check "upgrade_notice".
		if ( isset( $response->upgrade_notice ) && strlen( trim( $response->upgrade_notice ) ) > 0 ) : ?>

				<?php esc_attr_e( 'Important Upgrade Notice:', 'kirki' ); ?>
				<?php $upgrade_notice = wp_strip_all_tags( $response->upgrade_notice ); ?>
				<?php echo esc_html( $upgrade_notice ); ?>

			<?php
		endif;
	}
endif;
add_action( 'in_plugin_update_message-' . plugin_basename( __FILE__ ), 'kirki_show_upgrade_notification', 10, 2 );


text:
<html>

  <body>
  Contains classes pertaining to reports.
  </body>

</html>


text: package unmapify


text:
Bob
---

This game was an idea of using a point n' click type of game to explore the
reality of a depressed office worker in his depressing work, where
nothing motivates him. He is very frustrated and hates many aspects of his
life. That's way he escaped into his imagination in order to live the passions
that he cannot live in his day to day life.

Sadly, due to time restraints, only part of the office could be implemented.
Nonetheless, I learned a lot about making art for a game, exploring pixel-art.

Tools:
- Construct 2
- Graphics Gale
- Audacity


text:
class FileStatTest
  class << self
    def chmod(mode, path)
      system("chmod #{mode} #{path}")
      yield
    ensure
      system("chmod 644 #{path}")
    end
  end
end

assert 'File::Stat.new' do
  assert_kind_of File::Stat, File::Stat.new('README.md')
  assert_raise(RuntimeError){ File::Stat.new('unknown.file') }
end

assert 'File.stat' do
  assert_kind_of File::Stat, File.stat('README.md')
end

assert 'File.lstat' do
  assert_kind_of File::Stat, File.lstat('README.md')
end

assert 'File::Stat#initialize_copy' do
  orig = File::Stat.new('README.md')
  copy = orig.dup
  assert_equal orig.inspect, copy.inspect
end

assert 'File::Stat#<=>' do
  stat1 = File::Stat.new('README.md')
  stat2 = File::Stat.new('README.md')
  assert_equal 0, stat1.<=>(stat2)
  assert_equal nil, stat1.<=>(1)
  assert_raise(ArgumentError) { stat1 < 1 }
end

assert 'File::Stat#dev' do
  stat = File::Stat.new('README.md')
  assert_kind_of Fixnum, stat.dev
end

assert 'File::Stat#dev_major' do
  stat = File::Stat.new('README.md')
  if stat.dev_major
    assert_equal Fixnum, stat.dev_major.class
  else
    assert_nil stat.dev_major  ## not supported
  end
end

assert 'File::Stat#dev_minor' do
  stat = File::Stat.new('README.md')
  if stat.dev_minor
    assert_equal Fixnum, stat.dev_minor.class
  else
    assert_nil stat.dev_minor  ## not supported
  end
end

assert 'File::Stat#ino' do
  stat = File::Stat.new('README.md')
  assert_kind_of Numeric, stat.ino
end

assert 'File::Stat#mode' do
  stat = File::Stat.new('README.md')
  assert_kind_of Fixnum, stat.mode
end

assert 'File::Stat#nlink' do
  stat = File::Stat.new('README.md')
  assert_kind_of Fixnum, stat.nlink
end

assert 'File::Stat#uid' do
  stat = File::Stat.new('README.md')
  assert_kind_of Numeric, stat.uid
end

assert 'File::Stat#gid' do
  stat = File::Stat.new('README.md')
  assert_kind_of Numeric, stat.gid
end

assert 'File::Stat#rdev' do
  stat = File::Stat.new('README.md')
  assert_kind_of Fixnum, stat.rdev
end

assert 'File::Stat#rdev_major' do
  stat = File::Stat.new('README.md')
  if stat.rdev_major
    assert_equal Fixnum, stat.rdev_major.class
  else
    assert_nil stat.rdev_major  ## not supported
  end
end

assert 'File::Stat#rdev_minor' do
  stat = File::Stat.new('README.md')
  if stat.rdev_minor
    assert_equal Fixnum, stat.rdev_minor.class
  else
    assert_nil stat.rdev_minor  ## not supported
  end
end

assert 'File::Stat#blocks' do
  stat = File::Stat.new('README.md')
  blocks = stat.blocks
  skip "This system not support `struct stat.st_blocks`" if blocks.nil?

  assert_kind_of Integer, blocks
end

assert 'File::Stat#atime' do
  stat = File::Stat.new('README.md')
  assert_kind_of Time, stat.atime
end

assert 'File::Stat#mtime' do
  stat = File::Stat.new('README.md')
  assert_kind_of Time, stat.mtime
end

assert 'File::Stat#ctime' do
  stat = File::Stat.new('README.md')
  assert_kind_of Time, stat.ctime
end

assert 'File::Stat#birthtime' do
  stat = File::Stat.new('README.md')
  begin
    assert_kind_of Time, stat.birthtime
  rescue NotImplementedError
    skip 'This system not support `struct stat.birthtimespec`'
  end
end

assert 'File::Stat#size' do
  stat = File::Stat.new('README.md')
  assert_true 0 < stat.size
end

assert 'File::Stat#blksize' do
  stat = File::Stat.new('README.md')
  blksize = stat.blksize
  skip "This system not support `struct stat.st_blksize`" if blksize.nil?

  assert_kind_of Integer, blksize
end

assert 'File::Stat#inspect' do
  stat = File::Stat.new('README.md')
  %w(dev ino mode nlink uid gid size blksize blocks atime mtime ctime).all? do |name|
    assert_include stat.inspect, name
  end
end

assert 'File::Stat#ftype' do
  stat = File::Stat.new('README.md')
  assert_equal "file", stat.ftype

  stat = File::Stat.new('bin')
  assert_equal "directory", stat.ftype
end

assert 'File::Stat#directory?' do
  stat = File::Stat.new('README.md')
  assert_false stat.directory?

  stat = File::Stat.new('bin')
  assert_true stat.directory?
end

assert 'File::Stat#readable?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_true File::Stat.new("#{dir}/test/readable").readable?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_false File::Stat.new("#{dir}/test/writable").readable?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_false File::Stat.new("#{dir}/test/executable").readable?
  end
end

assert 'File::Stat#readable_real?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_true File::Stat.new("#{dir}/test/readable").readable_real?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_false File::Stat.new("#{dir}/test/writable").readable_real?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_false File::Stat.new("#{dir}/test/executable").readable_real?
  end
end

assert 'File::Stat#world_readable?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.system("chmod 0400 #{dir}/test/readable")
  assert_equal nil, File::Stat.new("#{dir}/test/readable").world_readable?
  FileStatTest.system("chmod 0444 #{dir}/test/readable")
  assert_equal 0444, File::Stat.new("#{dir}/test/readable").world_readable?
end

assert 'File::Stat#writable?' do
  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_false File::Stat.new("#{dir}/test/readable").writable?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_true File::Stat.new("#{dir}/test/writable").writable?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_false File::Stat.new("#{dir}/test/executable").writable?
  end
end

assert 'File::Stat#writable_real?' do
  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_false File::Stat.new("#{dir}/test/readable").writable_real?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_true File::Stat.new("#{dir}/test/writable").writable_real?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_false File::Stat.new("#{dir}/test/executable").writable_real?
  end
end

assert 'File::Stat#world_writable?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("0600", "#{dir}/test/writable") do
    assert_equal nil, File::Stat.new("#{dir}/test/writable").world_writable?
  end
  FileStatTest.chmod("0666", "#{dir}/test/writable") do
    assert_equal 0666, File::Stat.new("#{dir}/test/writable").world_writable?
  end
end

assert 'File::Stat#executable?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_false File::Stat.new("#{dir}/test/readable").executable?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_false File::Stat.new("#{dir}/test/writable").executable?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_true File::Stat.new("#{dir}/test/executable").executable?
  end
end

assert 'File::Stat#executable_real?' do
  skip "when windows" if FileStatTest.win?

  dir = __FILE__[0..-18] # 18 = /test/file-stat.rb
  FileStatTest.chmod("+r-w-x", "#{dir}/test/readable") do
    assert_false File::Stat.new("#{dir}/test/readable").executable_real?
  end
  FileStatTest.chmod("-r+w-x", "#{dir}/test/writable") do
    assert_false File::Stat.new("#{dir}/test/writable").executable_real?
  end
  FileStatTest.chmod("-r-w+x", "#{dir}/test/executable") do
    assert_true File::Stat.new("#{dir}/test/executable").executable_real?
  end
end

assert 'File::Stat#file?' do
  stat = File::Stat.new('README.md')
  assert_true stat.file?

  stat = File::Stat.new('bin')
  assert_false stat.file?
end

assert 'File::Stat#zero?' do
  stat = File::Stat.new('README.md')
  assert_false stat.zero?
end

assert 'File::Stat#size?' do
  stat = File::Stat.new('README.md')
  assert_true 0 < stat.size?
end

assert 'File::Stat#owned?' do
  stat = File::Stat.new('README.md')
  assert_true stat.owned?
end

assert 'File::Stat#owned_real?' do
  stat = File::Stat.new('README.md')
  assert_true stat.owned_real?
end

assert 'File::Stat#grpowned?' do
  is_unix = File::Stat.new('/dev/tty') rescue false
  if is_unix
    stat = File::Stat.new('README.md')
    assert_true stat.grpowned?
  else
    skip "is not supported"
  end
end

assert 'File::Stat#pipe?' do
  stat = File::Stat.new('README.md')
  assert_false stat.pipe?
end

assert 'File::Stat#symlink?' do
  stat = File::Stat.new('README.md')
  assert_false stat.symlink?
end

assert 'File::Stat#socket?' do
  stat = File::Stat.new('README.md')
  assert_false stat.socket?
end

assert 'File::Stat#blockdev?' do
  stat = File::Stat.new('README.md')
  assert_false stat.blockdev?
end

assert 'File::Stat#chardev?' do
  stat = File::Stat.new('README.md')
  assert_false stat.chardev?

  begin
    stat = File::Stat.new('/dev/tty')
    assert_true stat.chardev?
  rescue RuntimeError
    skip '/dev/tty is not found'
  end
end

assert 'File::Stat#setuid?' do
  stat = File::Stat.new('README.md')
  assert_false stat.setuid?
end

assert 'File::Stat#setgid?' do
  stat = File::Stat.new('README.md')
  assert_false stat.setgid?
end

assert 'File::Stat#sticky?' do
  stat = File::Stat.new('README.md')
  assert_false stat.sticky?
end


text:
ACCEPTED

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

#### Published in
Mycotaxon 55: 228 (1995)

#### Original name
Septosporium bolleanum Thüm., 1877

### Remarks
null


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.diamondq.common</groupId>
    <artifactId>common-parent</artifactId>
    <version>${revision}${sha1}${changelist}</version>
    <relativePath>../../common-parent</relativePath>
  </parent>
  <artifactId>common-tracing.opentracing</artifactId>
  <packaging>jar</packaging>
  <name>DiamondQ Common: Tracing: OpenTracing</name>
  <properties>
    <osgi.export.base.package>com.diamondq.common.tracing.opentracing.*</osgi.export.base.package>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>jakarta.enterprise</groupId>
      <artifactId>jakarta.enterprise.cdi-api</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>jakarta.annotation</groupId>
      <artifactId>jakarta.annotation-api</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>com.diamondq.common</groupId>
      <artifactId>common-utils</artifactId>
    </dependency>
    <dependency>
      <groupId>rocks.xmpp</groupId>
      <artifactId>xmpp-core-client</artifactId>
    </dependency>
    <dependency>
      <groupId>io.opentracing</groupId>
      <artifactId>opentracing-util</artifactId>
      <exclusions>
        <exclusion>
          <groupId>io.opentracing</groupId>
          <artifactId>opentracing-noop</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>io.opentracing</groupId>
      <artifactId>opentracing-noop</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>io.opentracing</groupId>
      <artifactId>opentracing-mock</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <id>test-jars</id>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <executions>
          <execution>
            <id>bundle-manifest</id>
            <configuration>
              <instructions>
                <Require-Capability>osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)"</Require-Capability>
                <Provide-Capability>osgi.serviceloader; osgi.serviceloader=rocks.xmpp.core.session.Module</Provide-Capability>
              </instructions>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
/**********|**********|**********|
Program: SaveFileCommand.h
Course: Degree In Computer Science - Game Development
Year: 2015/16 Trimester 1
Name: Wong Tiong Kiat
ID: 1132702943
Email: jackwongtiongkiat@gmail.com
Phone: 012-2321133
**********|**********|**********/
#ifndef SAVEFILECOMMAND_H_INCLUDED
#define SAVEFILECOMMAND_H_INCLUDED
/// using Board header for referencing.
#include "Board.h"
/// using FileWriter header for referencing.
#include "FileWriter.h"
//!  A sub-class SaveFileCommand of Command class.
/*!
  An interface class for sub-classes to inherits.
*/
class SaveFileCommand : public Command
{
       /**
       * save the board to a file name
       * \param board first argument.
       * \param fileName second argument.
       */
    public:
        SaveFileCommand(Board* board, std::string fileName)
        {
            board_ = board;
            fileName_ = fileName;
        }
      /**
       * save the game.
       */
        void execute()
        {
            FileWriter fw;
            fw.boardToFile(board_, fileName_);
        }

    private:
        Board* board_;
        std::string fileName_;
};

#endif // SAVEFILECOMMAND_H_INCLUDED


text:
layout: post
title: "Watch Out's Guide to the Branches at IIT Roorkee"
tags: [wona]
category: academics
image: branch-guide-22-cover.png
---

It is pretty difficult to choose a field of study that you might have to stick with for four (or five) years. We know because we've all been there. Hence, to make the process a little easier, we came up with this rather elaborate and painstakingly devised guide to the various branches at IIT Roorkee. With an analysis of the various specialisations available, including an overview of the syllabus, future prospects, and some inside information from IIT Roorkee, we hope to give you a perspective of what you might be getting into!

![pic](/images/posts/branch-guide-22.png){: style="width:100%;height:auto"}

<button type="button" class="btn btn-primary btn-block btn-lg">Download the Guide Here!</button>


text:
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*****更新用户基本信息*****/
CREATE PROCEDURE [dbo].[sp_UserInfo_Update]
@UserInfoID BIGINT,
@UserName VARCHAR(50),
@FK_MerchantID BIGINT,
@FK_MerchantAppID BIGINT,
@RealName NVARCHAR(50),
@NickName NVARCHAR(50),
@Pwd VARCHAR(50),
@Age INT,
@SexType CHAR(1),
@Birthday DATETIME,
@Tel VARCHAR(50),
@QQ VARCHAR(50),
@Email VARCHAR(100),
@OtherContact NVARCHAR(500),
@AccessType VARCHAR(50),
@AccessToken VARCHAR(100),
@UserState CHAR(1),
@UserType char(3),
@Remark NVARCHAR(1000),
@RoleName NVARCHAR(100),
@RoleMaxWeight INT,
@RecordState CHAR(1),
@CreateTime DATETIME,
@CreaterID BIGINT,
@CreaterName NVARCHAR(50),
@UpdateTime DATETIME,
@UpdaterID BIGINT,
@UpdaterName NVARCHAR(50),

@ResultCode INT OUTPUT,
@ResultMessage NVARCHAR(1000) OUTPUT
 AS
BEGIN

	BEGIN TRY
	UPDATE [UserInfo] SET
	UserName=@UserName , FK_MerchantID=@FK_MerchantID , RealName=@RealName , NickName=@NickName ,
	[FK_MerchantAppID] = @FK_MerchantAppID,[Pwd] = @Pwd,[Age] = @Age,[SexType] = @SexType,[Birthday] = @Birthday,[Tel] = @Tel,[QQ] = @QQ,[Email] = @Email,[OtherContact] = @OtherContact,[AccessType] = @AccessType,[AccessToken] = @AccessToken,[UserState] = @UserState,[UserType]=@UserType,[Remark] = @Remark,[RoleName] = @RoleName,[RoleMaxWeight] = @RoleMaxWeight,[RecordState] = @RecordState,[CreateTime] = @CreateTime,[CreaterID] = @CreaterID,[CreaterName] = @CreaterName,[UpdateTime] = @UpdateTime,[UpdaterID] = @UpdaterID,[UpdaterName] = @UpdaterName
	WHERE UserInfoID=@UserInfoID

		SET @ResultCode=1
	END TRY
	BEGIN CATCH
		SET @ResultMessage= ERROR_MESSAGE()
		SET @ResultCode=0
	END CATCH

END

GO


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using DataAccess;
using Shared;
using Shared.Models;
namespace MvcAngularBlog.Models
{
    public class BlogUserRepository : IBlogUser
    {
        private Dictionary<String, Object> operationParams = new Dictionary<String, Object>(); //passing empty collection
        private DataController dataController = new DataController();

        /// <summary>
        /// Constructor
        /// </summary>
        public BlogUserRepository()
        {
            operationParams.Clear();
        }

        /// <summary>
        /// Returns the info of the current user
        /// </summary>
        /// <returns></returns>
        public IEnumerable<BlogUser> GetCurrentUser()
        {
            List<BlogUser> blogUsers = new List<BlogUser>();
            Int32 userId;
            String userName = HttpContext.Current.User.Identity.Name;
            operationParams.Clear();
            operationParams.Add("userName", userName);
            userId = Convert.ToInt32(dataController.ExecuteOperation(OperationType.GetUserIdByUserName, operationParams));
            blogUsers.Add(new BlogUser { UserId = userId, UserName = userName });
            return blogUsers;
        }
    }
}


text:
"""This component provides HA sensor support for Ring Door Bell/Chimes."""
from datetime import datetime

from homeassistant.components.binary_sensor import (
    DEVICE_CLASS_MOTION,
    DEVICE_CLASS_OCCUPANCY,
    BinarySensorEntity,
)
from homeassistant.core import callback

from . import DOMAIN
from .entity import RingEntityMixin

# Sensor types: Name, category, device_class
SENSOR_TYPES = {
    "ding": ["Ding", ["doorbots", "authorized_doorbots"], DEVICE_CLASS_OCCUPANCY],
    "motion": [
        "Motion",
        ["doorbots", "authorized_doorbots", "stickup_cams"],
        DEVICE_CLASS_MOTION,
    ],
}

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Ring binary sensors from a config entry."""
    ring = hass.data[DOMAIN][config_entry.entry_id]["api"]
    devices = hass.data[DOMAIN][config_entry.entry_id]["devices"]

    sensors = []

    for device_type in ("doorbots", "authorized_doorbots", "stickup_cams"):
        for sensor_type in SENSOR_TYPES:
            if device_type not in SENSOR_TYPES[sensor_type][1]:
                continue

            for device in devices[device_type]:
                sensors.append(
                    RingBinarySensor(config_entry.entry_id, ring, device, sensor_type)
                )

    async_add_entities(sensors)

class RingBinarySensor(RingEntityMixin, BinarySensorEntity):
    """A binary sensor implementation for Ring device."""

    _active_alert = None

    def __init__(self, config_entry_id, ring, device, sensor_type):
        """Initialize a sensor for Ring device."""
        super().__init__(config_entry_id, device)
        self._ring = ring
        self._sensor_type = sensor_type
        self._name = "{} {}".format(self._device.name, SENSOR_TYPES.get(sensor_type)[0])
        self._device_class = SENSOR_TYPES.get(sensor_type)[2]
        self._state = None
        self._unique_id = f"{device.id}-{sensor_type}"
        self._update_alert()

    async def async_added_to_hass(self):
        """Register callbacks."""
        await super().async_added_to_hass()
        self.ring_objects["dings_data"].async_add_listener(self._dings_update_callback)
        self._dings_update_callback()

    async def async_will_remove_from_hass(self):
        """Disconnect callbacks."""
        await super().async_will_remove_from_hass()
        self.ring_objects["dings_data"].async_remove_listener(
            self._dings_update_callback
        )

    @callback
    def _dings_update_callback(self):
        """Call update method."""
        self._update_alert()
        self.async_write_ha_state()

    @callback
    def _update_alert(self):
        """Update active alert."""
        self._active_alert = next(
            (
                alert
                for alert in self._ring.active_alerts()
                if alert["kind"] == self._sensor_type
                and alert["doorbot_id"] == self._device.id
            ),
            None,
        )

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def is_on(self):
        """Return True if the binary sensor is on."""
        return self._active_alert is not None

    @property
    def device_class(self):
        """Return the class of the binary sensor."""
        return self._device_class

    @property
    def unique_id(self):
        """Return a unique ID."""
        return self._unique_id

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        attrs = super().device_state_attributes

        if self._active_alert is None:
            return attrs

        attrs["state"] = self._active_alert["state"]
        attrs["expires_at"] = datetime.fromtimestamp(
            self._active_alert.get("now") + self._active_alert.get("expires_in")
        ).isoformat()

        return attrs


text:
- Fixed an issue where multiple context results were outputted for the same incident id.
- Updated the Docker image to: *demisto/python3:3.8.6.13358*.


text:
namespace AppKit.Core.Requests.Paging
{
    public enum ResponsePageAddInfoType
    {
        Undefined = 0,
        TotalAmount = 1,
        IsLastPage = 2
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
	This XML file was automatically generated by UiBuilder - do not modify by hand.
-->
<string_table Bversion="2.0.6.v20120503" Dversion="20100701">
    <text id="IDS_FIELD_REQUIRED">Pflicht</text>
    <text id="IDS_TITLE_SETTINGS">Einstellungen</text>
    <text id="IDS_FIELD_ALARM_TIME">Vorher Alarmieren (in Minuten)</text>
    <text id="IDS_TITLE_EDIT_ITEM">Eintrag bearbeiten</text>
    <text id="IDS_IMPORTED_ITEMS">Einträge importiert</text>
    <text id="IDS_TITLE_NEW_ITEM">Neuer Eintrag</text>
    <text id="IDS_ERROR_EMPTY">kann nicht leer bleiben</text>
    <text id="IDS_BUTTON_TO">An</text>
    <text id="IDS_BUTTON_EMPTY">Leer</text>
    <text id="IDS_ERROR_NO_DATE">Feld ist leer oder ungültig</text>
    <text id="IDS_ERROR">Fehler</text>
    <text id="IDS_ERROR_EXPORT_FILE_NOT_FOUND">Datei 'export.db' konnte nicht gefunden werden</text>
    <text id="IDS_BUTTON_DELETE">Löschen</text>
    <text id="IDS_BUTTON_ALLOW_EXPORT">Mit Kalender verknüpfen</text>
    <text id="IDS_EXPORT">Export</text>
    <text id="IDS_BUTTON_ADD_TO_CALENDAR">Im Kalender eintragen</text>
    <text id="IDS_TITLE_CONTACTS">Kontakte</text>
    <text id="IDS_ERROR_END_BEFORE_START">Ende kann nicht vor dem Start sein</text>
    <text id="IDS_IMPORT">Import</text>
    <text id="IDS_BUTTON_IMPORT_DB">Datenbank importieren</text>
    <text id="IDS_BUTTON_FROM">Von</text>
    <text id="IDS_FIELD_NOTE_TEXT">Notizen können hier eingetragen werden</text>
    <text id="IDS_FIELD_END_DATE">Ende</text>
    <text id="IDS_FIELD_PERSON">Person</text>
    <text id="IDS_EXPORT_COMPLETED">Export abgeschlossen</text>
    <text id="IDS_FIELD_TITLE">Titel</text>
    <text id="IDS_IMPORTED_ITEM">Eintrag importiert</text>
    <text id="IDS_BUTTON_EDIT">Bearbeiten</text>
    <text id="IDS_BUTTON_SAVE">Speichern</text>
    <text id="IDS_BUTTON_EXPORT_DB">Datenbank exportieren</text>
    <text id="IDS_BUTTON_DISPLAY_ONLY">Nur Anzeige</text>
    <text id="IDS_IMPORT_COMPLETED">Import abgeschlossen\n</text>
    <text id="IDS_BUTTON_DISPLAY_SOUND">Anzeige und Ton</text>
    <text id="IDS_FIELD_PREVIEW">Vorschau</text>
    <text id="IDS_ERROR_UNKNOWN_ERROR">Unerwarteter Fehler ist aufgetreten</text>
    <text id="IDS_ERROR_IMPORT_FILE_CORRUPTED">File ist beschädigt\nImport wurde abgebrochen</text>
    <text id="IDS_FIELD_TYPE">Status</text>
    <text id="IDS_ERROR_EXPORT">Exportfehler</text>
    <text id="IDS_BUTTON_ADD">Neu</text>
    <text id="IDS_BUTTON_ENABLE_NOTIFY">Benachrichtigungen</text>
    <text id="IDS_ERROR_EXPORT_MISSING_PERMISSION">Fehlende Rechte um die Datei zu lesen/beschreiben</text>
    <text id="IDS_ERROR_IMPORT">Importfehler</text>
    <text id="IDS_BUTTON_CANCEL">Abbrechen</text>
    <text id="IDS_FIELD_START_DATE">Start</text>
    <text id="IDS_BUTTON_NO_ALARM">Kein Alarm</text>
</string_table>


text:
#ifndef __LIBXQ_H_INCLUDED__
#define __LIBXQ_H_INCLUDED__

/**
 * A library implementing a jQuery-like interface for working with XML
 */

#include <libxml/parser.h>
#include <libxml/tree.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
  XQ_OK = 0,
  XQ_OUT_OF_MEMORY,
  XQ_ARGUMENT_OUT_OF_BOUNDS,
  XQ_XML_PARSER_ERROR,
  XQ_NO_TOKEN, // this is an internal status code
  XQ_INVALID_SEL_UNTERMINATED_STR,
  XQ_INVALID_SEL_UNEXPECTED_TOKEN,
  XQ_NO_MATCH, // this is an internal status code
  XQ_UNKNOWN_NS_PREFIX
} xQStatusCode;

typedef struct _xQNodeList {
  xmlNodePtr* list;
  unsigned long capacity;
  unsigned long size;
} xQNodeList;

xQStatusCode xQNodeList_alloc_init(xQNodeList** list, unsigned long size);
xQStatusCode xQNodeList_init(xQNodeList* list, unsigned long size);
xQStatusCode xQNodeList_free(xQNodeList* list, int freeList);
xQStatusCode xQNodeList_insert(xQNodeList* list, xmlNodePtr node, unsigned long atIdx);
xQStatusCode xQNodeList_remove(xQNodeList* list, unsigned long fromIdx, unsigned long count);
xQStatusCode xQNodeList_assign(xQNodeList* toList, xQNodeList* fromList);
#define xQNodeList_push(list, node) (xQNodeList_insert(list, node, (list)->size))
#define xQNodeList_clear(list) ((list)->size = 0)

typedef struct _xQ {
  xmlDocPtr document;
  xQNodeList context;
  xmlHashTablePtr nsPrefixes;
} xQ;

xQStatusCode xQ_alloc_init(xQ** self);
xQStatusCode xQ_alloc_initDoc(xQ** self, xmlDocPtr doc);
xQStatusCode xQ_alloc_initFile(xQ** self, const char* filename, xmlDocPtr* doc);
xQStatusCode xQ_alloc_initMemory(xQ** self, const char* buffer, int size, xmlDocPtr* doc);
xQStatusCode xQ_alloc_initNodeList(xQ** self, xQNodeList* list);
xQStatusCode xQ_init(xQ* self);
xQStatusCode xQ_free(xQ* self, int freeXQ);
xQStatusCode xQ_children(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_closest(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_find(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_filter(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_next(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_nextAll(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_nextUntil(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_not(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_parent(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_parents(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_parentsUntil(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_prev(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_prevAll(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_prevUntil(xQ* self, const xmlChar* selector, xQ** result);
xQStatusCode xQ_clear(xQ* self);
unsigned long xQ_length(xQ* self);
xmlChar* xQ_getText(xQ* self);
xmlChar* xQ_getAttr(xQ* self, const char* name);
xmlChar* xQ_getXml(xQ* self);
xQStatusCode xQ_first(xQ* self, xQ** result);
xQStatusCode xQ_last(xQ* self, xQ** result);
xQStatusCode xQ_addNamespace(xQ* self, const xmlChar* prefix, const xmlChar* uri);
const xmlChar* xQ_namespaceForPrefix(xQ* self, const xmlChar* prefix);

typedef xQStatusCode (*xQSearchOp)(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
typedef struct _xQSearchExpr xQSearchExpr;
struct _xQSearchExpr {
  unsigned int argc;
  xmlChar** argv;
  xQSearchOp operation;
  xQSearchExpr* next;
};

xQStatusCode xQSearchExpr_alloc_init(xQSearchExpr** self, const xmlChar* expr);
xQStatusCode xQSearchExpr_alloc_initFilter(xQSearchExpr** self, const xmlChar* expr);
xQStatusCode xQSearchExpr_free(xQSearchExpr* self);
xQStatusCode xQSearchExpr_eval(xQSearchExpr* self, xQ* context, xmlNodePtr node, xQNodeList* outList);

xQStatusCode _xQ_findDescendants(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_findDescendantsByName(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_findChildrenByName(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_findNextSiblingByName(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_filterAttributeEquals(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_addToOutput(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);
xQStatusCode _xQ_filterByName(xQ* context, xmlChar** args, xmlNodePtr node, xQNodeList* outList);

extern const xmlChar* XQ_EMPTY_NAMESPACE;

#ifdef __cplusplus
}
#endif

#endif // __LIBXQ_H_INCLUDED__


text:
//
//     ____    _                        __     _      _____
//    / ___\  /_\     /\/\    /\ /\    /__\   /_\     \_   \
//    \ \    //_\\   /    \  / / \ \  / \//  //_\\     / /\/
//  /\_\ \  /  _  \ / /\/\ \ \ \_/ / / _  \ /  _  \ /\/ /_
//  \____/  \_/ \_/ \/    \/  \___/  \/ \_/ \_/ \_/ \____/
//
//	Copyright Samurai development team and other contributors
//
//	http://www.samurai-framework.com
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//

#import "Samurai_CSSStyleSheet.h"
#import "Samurai_CSSMediaQuery.h"
#import "Samurai_CSSParser.h"

#import "Samurai_CSSProtocol.h"
#import "Samurai_CSSRule.h"
#import "Samurai_CSSRuleSet.h"
#import "Samurai_CSSRuleCollector.h"

#import "_pragma_push.h"

#if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

// ----------------------------------
// Source code
// ----------------------------------

#pragma mark -

@interface SamuraiCSSStyleSheet ()
@prop_unsafe( KatanaOutput *,                   output );
@end

@implementation SamuraiCSSStyleSheet

@def_prop_unsafe( KatanaOutput *,               output );
@def_prop_strong( SamuraiCSSRuleSet *,			ruleSet );
@def_prop_strong( SamuraiCSSRuleCollector *,	collector );

- (id)init
{
	self = [super init];
	if ( self )
	{
		self.ruleSet = [[SamuraiCSSRuleSet alloc] init];
		self.collector = [[SamuraiCSSRuleCollector alloc] init];
	}
	return self;
}

- (void)dealloc
{
    if ( _output )
	{
        katana_destroy_output( _output );

        _output = NULL;
    }

	self.ruleSet = nil;
	self.collector = nil;
}

#pragma mark -

+ (NSArray *)supportedExtensions
{
	return [NSArray arrayWithObjects:@"css", nil];
}

+ (NSArray *)supportedTypes
{
	return [NSArray arrayWithObjects:@"text/css", nil];
}

+ (NSString *)baseDirectory
{
	return @"/www/css";
}

#pragma mark -

- (NSDictionary *)queryForObject:(NSObject<SamuraiCSSProtocol> *)object
{
	return [self.collector collectFromRuleSet:self.ruleSet forElement:object];
}

- (NSDictionary *)queryForString:(NSString *)string
{
	SamuraiCSSCondition * condition = [[SamuraiCSSCondition alloc] init];

	if ( [string hasPrefix:@"#"] )
	{
		condition.cssId = [string substringFromIndex:1];
	}
	else if ( [string hasPrefix:@"."] )
	{
		condition.cssClasses = [NSArray arrayWithObject:[string substringFromIndex:1]];
	}
	else
	{
		condition.cssTag = string;
	}

	return [self.collector collectFromRuleSet:self.ruleSet forElement:condition];
}

#pragma mark -

- (BOOL)parse
{
	if ( nil == self.resContent || 0 == [self.resContent length] )
	{
	//	return NO;
		return YES;
	}

	_output = [[SamuraiCSSParser sharedInstance] parseStylesheet:self.resContent];

	if ( _output )
	{
		KatanaStylesheet * stylesheet = _output->stylesheet;

		if ( stylesheet && stylesheet->imports.length )
		{
			/*
			for ( unsigned int i = 0; i < stylesheet->imports.length; i++ )
			{
				KatanaImportRule * rule = stylesheet->imports.data[i];

				if ( [[SamuraiCSSMediaQuery sharedInstance] testMediaQueries:rule->medias] )
				{
					SamuraiCSSStyleSheet * styleSheet = nil;

					NSString *	href = [NSString stringWithUTF8String:rule->href];
					NSString *	basePath = self.resPath;

					NSString *	fileName = [[href lastPathComponent] stringByDeletingPathExtension];
					NSString *	fileExt = [[href lastPathComponent] pathExtension];
					NSString *	filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExt];

					if ( filePath && [[NSFileManager defaultManager] fileExistsAtPath:filePath] )
					{
						styleSheet = [SamuraiCSSStyleSheet resourceAtPath:filePath];
					}
					else if ( [href hasPrefix:@"http://"] || [href hasPrefix:@"https://"] )
					{
						styleSheet = [SamuraiCSSStyleSheet resourceWithURL:href];
					}
					else if ( [href hasPrefix:@"//"] )
					{
						styleSheet = [SamuraiCSSStyleSheet resourceWithURL:[@"http:" stringByAppendingString:href]];
					}
					else if ( [basePath hasPrefix:@"http://"] || [basePath hasPrefix:@"https://"] )
					{
						NSURL * url = [NSURL URLWithString:href relativeToURL:[NSURL URLWithString:basePath]];

						styleSheet = [SamuraiCSSStyleSheet resourceWithURL:[url absoluteString]];
					}
					else
					{
						NSString * cssPath;

						cssPath = [basePath stringByDeletingLastPathComponent];
						cssPath = [cssPath stringByAppendingPathComponent:href];
						cssPath = [cssPath stringByStandardizingPath];

						styleSheet = [SamuraiCSSStyleSheet resourceAtPath:cssPath];
					}

					if ( styleSheet )
					{
						BOOL succeed = [styleSheet parse];
						if ( succeed )
						{
							[self.ruleSet mergeWithRuleSet:styleSheet.ruleSet];
						}
					}
				}
			}
			*/
		}

		if ( stylesheet && stylesheet->rules.length )
		{
			[self.ruleSet addStyleRules:&_output->stylesheet->rules];
		}
	}

	return YES;
}

- (void)merge:(SamuraiCSSStyleSheet *)styleSheet
{
	if ( nil == styleSheet )
		return;

	if ( NO == [styleSheet isKindOfClass:[SamuraiCSSStyleSheet class]] )
		return;

    if ( nil == styleSheet.output )
        return;

    [self.ruleSet addStyleRules:&styleSheet.output->stylesheet->rules];
}

- (void)clear
{
	[self.ruleSet clear];
}

@end

// ----------------------------------
// Unit test
// ----------------------------------

#pragma mark -

#if __SAMURAI_TESTING__

TEST_CASE( WebCore, CSSStyleSheet )

DESCRIBE( before )
{
}

DESCRIBE( after )
{
}

TEST_CASE_END

#endif	// #if __SAMURAI_TESTING__

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

#import "_pragma_pop.h"


text:
namespace VkNet.Model
{
    using VkNet.Utils;

    /// <summary>
    /// Текст аудиозаписи.
    /// См. описание <see href="http://vk.com/dev/audio.getLyrics"/>.
    /// </summary>
    public class Lyrics
    {
        /// <summary>
        /// Идентификатор текста аудиозаписи.
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// Тест аудиозаписи. В качестве переводов строк в тексте используется '\n'.
        /// </summary>
        public string Text { get; set; }

        #region Методы

        internal static Lyrics FromJson(VkResponse re)
        {
            var lyrics = new Lyrics();

            lyrics.Id = re["lyrics_id"];
            lyrics.Text = re["text"];

            return lyrics;
        }

        #endregion
    }
}


text:
{- Function that recurses into a directory tree,
 - and returns a list of the number of entries
 - it finds at each level of the tree -}

module CountEntries (listDirectory, countEntriesTrad) where

import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.FilePath ((</>))
import Control.Monad (forM, liftM)

listDirectory :: FilePath -> IO [String]
listDirectory = liftM (filter notDots) . getDirectoryContents
    where notDots p = p /= "." && p /= ".."

countEntriesTrad :: FilePath -> IO [(FilePath, Int)]
countEntriesTrad path = do
    contents <- listDirectory path
    rest     <- forM contents $ \name -> do
                  let newName = path </> name
                  isDir <- doesDirectoryExist newName
                  if isDir
                    then countEntriesTrad newName
                    else return []
    return $ (path, length contents) : concat rest


text:
layout: post
title: Testing 1-2
---

Hot mic? Hot mic.

Somewhere along the line
this just
kept
going.
Where to?

This is down below the break.


text:
/* eslint-disable import/namespace */
import * as ML from '..';

describe('Check all properties are defined', () => {
  it.each(Object.keys(ML))('Check %s', (key) => {
    expect(ML[key]).toBeDefined();
  });
});


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>contextmenu synthetic event</title>
        <meta name="author" content="Todd Kloots">

	   Button 1
	   <button type="button" id="btn-2">Click Me</button>


text:
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Input;
using System.Xml.Serialization;
using ACT.TTSYukkuri.Voiceroid;
using FFXIV.Framework.Common;
using Prism.Commands;
using Prism.Mvvm;
using RucheHome.Voiceroid;

namespace ACT.TTSYukkuri.Config
{
    [Serializable]
    public class VoiceroidConfig :
        BindableBase
    {
        public VoiceroidConfig()
        {
#if DEBUG
            if (WPFHelper.IsDesignMode)
            {
                var processes = (new ProcessFactory()).Processes;
                foreach (var inner in processes)
                {
                    this.Voiceroids.Add(new VoiceroidProcess()
                    {
                        InnerProcess = inner
                    });
                }
            }
#endif
        }

        private VoiceroidId selectedVoiceroidId = VoiceroidId.YukariEx;
        private ObservableCollection<VoiceroidProcess> voiceroids = new ObservableCollection<VoiceroidProcess>();
        private bool exitVoiceroidWhenExit = true;
        private bool directSpeak = true;

        public VoiceroidId SelectedVoiceroidId
        {
            get => this.selectedVoiceroidId;
            set => this.SetProperty(ref this.selectedVoiceroidId, value);
        }

        public ObservableCollection<VoiceroidProcess> Voiceroids => this.voiceroids;

        public bool ExitVoiceroidWhenExit
        {
            get => this.exitVoiceroidWhenExit;
            set => this.SetProperty(ref this.exitVoiceroidWhenExit, value);
        }

        public bool DirectSpeak
        {
            get => this.directSpeak;
            set => this.SetProperty(ref this.directSpeak, value);
        }

        public void Load()
        {
            var ctrl = SpeechController.Default as VoiceroidSpeechController;
            if (ctrl == null)
            {
                return;
            }

            foreach (var p in ctrl.ProcessFactory.Processes)
            {
                var voiceroid = this.Get(p.Id);
                if (voiceroid == null)
                {
                    voiceroid = new VoiceroidProcess();
                    this.Voiceroids.Add(voiceroid);
                }

                if (voiceroid.InnerProcess == null)
                {
                    voiceroid.InnerProcess = p;
                }
            }
        }

        public VoiceroidProcess Get(
            VoiceroidId id) =>
            this.Voiceroids.FirstOrDefault(x => x.Id == id);

        public VoiceroidProcess GetSelected() =>
            this.Get(this.SelectedVoiceroidId);

        public override string ToString() =>
            $"{nameof(this.SelectedVoiceroidId)}:{this.SelectedVoiceroidId}," +
            $"{nameof(this.DirectSpeak)}:{this.DirectSpeak}";
    }

    [Serializable]
    public class VoiceroidProcess :
        BindableBase
    {
        private IProcess innerProcess;
        private VoiceroidId id;
        private string name;
        private string path;

        [XmlIgnore]
        public IProcess InnerProcess
        {
            get => this.innerProcess;
            set
            {
                if (this.SetProperty(ref this.innerProcess, value))
                {
                    this.id = this.innerProcess.Id;
                    this.Name = this.innerProcess.Name;
                }
            }
        }

        public VoiceroidId Id
        {
            get => this.id;
            set => this.SetProperty(ref this.id, value);
        }

        public string Name
        {
            get => this.name;
            set => this.SetProperty(ref this.name, value);
        }

        public string Path
        {
            get => this.path;
            set
            {
                if (this.SetProperty(ref this.path, value))
                {
                    this.RaisePropertyChanged(nameof(this.IsFound));
                }
            }
        }

        public bool IsFound =>
            !string.IsNullOrEmpty(this.Path) && File.Exists(this.Path);

        private ICommand powerCommand;

        public ICommand PowerCommand =>
            this.powerCommand ?? (this.powerCommand = new DelegateCommand<VoiceroidProcess>(async (x) =>
            {
                if (x == null)
                {
                    return;
                }

                if (x.InnerProcess.IsRunning)
                {
                    await x.InnerProcess.Exit();
                }
                else
                {
                    if (x.IsFound)
                    {
                        await x.InnerProcess.Run(x.Path);
                    }
                }
            }));
    }
}


text:
using Portal.CMS.Entities;
using Portal.CMS.Entities.Entities;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace Portal.CMS.Services.Menu
{
    public interface IMenuItemService
    {
        Task<MenuItem> GetAsync(int menuItemId);

        Task<int> CreateAsync(int menuId, string linkText, string linkURL, string linkIcon);

        Task EditAsync(int menuItemId, string linkText, string linkURL, string linkIcon);

        Task DeleteAsync(int menuItemId);

        Task RolesAsync(int menuItemId, List<string> roleList);
    }

    public class MenuItemService : IMenuItemService
    {
        #region Dependencies

        readonly PortalEntityModel _context;

        public MenuItemService(PortalEntityModel context)
        {
            _context = context;
        }

        #endregion Dependencies

        public async Task<MenuItem> GetAsync(int menuItemId)
        {
            var menuItem = await _context.MenuItems.Include(x => x.Menu).SingleOrDefaultAsync(x => x.MenuItemId == menuItemId);

            return menuItem;
        }

        public async Task<int> CreateAsync(int menuId, string linkText, string linkURL, string linkIcon)
        {
            var newMenuItem = new MenuItem
            {
                MenuId = menuId,
                LinkText = linkText,
                LinkURL = linkURL,
                LinkIcon = linkIcon
            };

            _context.MenuItems.Add(newMenuItem);

            await _context.SaveChangesAsync();

            return newMenuItem.MenuItemId;
        }

        public async Task EditAsync(int menuItemId, string linkText, string linkURL, string linkIcon)
        {
            var menuItem = await _context.MenuItems.SingleOrDefaultAsync(x => x.MenuItemId == menuItemId);
            if (menuItem == null) return;

            menuItem.LinkText = linkText;
            menuItem.LinkURL = linkURL;
            menuItem.LinkIcon = linkIcon;

            await _context.SaveChangesAsync();
        }

        public async Task DeleteAsync(int menuItemId)
        {
            var menuItem = await _context.MenuItems.SingleOrDefaultAsync(x => x.MenuItemId == menuItemId);
            if (menuItem == null) return;

            _context.MenuItems.Remove(menuItem);

            await _context.SaveChangesAsync();
        }

        public async Task RolesAsync(int menuItemId, List<string> roleList)
        {
            var menuItem = await GetAsync(menuItemId);
            if (menuItem == null) return;

            var roles = await _context.Roles.ToListAsync();

            if (menuItem.MenuItemRoles != null)
                foreach (var role in menuItem.MenuItemRoles.ToList())
                    _context.MenuItemRoles.Remove(role);

            foreach (var roleName in roleList)
            {
                var currentRole = roles.FirstOrDefault(x => x.RoleName == roleName);

                if (currentRole == null) continue;

                _context.MenuItemRoles.Add(new MenuItemRole { MenuItemId = menuItemId, RoleId = currentRole.RoleId });
            }

            await _context.SaveChangesAsync();
        }
    }
}


text:
package example;

import java.io.IOException;
import java.util.*;

import org.apache.avro.*;
import org.apache.avro.Schema.Type;
import org.apache.avro.mapred.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

/**
 * The classic WordCount example modified to output Avro Pair<CharSequence,
 * Integer> records instead of text.
 */
public class AvroWordCount extends Configured implements Tool {

  public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter)
        throws IOException {
      String line = value.toString();
      StringTokenizer tokenizer = new StringTokenizer(line);
      while (tokenizer.hasMoreTokens()) {
        word.set(tokenizer.nextToken());
        output.collect(word, one);
      }
    }
  }

  public static class Reduce extends MapReduceBase
    implements Reducer<Text, IntWritable,
                       AvroWrapper<Pair<CharSequence, Integer>>, NullWritable> {

    public void reduce(Text key, Iterator<IntWritable> values,
        OutputCollector<AvroWrapper<Pair<CharSequence, Integer>>, NullWritable> output,
        Reporter reporter) throws IOException {
      int sum = 0;
      while (values.hasNext()) {
        sum += values.next().get();
      }
      output.collect(new AvroWrapper<Pair<CharSequence, Integer>>(
          new Pair<CharSequence, Integer>(key.toString(), sum)),
          NullWritable.get());
    }
  }

  public int run(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: AvroWordCount <input path> <output path>");
      return -1;
    }

    JobConf conf = new JobConf(AvroWordCount.class);
    conf.setJobName("wordcount");

    // We call setOutputSchema first so we can override the configuration
    // parameters it sets
    AvroJob.setOutputSchema(conf, Pair.getPairSchema(Schema.create(Type.STRING),
        Schema.create(Type.INT)));

    conf.setMapperClass(Map.class);
    conf.setReducerClass(Reduce.class);

    conf.setInputFormat(TextInputFormat.class);

    conf.setMapOutputKeyClass(Text.class);
    conf.setMapOutputValueClass(IntWritable.class);
    conf.setOutputKeyComparatorClass(Text.Comparator.class);

    FileInputFormat.setInputPaths(conf, new Path(args[0]));
    FileOutputFormat.setOutputPath(conf, new Path(args[1]));

    JobClient.runJob(conf);
    return 0;
  }

  public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new Configuration(), new AvroWordCount(), args);
    System.exit(res);
  }
}


text:
<?xml-stylesheet href="css3-modsel-38.css" type="text/css"?>
<test>

This very long paragraph should have a
      first line with green background. This very long paragraph should have a first
      line with green background.  This very long paragraph should have a first line
      with green background. This very long paragraph should have a first line with
      green background. This very long paragraph should have a first line with green
      background. This very long paragraph should have a first line with green background.
      This very long paragraph should have a first line with green background.

</test>


text:
namespace llvm {

class raw_ostream;
/// Construct a deterministic finite state automaton from possible
/// nondeterministic state and transition data.
///
/// The state type is a 64-bit unsigned integer. The generated automaton is
/// invariant to the sparsity of the state representation - its size is only
/// a function of the cardinality of the set of states.
///
/// The inputs to this emitter are considered to define a nondeterministic
/// finite state automaton (NFA). This is then converted to a DFA during
/// emission. The emitted tables can be used to by
/// include/llvm/Support/Automaton.h.
class DfaEmitter {
public:
  // The type of an NFA state. The initial state is always zero.
  using state_type = uint64_t;
  // The type of an action.
  using action_type = uint64_t;

  DfaEmitter() = default;
  virtual ~DfaEmitter() = default;

  void addTransition(state_type From, state_type To, action_type A);
  void emit(StringRef Name, raw_ostream &OS);

protected:
  /// Emit the C++ type of an action to OS.
  virtual void printActionType(raw_ostream &OS);
  /// Emit the C++ value of an action A to OS.
  virtual void printActionValue(action_type A, raw_ostream &OS);

private:
  /// The state type of deterministic states. These are only used internally to
  /// this class. This is an ID into the DfaStates UniqueVector.
  using dfa_state_type = unsigned;

  /// The actual representation of a DFA state, which is a union of one or more
  /// NFA states.
  using DfaState = SmallVector<state_type, 4>;

  /// A DFA transition consists of a set of NFA states transitioning to a
  /// new set of NFA states. The DfaTransitionInfo tracks, for every
  /// transitioned-from NFA state, a set of valid transitioned-to states.
  ///
  /// Emission of this transition relation allows algorithmic determination of
  /// the possible candidate NFA paths taken under a given input sequence to
  /// reach a given DFA state.
  using DfaTransitionInfo = SmallVector<std::pair<state_type, state_type>, 4>;

  /// The set of all possible actions.
  std::set<action_type> Actions;

  /// The set of nondeterministic transitions. A state-action pair can
  /// transition to multiple target states.
  std::map<std::pair<state_type, action_type>, std::vector<state_type>>
      NfaTransitions;
  std::set<state_type> NfaStates;
  unsigned NumNfaTransitions = 0;

  /// The set of deterministic states. DfaStates.getId(DfaState) returns an ID,
  /// which is dfa_state_type. Note that because UniqueVector reserves state
  /// zero, the initial DFA state is always 1.
  UniqueVector<DfaState> DfaStates;
  /// The set of deterministic transitions. A state-action pair has only a
  /// single target state.
  std::map<std::pair<dfa_state_type, action_type>,
           std::pair<dfa_state_type, DfaTransitionInfo>>
      DfaTransitions;

  /// Visit all NFA states and construct the DFA.
  void constructDfa();
  /// Visit a single DFA state and construct all possible transitions to new DFA
  /// states.
  void visitDfaState(const DfaState &DS);
};

} // namespace llvm

#endif


text:
package software.amazon.awssdk.enhanced.dynamodb.internal.converter;

import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;

/**
 * Interface for {@link StringConverter} and {@link AttributeConverter} implementations
 * that support boxed and primitive types.
 */
@SdkInternalApi
@ThreadSafe
public interface PrimitiveConverter<T> {
    /**
     * The type supported by this converter.
     */
    EnhancedType<T> primitiveType();
}


text:
FactoryBot.define do
  factory :block do
    content { 'MyText' }
    language { 'zh-TW' }
    page { 'night_market' }
    component_type { 'text' }
  end

  factory :text_block, parent: :block
  factory :twitch_live_block, parent: :block do
    component_type { 'twitch_live' }
  end
end


text:
namespace theia {

TEST(RemoveDisconnectedViewPairs, SingleConnectedComponent) {
  ViewGraph view_graph;
  TwoViewInfo info;
  view_graph.AddEdge(0, 1, info);
  view_graph.AddEdge(1, 2, info);
  view_graph.AddEdge(2, 3, info);

  const std::unordered_set<ViewId> removed_views =
      RemoveDisconnectedViewPairs(&view_graph);
  EXPECT_EQ(view_graph.NumEdges(), 3);
  EXPECT_EQ(removed_views.size(), 0);
}

TEST(RemoveDisconnectedViewPairs, TwoConnectedComponents) {
  ViewGraph view_graph;
  TwoViewInfo info;
  view_graph.AddEdge(0, 1, info);
  view_graph.AddEdge(1, 2, info);
  view_graph.AddEdge(2, 3, info);
  view_graph.AddEdge(5, 6, info);
  view_graph.AddEdge(6, 7, info);

  const std::unordered_set<ViewId> removed_views =
      RemoveDisconnectedViewPairs(&view_graph);
  EXPECT_EQ(view_graph.NumEdges(), 3);
  EXPECT_EQ(removed_views.size(), 3);
  EXPECT_TRUE(ContainsKey(removed_views, 5));
  EXPECT_TRUE(ContainsKey(removed_views, 6));
  EXPECT_TRUE(ContainsKey(removed_views, 7));
}

TEST(RemoveDisconnectedViewPairs, ThreeConnectedComponents) {
  ViewGraph view_graph;
  TwoViewInfo info;
  view_graph.AddEdge(0, 1, info);
  view_graph.AddEdge(1, 2, info);
  view_graph.AddEdge(2, 3, info);
  view_graph.AddEdge(5, 6, info);
  view_graph.AddEdge(7, 8, info);

  const std::unordered_set<ViewId> removed_views =
      RemoveDisconnectedViewPairs(&view_graph);
  EXPECT_EQ(view_graph.NumEdges(), 3);
  EXPECT_EQ(removed_views.size(), 4);
  EXPECT_TRUE(ContainsKey(removed_views, 5));
  EXPECT_TRUE(ContainsKey(removed_views, 6));
  EXPECT_TRUE(ContainsKey(removed_views, 7));
  EXPECT_TRUE(ContainsKey(removed_views, 8));
}

}  // namespace theia


text:
describe('Leniency', function() {
    integration(function() {
        describe('When playing Leniency', function() {
            beforeEach(function() {
                this.setupTest({
                    phase: 'conflict',
                    player1: {
                        inPlay: ['adept-of-the-waves'],
                        dynastyDeck: ['shiba-tsukune', 'shiba-peacemaker', 'naive-student', 'ethereal-dreamer'],
                        hand: ['leniency', 'assassination']
                    },
                    player2: {
                        hand: ['leniency', 'fine-katana', 'display-of-power'],
                        provinces: ['defend-the-wall'],
                        inPlay: ['shinjo-outrider'],
                        dynastyDeck: ['border-rider']
                    }
                });
                this.player1.placeCardInProvince('shiba-tsukune', 'province 1');
                this.player1.placeCardInProvince('shiba-peacemaker', 'province 2');
                this.player1.placeCardInProvince('naive-student', 'province 3');
                this.player1.placeCardInProvince('ethereal-dreamer', 'province 4');
                this.player2.placeCardInProvince('border-rider', 'province 1');
                this.etherealDreamer = this.player1.findCardByName('ethereal-dreamer');
                this.naiveStudent = this.player1.findCardByName('naive-student');
                this.borderRider = this.player2.findCardByName('border-rider');
                this.noMoreActions();
                this.initiateConflict({
                    type: 'military',
                    ring: 'earth',
                    province: 'defend-the-wall',
                    attackers: ['adept-of-the-waves'],
                    defenders: ['shinjo-outrider']
                });
            });

            it('should let you put ethereal dreamer into play instead of resolving the ring effect', function () {
                this.noMoreActions();
                this.player1.clickCard('leniency');
                expect(this.player1).toHavePrompt('Choose a character');
                this.player1.clickCard(this.etherealDreamer);
                expect(this.etherealDreamer.location).toBe('play area');
                expect(this.player1).toHavePrompt('Action Window');
            });

            it('should let you put a dash mil chararcter into play instead of resolving the ring effect', function () {
                this.noMoreActions();
                this.player1.clickCard('leniency');
                expect(this.player1).toHavePrompt('Choose a character');
                this.player1.clickCard(this.naiveStudent);
                expect(this.naiveStudent.location).toBe('play area');
                expect(this.player1).toHavePrompt('Action Window');
            });

            it('should work with defend the wall', function () {
                this.player2.playAttachment('fine-katana', 'shinjo-outrider');
                this.noMoreActions();
                this.player2.clickCard('defend-the-wall');
                this.player2.clickCard('leniency');
                expect(this.player2).toHavePrompt('Choose a character');
                this.player2.clickCard(this.borderRider);
                expect(this.borderRider.location).toBe('play area');
                expect(this.player1).toHavePrompt('Action Window');
            });

            it('should work with display of power', function () {
                this.player2.pass();
                this.player1.clickCard('assassination');
                this.player1.clickCard('shinjo-outrider', 'any', 'opponent');
                this.noMoreActions();
                expect(this.player2).toBeAbleToSelect('display-of-power');
                this.player2.clickCard('display-of-power');
                expect(this.player2).toBeAbleToSelect('leniency');
                this.player2.clickCard('leniency');
                expect(this.player2).toHavePrompt('Choose a character');
                this.player2.clickCard(this.borderRider);
                expect(this.borderRider.location).toBe('play area');
                expect(this.player1).toHavePrompt('Action Window');
            });
        });
    });
});


text:
package edu.uci.ics.hyracks.dataflow.std.sort;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;

import edu.uci.ics.hyracks.api.comm.IFrameReader;
import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparator;
import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
import edu.uci.ics.hyracks.api.dataflow.value.RecordDescriptor;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.api.io.FileReference;
import edu.uci.ics.hyracks.dataflow.common.comm.io.FrameTupleAccessor;
import edu.uci.ics.hyracks.dataflow.common.comm.io.FrameTupleAppender;
import edu.uci.ics.hyracks.dataflow.common.comm.util.FrameUtils;
import edu.uci.ics.hyracks.dataflow.common.io.RunFileWriter;

/**
 * @author pouria This class implements the run generator for sorting with
 *         replacement selection, where there is no limit on the output, i.e.
 *         the whole data should be sorted. A SortMinHeap is used as the
 *         selectionTree to decide the order of writing tuples into the runs,
 *         while memory manager is based on a binary search tree to allocate
 *         tuples in the memory. The overall process is as follows: - Read the
 *         input data frame by frame. For each tuple T in the current frame: -
 *         Try to allocate a memory slot for writing T along with the attached
 *         header/footer (for memory management purpose) - If T can not be
 *         allocated, try to output as many tuples, currently resident in
 *         memory, as needed so that a free slot, large enough to hold T, gets
 *         created. MinHeap decides about which tuple should be sent to the
 *         output at each step. - Write T into the memory - Calculate the runID
 *         of T (based on the last output tuple for the current run). It is
 *         either the current run or the next run. Also calculate Poorman's
 *         Normalized Key (PNK) for T, to make comparisons faster later. -
 *         Create a heap element for T, containing: its runID, the slot pointer
 *         to its memory location, and its PNK. - Insert the created heap
 *         element into the heap - Upon closing, write all the tuples, currently
 *         resident in memory, into their corresponding run(s). Again min heap
 *         decides about which tuple is the next for output.
 *         OptimizedSortOperatorDescriptor will merge the generated runs, to
 *         generate the final sorted output of the data.
 */
public class OptimizedExternalSortRunGenerator implements IRunGenerator {
    private final IHyracksTaskContext ctx;
    private final int[] sortFields;
    private final INormalizedKeyComputer nkc;
    private final IBinaryComparatorFactory[] comparatorFactories;
    private final IBinaryComparator[] comparators;
    private final RecordDescriptor recordDescriptor;
    private final List<IFrameReader> runs;

    private ISelectionTree sTree;
    private IMemoryManager memMgr;

    private final int memSize;
    private FrameTupleAccessor inputAccessor; // Used to read tuples in
                                              // nextFrame()
    private FrameTupleAppender outputAppender; // Used to write tuple to the
                                               // dedicated output buffer
    private ByteBuffer outputBuffer; // Dedicated output buffer to write tuples
                                     // into run(s)
    private FrameTupleAccessor lastRecordAccessor; // Used to read last output
                                                   // record from the output
                                                   // buffer
    private int lastTupleIx; // Holds index of last output tuple in the
                             // dedicated output buffer
    private Slot allocationPtr; // Contains the ptr to the allocated memory slot
                                // by the memory manager for the new tuple
    private Slot outputedTuple; // Contains the ptr to the next tuple chosen by
                                // the selectionTree to output
    private int[] sTreeTop;

    private RunFileWriter writer;

    private boolean newRun;
    private int curRunId;

    public OptimizedExternalSortRunGenerator(IHyracksTaskContext ctx, int[] sortFields,
            INormalizedKeyComputerFactory firstKeyNormalizerFactory, IBinaryComparatorFactory[] comparatorFactories,
            RecordDescriptor recordDesc, int memSize) {
        this.ctx = ctx;
        this.sortFields = sortFields;
        nkc = firstKeyNormalizerFactory == null ? null : firstKeyNormalizerFactory.createNormalizedKeyComputer();
        this.comparatorFactories = comparatorFactories;
        comparators = new IBinaryComparator[comparatorFactories.length];
        for (int i = 0; i < comparatorFactories.length; ++i) {
            comparators[i] = comparatorFactories[i].createBinaryComparator();
        }
        this.recordDescriptor = recordDesc;
        this.runs = new LinkedList<IFrameReader>();
        this.memSize = memSize;
    }

    @Override
    public void open() throws HyracksDataException {
        runs.clear();
        inputAccessor = new FrameTupleAccessor(ctx.getFrameSize(), recordDescriptor);
        outputAppender = new FrameTupleAppender(ctx.getFrameSize());
        outputBuffer = ctx.allocateFrame();
        outputAppender.reset(outputBuffer, true);
        lastRecordAccessor = new FrameTupleAccessor(ctx.getFrameSize(), recordDescriptor);

        this.memMgr = new BSTMemMgr(ctx, memSize);
        this.sTree = new SortMinHeap(ctx, sortFields, comparatorFactories, recordDescriptor, memMgr);
        this.allocationPtr = new Slot();
        this.outputedTuple = new Slot();
        this.sTreeTop = new int[] { -1, -1, -1, -1 };
        curRunId = -1;
        openNewRun();
    }

    @Override
    public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
        inputAccessor.reset(buffer);
        byte[] bufferArray = buffer.array();
        int tupleCount = inputAccessor.getTupleCount();
        for (int i = 0; i < tupleCount; ++i) {
            allocationPtr.clear();
            int tLength = inputAccessor.getTupleEndOffset(i) - inputAccessor.getTupleStartOffset(i);
            memMgr.allocate(tLength, allocationPtr);
            while (allocationPtr.isNull()) {
                int unAllocSize = -1;
                while (unAllocSize < tLength) {
                    unAllocSize = outputRecord();
                    if (unAllocSize < 1) {
                        throw new HyracksDataException(
                                "Unable to allocate space for the new tuple, while there is no more tuple to output");
                    }
                }
                memMgr.allocate(tLength, allocationPtr);
            }
            memMgr.writeTuple(allocationPtr.getFrameIx(), allocationPtr.getOffset(), inputAccessor, i);
            int runId = getRunId(inputAccessor, i);
            int pnk = getPNK(inputAccessor, i, bufferArray);
            int[] entry = new int[] { runId, allocationPtr.getFrameIx(), allocationPtr.getOffset(), pnk };
            sTree.insert(entry);
        }
    }

    @Override
    public void fail() throws HyracksDataException {
    }

    @Override
    public void close() throws HyracksDataException {
        while (!sTree.isEmpty()) { // Outputting remaining elements in the
                                   // selectionTree
            outputRecord();
        }
        if (outputAppender.getTupleCount() > 0) { // Writing out very last
                                                  // resident records to file
            FrameUtils.flushFrame(outputBuffer, writer);
        }
        outputAppender.reset(outputBuffer, true);
        writer.close();
        runs.add(writer.createReader());
        memMgr.close();
    }

    public List<IFrameReader> getRuns() {
        return runs;
    }

    private int outputRecord() throws HyracksDataException {
        outputedTuple.clear();
        sTree.getMin(sTreeTop);
        if (!isEntryValid(sTreeTop)) {
            throw new HyracksDataException("Invalid outputed tuple (Top of the selection tree is invalid)");
        }

        if (sTreeTop[SortMinHeap.RUN_ID_IX] != curRunId) { // We need to switch
                                                           // runs
            openNewRun();
        }

        int tFrameIx = sTreeTop[SortMinHeap.FRAME_IX];
        int tOffset = sTreeTop[SortMinHeap.OFFSET_IX];
        if (!memMgr.readTuple(tFrameIx, tOffset, outputAppender)) { // Can not
                                                                    // append to
                                                                    // the
                                                                    // tupleAppender
            FrameUtils.flushFrame(outputBuffer, writer);
            outputAppender.reset(outputBuffer, true);
            if (!memMgr.readTuple(tFrameIx, tOffset, outputAppender)) {
                throw new HyracksDataException("Can not append to the ouput buffer in sort");
            }
            lastTupleIx = 0;
        } else {
            lastTupleIx++;
        }
        outputedTuple.set(tFrameIx, tOffset);
        newRun = false;
        return memMgr.unallocate(outputedTuple);

    }

    private int getPNK(FrameTupleAccessor fta, int tIx, byte[] buffInArray) {
        // Moved buffInArray out for better performance (not converting for each and every tuple)
        int sfIdx = sortFields[0];
        int tStart = fta.getTupleStartOffset(tIx);
        int f0StartRel = fta.getFieldStartOffset(tIx, sfIdx);
        int f0EndRel = fta.getFieldEndOffset(tIx, sfIdx);
        int f0Start = f0StartRel + tStart + fta.getFieldSlotsLength();
        return (nkc == null ? 0 : nkc.normalize(buffInArray, f0Start, f0EndRel - f0StartRel));
    }

    private int getRunId(FrameTupleAccessor fta, int tupIx) throws HyracksDataException {
        // Comparing current record to last output record, it decides about current record's runId
        if (newRun) { // Very first record for a new run
            return curRunId;
        }

        byte[] lastRecBuff = outputBuffer.array();
        lastRecordAccessor.reset(outputBuffer);
        int lastStartOffset = lastRecordAccessor.getTupleStartOffset(lastTupleIx);

        ByteBuffer fr2 = fta.getBuffer();
        byte[] curRecBuff = fr2.array();
        int r2StartOffset = fta.getTupleStartOffset(tupIx);

        for (int f = 0; f < comparators.length; ++f) {
            int fIdx = sortFields[f];
            int f1Start = fIdx == 0 ? 0 : outputBuffer.getInt(lastStartOffset + (fIdx - 1) * 4);
            int f1End = outputBuffer.getInt(lastStartOffset + fIdx * 4);
            int s1 = lastStartOffset + lastRecordAccessor.getFieldSlotsLength() + f1Start;
            int l1 = f1End - f1Start;
            int f2Start = fIdx == 0 ? 0 : fr2.getInt(r2StartOffset + (fIdx - 1) * 4);
            int f2End = fr2.getInt(r2StartOffset + fIdx * 4);
            int s2 = r2StartOffset + fta.getFieldSlotsLength() + f2Start;
            int l2 = f2End - f2Start;
            int c = comparators[f].compare(lastRecBuff, s1, l1, curRecBuff, s2, l2);
            if (c != 0) {
                if (c <= 0) {
                    return curRunId;
                } else {
                    return (curRunId + 1);
                }
            }
        }
        return curRunId;
    }

    private void openNewRun() throws HyracksDataException {
        if (writer != null) { // There is a prev run, so flush its tuples and
                              // close it first
            if (outputAppender.getTupleCount() > 0) {
                FrameUtils.flushFrame(outputBuffer, writer);
            }
            outputAppender.reset(outputBuffer, true);
            writer.close();
            runs.add(writer.createReader());
        }

        FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(
                ExternalSortRunGenerator.class.getSimpleName());
        writer = new RunFileWriter(file, ctx.getIOManager());
        writer.open();
        curRunId++;
        newRun = true;
        lastTupleIx = -1;
    }

    private boolean isEntryValid(int[] entry) {
        return ((entry[SortMinHeap.RUN_ID_IX] > -1) && (entry[SortMinHeap.FRAME_IX] > -1) && (entry[SortMinHeap.OFFSET_IX] > -1));
    }
}


text: I hold helper methods for SFDiff classes.