text:
# vue-cli [![Build Status](https://img.shields.io/circleci/project/vuejs/vue-cli/master.svg)](https://circleci.com/gh/vuejs/vue-cli) [![npm package](https://img.shields.io/npm/v/vue-cli.svg)](https://www.npmjs.com/package/vue-cli)

A simple CLI for scaffolding Vue.js projects.

### Installation

Prerequisites: [Node.js](https://nodejs.org/en/) (>=4.x, 6.x preferred), npm version 3+ and [Git](https://git-scm.com/).

``` bash
$ npm install -g vue-cli
```

### Usage

``` bash
$ vue init <template-name> <project-name>
```

Example:

``` bash
$ vue init webpack my-project
```

The above command pulls the template from [vuejs-templates/webpack](https://github.com/vuejs-templates/webpack), prompts for some information, and generates the project at `./my-project/`.

### vue build

Use vue-cli as a zero-configuration development tool for your Vue apps and component, check out the [docs](/docs/build.md).

### Official Templates

The purpose of official Vue project templates are to provide opinionated, battery-included development tooling setups so that users can get started with actual app code as fast as possible. However, these templates are un-opinionated in terms of how you structure your app code and what libraries you use in addition to Vue.js.

All official project templates are repos in the [vuejs-templates organization](https://github.com/vuejs-templates). When a new template is added to the organization, you will be able to run `vue init <template-name> <project-name>` to use that template. You can also run `vue list` to see all available official templates.

Current available templates include:

- [webpack](https://github.com/vuejs-templates/webpack) - A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.

- [webpack-simple](https://github.com/vuejs-templates/webpack-simple) - A simple Webpack + vue-loader setup for quick prototyping.

- [browserify](https://github.com/vuejs-templates/browserify) - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.

- [browserify-simple](https://github.com/vuejs-templates/browserify-simple) - A simple Browserify + vueify setup for quick prototyping.

- [simple](https://github.com/vuejs-templates/simple) - The simplest possible Vue setup in a single HTML file

### Custom Templates

It's unlikely to make everyone happy with the official templates. You can simply fork an official template and then use it via `vue-cli` with:

``` bash
vue init username/repo my-project
```

Where `username/repo` is the GitHub repo shorthand for your fork.

The shorthand repo notation is passed to [download-git-repo](https://github.com/flipxfx/download-git-repo) so you can also use things like `bitbucket:username/repo` for a Bitbucket repo and `username/repo#branch` for tags or branches.

If you would like to download from a private repository use the `--clone` flag and the cli will use `git clone` so your SSH keys are used.

### Local Templates

Instead of a GitHub repo, you can also use a template on your local file system:

``` bash
vue init ~/fs/path/to-custom-template my-project
```

### Writing Custom Templates from Scratch

- A template repo **must** have a `template` directory that holds the template files.

- A template repo **may** have a metadata file for the template which can be either a `meta.js` or `meta.json` file. It can contain the following fields:

  - `prompts`: used to collect user options data;

  - `filters`: used to conditional filter files to render.

  - `metalsmith`: used to add custom metalsmith plugins in the chain.

  - `completeMessage`: the message to be displayed to the user when the template has been generated. You can include custom instruction here.

  - `complete`: Instead of using `completeMessage`, you can use a function to run stuffs when the template has been generated.

#### prompts

The `prompts` field in the metadata file should be an object hash containing prompts for the user. For each entry, the key is the variable name and the value is an [Inquirer.js question object](https://github.com/SBoudrias/Inquirer.js/#question). Example:

``` json
{
  "prompts": {
    "name": {
      "type": "string",
      "required": true,
      "message": "Project name"
    }
  }
}
```

After all prompts are finished, all files inside `template` will be rendered using [Handlebars](http://handlebarsjs.com/), with the prompt results as the data.

##### Conditional Prompts

A prompt can be made conditional by adding a `when` field, which should be a JavaScript expression evaluated with data collected from previous prompts. For example:

``` json
{
  "prompts": {
    "lint": {
      "type": "confirm",
      "message": "Use a linter?"
    },
    "lintConfig": {
      "when": "lint",
      "type": "list",
      "message": "Pick a lint config",
      "choices": [
        "standard",
        "airbnb",
        "none"
      ]
    }
  }
}
```

The prompt for `lintConfig` will only be triggered when the user answered yes to the `lint` prompt.

##### Pre-registered Handlebars Helpers

Two commonly used Handlebars helpers, `if_eq` and `unless_eq` are pre-registered:

``` handlebars
{{#if_eq lintConfig "airbnb"}};{{/if_eq}}
```

##### Custom Handlebars Helpers

You may want to register additional Handlebars helpers using the `helpers` property in the metadata file. The object key is the helper name:

``` js
module.exports = {
  helpers: {
    lowercase: str => str.toLowerCase()
  }
}
```

Upon registration, they can be used as follows:

``` handlebars
{{ lowercase name }}
```

#### File filters

The `filters` field in the metadata file should be an object hash containing file filtering rules. For each entry, the key is a [minimatch glob pattern](https://github.com/isaacs/minimatch) and the value is a JavaScript expression evaluated in the context of prompt answers data. Example:

``` json
{
  "filters": {
    "test/**/*": "needTests"
  }
}
```

Files under `test` will only be generated if the user answered yes to the prompt for `needTests`.

Note that the `dot` option for minimatch is set to `true` so glob patterns would also match dotfiles by default.

#### Skip rendering

The `skipInterpolation` field in the metadata file should be a [minimatch glob pattern](https://github.com/isaacs/minimatch). The files matched should skip rendering. Example:

``` json
{
  "skipInterpolation": "src/**/*.vue"
}
```

#### Metalsmith

`vue-cli` uses [metalsmith](https://github.com/segmentio/metalsmith) to generate the project.

You may customize the metalsmith builder created by vue-cli to register custom plugins.

```js
{
  "metalsmith": function (metalsmith, opts, helpers) {
    function customMetalsmithPlugin (files, metalsmith, done) {
      // Implement something really custom here.
      done(null, files)
    }

    metalsmith.use(customMetalsmithPlugin)
  }
}
```

If you need to hook metalsmith before questions are asked, you may use an object with `before` key.

```js
{
  "metalsmith": {
    before: function (metalsmith, opts, helpers) {},
    after: function (metalsmith, opts, helpers) {}
  }
}
```

#### Additional data available in meta.{js,json}

- `destDirName` - destination directory name

```json
{
  "completeMessage": "To get started:\n\n  cd {{destDirName}}\n  npm install\n  npm run dev"
}
```

- `inPlace` - generating template into current directory

```json
{
  "completeMessage": "{{#inPlace}}To get started:\n\n  npm install\n  npm run dev.{{else}}To get started:\n\n  cd {{destDirName}}\n  npm install\n  npm run dev.{{/inPlace}}"
}
```

### `complete` function

Arguments:

- `data`: the same data you can access in `completeMessage`:
  ```js
  {
    complete (data) {
      if (!data.inPlace) {
        console.log(`cd ${data.destDirName}`)
      }
    }
  }
  ```

- `helpers`: some helpers you can use to log results.
  - `chalk`: the `chalk` module
  - `logger`: [the built-in vue-cli logger](/lib/logger.js)
  - `files`: An array of generated files
  ```js
  {
    complete (data, {logger, chalk}) {
      if (!data.inPlace) {
        logger.log(`cd ${chalk.yellow(data.destDirName)}`)
      }
    }
  }
  ```

### Installing a specific template version

`vue-cli` uses the tool [`download-git-repo`](https://github.com/flipxfx/download-git-repo) to download the official templates used. The `download-git-repo` tool allows you to indicate a specific branch for a given repository by providing the desired branch name after a pound sign (`#`).

The format needed for a specific official template is:

```
vue init '<template-name>#<branch-name>' <project-name>
```

Example:

Installing the [`1.0` branch](https://github.com/vuejs-templates/webpack-simple/tree/1.0) of the webpack-simple vue template:

```
vue init 'webpack-simple#1.0' mynewproject
```

_Note_: The surrounding quotes are necessary on zsh shells because of the special meaning of the `#` character.

### License

[MIT](http://opensource.org/licenses/MIT)


text:
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Abot.Crawler;
using Abot.Poco;
using Autofac;
using HtmlAgilityPack;
using ItWebSite.Core.BLL;
using ItWebSite.Core.DbModel;
using ItWebSite.Core.IDAL;
using ItWebSite.Core.QueueDAL;
using ItWebSite.Crawler.Help;
using ItWebSite.Crawler.IDAL;

namespace ItWebSite.Crawler.DAL
{
    public class HandlerCsdnNews : HandlerBase
    {

        private static INewsTypeDal _newsTypeDal;
        private static string _newsTypeName = ConfigurationManager.AppSettings["CSDNNewsType"];

        public HandlerCsdnNews()
        {
            _newsTypeDal = Helper.Resolve<INewsTypeDal>();
        }

        private static DateTime GetCreateTime(HtmlDocument document)
        {
            var nodes = document.DocumentNode.SelectNodes("//span").Where(t => t.Attributes.Any(s => s.Name == "class" && s.Value == "ago"));
            var node = nodes.SingleOrDefault(t => ConvertToDateTime(t.InnerText) != DateTime.MinValue);
            if (node != null)
                return ConvertToDateTime(node.InnerText);
            return DateTime.Now;
        }

        private static DateTime ConvertToDateTime(string value)
        {
            DateTime result;
            if (DateTime.TryParse(value, out result))
                return result;
            return DateTime.MinValue;
        }

        public override bool SaveContent(CrawledPage crawledPage)
        {

            try
            {
                if (crawledPage.Uri.ToString().Contains("http://www.csdn.net/article"))
                    return SaveCsdnNews(crawledPage);
            }
            catch (Exception ex)
            {
                LogInfoQueue.Instance.Insert(typeof(HandlerCsdnNews), MethodBase.GetCurrentMethod().Name, ex);
                return false;
            }
            return true;
        }

        private bool SaveCsdnNews(CrawledPage crawledPage)
        {
            try
            {
                if (!crawledPage.Uri.ToString().Contains("http://www.csdn.net/article")) return false;
                var document = new HtmlDocument();
                document.LoadHtml(crawledPage.Content.Text);
                var title = document.DocumentNode.SelectNodes("//h1").SingleOrDefault(t => t.Attributes.Any(s => s.Name == "class" && s.Value == "title"));
                var body = document.DocumentNode.SelectSingleNode("//body");
                var summary = body.SelectNodes("//div").SingleOrDefault(t => t.Attributes.Any(s => s.Name == "class" && s.Value == "summary"));
                var createTime = GetCreateTime(document);
                body = body.SelectNodes("//div").SingleOrDefault(t => t.Attributes.Any(s => s.Name == "class" && s.Value == "con news_content"));
                if (title == null || body == null || string.IsNullOrEmpty(crawledPage.Uri.ToString()))
                    return false;
                if (_isSaveLocalFile)
                    SaveFile(title.InnerText, body.InnerHtml);
                SaveNews(title.InnerText, summary == null ? string.Empty : summary.InnerHtml, body.InnerHtml, crawledPage.Uri.ToString(), createTime);
                return true;
            }
            catch (Exception ex)
            {
                LogInfoQueue.Instance.Insert(typeof(HandlerCsdnNews), MethodBase.GetCurrentMethod().Name, ex);
                return false;
            }
        }

        private void SaveFile(string title, string body)
        {
            var filePath = Path.Combine(SavePath(), title + ".html");
            try
            {
                using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    writer.Write(body);
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                LogInfoQueue.Instance.Insert(typeof(HandlerCsdnNews), MethodBase.GetCurrentMethod().Name, ex);
            }
        }

        private void SaveNews(string title, string summary, string body, string sourceUrl, DateTime createTime)
        {
            var typeId = GetNewsTypeId(_newsTypeName);
            var entity = new NewsCsdn
            {
                NewsTypeId = typeId,
                Content = body,
                Creater = "snbbdx@sina.com",
                LastModifier = "snbbdx@sina.com",
                CreateDate = createTime,
                LastModifyDate = createTime,
                DisplayOrder = 1,
                Title = title,
                NewsFrom = "CSDN",
                NewsFromUrl = sourceUrl,
                Summary = summary
            };
            HandlerQueue.Instance.Add(entity);
        }

        private static int? _newsTypeId = null;

        private static object _syncTypeId = new object();

        private int GetNewsTypeId(string typeName)
        {
            lock (_syncTypeId)
            {
                if (_newsTypeId == null)
                {
                    _newsTypeId = GetNewsTypeIdFromDb(typeName);
                }
                return (int)_newsTypeId;
            }
        }

        private int GetNewsTypeIdFromDb(string typeName)
        {
            var entityList = _newsTypeDal.QueryByFun(t => t.Name == typeName);
            if (entityList.Any())
            {
                return entityList.First().Id;
            }
            return _newsTypeDal.Insert(new NewsType()
            {
                Creater = "snbbdx@sina.com",
                LastModifier = "snbbdx@sina.com",
                CreateDate = DateTime.Now,
                LastModifyDate = DateTime.Now,
                Name = typeName
            });
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
NSString *OrgBouncycastleMathEcFixedPointUtil_PRECOMP_NAME_ = @"bc_fixed_point";

@implementation OrgBouncycastleMathEcFixedPointUtil

+ (jint)getCombSizeWithOrgBouncycastleMathEcECCurve:(OrgBouncycastleMathEcECCurve *)c {
  return OrgBouncycastleMathEcFixedPointUtil_getCombSizeWithOrgBouncycastleMathEcECCurve_(c);
}

+ (OrgBouncycastleMathEcFixedPointPreCompInfo *)getFixedPointPreCompInfoWithOrgBouncycastleMathEcPreCompInfo:(id<OrgBouncycastleMathEcPreCompInfo>)preCompInfo {
  return OrgBouncycastleMathEcFixedPointUtil_getFixedPointPreCompInfoWithOrgBouncycastleMathEcPreCompInfo_(preCompInfo);
}

+ (OrgBouncycastleMathEcFixedPointPreCompInfo *)precomputeWithOrgBouncycastleMathEcECPoint:(OrgBouncycastleMathEcECPoint *)p
                                                                                withInt:(jint)minWidth {
  return OrgBouncycastleMathEcFixedPointUtil_precomputeWithOrgBouncycastleMathEcECPoint_withInt_(p, minWidth);
}

- (instancetype)init {
  OrgBouncycastleMathEcFixedPointUtil_init(self);
  return self;
}

@end

jint OrgBouncycastleMathEcFixedPointUtil_getCombSizeWithOrgBouncycastleMathEcECCurve_(OrgBouncycastleMathEcECCurve *c) {
  OrgBouncycastleMathEcFixedPointUtil_initialize();
  JavaMathBigInteger *order = [((OrgBouncycastleMathEcECCurve *) nil_chk(c)) getOrder];
  return order == nil ? [c getFieldSize] + 1 : [order bitLength];
}

OrgBouncycastleMathEcFixedPointPreCompInfo *OrgBouncycastleMathEcFixedPointUtil_getFixedPointPreCompInfoWithOrgBouncycastleMathEcPreCompInfo_(id<OrgBouncycastleMathEcPreCompInfo> preCompInfo) {
  OrgBouncycastleMathEcFixedPointUtil_initialize();
  if ((preCompInfo != nil) && ([preCompInfo isKindOfClass:[OrgBouncycastleMathEcFixedPointPreCompInfo class]])) {
    return (OrgBouncycastleMathEcFixedPointPreCompInfo *) check_class_cast(preCompInfo, [OrgBouncycastleMathEcFixedPointPreCompInfo class]);
  }
  return new_OrgBouncycastleMathEcFixedPointPreCompInfo_init();
}

OrgBouncycastleMathEcFixedPointPreCompInfo *OrgBouncycastleMathEcFixedPointUtil_precomputeWithOrgBouncycastleMathEcECPoint_withInt_(OrgBouncycastleMathEcECPoint *p, jint minWidth) {
  OrgBouncycastleMathEcFixedPointUtil_initialize();
  OrgBouncycastleMathEcECCurve *c = [((OrgBouncycastleMathEcECPoint *) nil_chk(p)) getCurve];
  jint n = LShift32(1, minWidth);
  OrgBouncycastleMathEcFixedPointPreCompInfo *info = OrgBouncycastleMathEcFixedPointUtil_getFixedPointPreCompInfoWithOrgBouncycastleMathEcPreCompInfo_([((OrgBouncycastleMathEcECCurve *) nil_chk(c)) getPreCompInfoWithOrgBouncycastleMathEcECPoint:p withNSString:OrgBouncycastleMathEcFixedPointUtil_PRECOMP_NAME_]);
  IOSObjectArray *lookupTable = [((OrgBouncycastleMathEcFixedPointPreCompInfo *) nil_chk(info)) getPreComp];
  if (lookupTable == nil || lookupTable->size_ < n) {
    jint bits = OrgBouncycastleMathEcFixedPointUtil_getCombSizeWithOrgBouncycastleMathEcECCurve_(c);
    jint d = (bits + minWidth - 1) / minWidth;
    IOSObjectArray *pow2Table = [IOSObjectArray newArrayWithLength:minWidth type:OrgBouncycastleMathEcECPoint_class_()];
    (void) IOSObjectArray_Set(pow2Table, 0, p);
    for (jint i = 1; i < minWidth; ++i) {
      (void) IOSObjectArray_Set(pow2Table, i, [((OrgBouncycastleMathEcECPoint *) nil_chk(IOSObjectArray_Get(pow2Table, i - 1))) timesPow2WithInt:d]);
    }
    [c normalizeAllWithOrgBouncycastleMathEcECPointArray:pow2Table];
    lookupTable = [IOSObjectArray newArrayWithLength:n type:OrgBouncycastleMathEcECPoint_class_()];
    (void) IOSObjectArray_Set(lookupTable, 0, [c getInfinity]);
    for (jint bit = minWidth - 1; bit >= 0; --bit) {
      OrgBouncycastleMathEcECPoint *pow2 = IOSObjectArray_Get(pow2Table, bit);
      jint step = LShift32(1, bit);
      for (jint i = step; i < n; i += (LShift32(step, 1))) {
        (void) IOSObjectArray_Set(lookupTable, i, [((OrgBouncycastleMathEcECPoint *) nil_chk(IOSObjectArray_Get(lookupTable, i - step))) addWithOrgBouncycastleMathEcECPoint:pow2]);
      }
    }
    [c normalizeAllWithOrgBouncycastleMathEcECPointArray:lookupTable];
    [info setPreCompWithOrgBouncycastleMathEcECPointArray:lookupTable];
    [info setWidthWithInt:minWidth];
    [c setPreCompInfoWithOrgBouncycastleMathEcECPoint:p withNSString:OrgBouncycastleMathEcFixedPointUtil_PRECOMP_NAME_ withOrgBouncycastleMathEcPreCompInfo:info];
  }
  return info;
}

void OrgBouncycastleMathEcFixedPointUtil_init(OrgBouncycastleMathEcFixedPointUtil *self) {
  (void) NSObject_init(self);
}

OrgBouncycastleMathEcFixedPointUtil *new_OrgBouncycastleMathEcFixedPointUtil_init() {
  OrgBouncycastleMathEcFixedPointUtil *self = [OrgBouncycastleMathEcFixedPointUtil alloc];
  OrgBouncycastleMathEcFixedPointUtil_init(self);
  return self;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgBouncycastleMathEcFixedPointUtil)


text:
Munin plugin for monitoring count lines in log file

To install copy log_lines file to munin plugins directory (In common systems is ```/etc/munin/plugins/```). Make sure it has executable flag.
Then change LOG_FILE variable in this file to desired log file path.


text:
{% extends 'base_app.html' %}

{% block title %}{% trans 'Create user' %}{% endblock title %}

{% block content %}

{% trans 'Create user' %} {{ username }}

{% crispy form %}
{% endblock content %}


text:
module Fastlane
  module Actions
    class LastGitTagAction < Action
      def self.run(params)
        Actions.last_git_tag_name
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Get the most recent git tag"
      end

      def self.available_options
        []
      end

      def self.output
        []
      end

      def self.authors
        ["KrauseFx"]
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end


text:
package xyz.white.editor.events.attrs;

import com.badlogic.gdx.scenes.scene2d.Actor;
import xyz.white.editor.events.Event;
import xyz.white.editor.events.SelectedActorEvent;

/**
 * Created by 10037 on 2017/4/23 0023.
 */
public class ActorRotationEvent extends SelectedActorEvent {
    public float rotation,orginRotation;
    private Actor actor;

    public ActorRotationEvent(float rotation){
        this.rotation = rotation;
    }

    @Override
    public Event redo() {
        if (actor == null){
            actor = selectGroup.getLastSelectActor();
            orginRotation = actor.getRotation();
        }
        if (actor == null){
            isUndo = false;
            return this;
        }
        isUndo = true;
        actor.setRotation(rotation);
        return this;
    }

    @Override
    public Event undo() {
        actor.setRotation(orginRotation);
        return this;
    }
}


text:
import React from 'react'
import styles from '../css/footer.module.css'
import cx from 'classnames'
import {prefixLink} from "gatsby-helpers";
import {Link} from 'react-router'

import FaFacebook from 'react-icons/lib/fa/facebook'
import FaTwitter from 'react-icons/lib/fa/twitter'

export default class Footer extends React.Component {

  render() {
    return (

            The goal is not to do business
            with everybody who needs what we do.

            The goal is to do business
            with people who believe what we believe.

            Ir al inicio

Síguenos

                    <FaFacebook className={styles.icon}/>

                {/*
*/}
                {/**/}
                {/*<FaTwitter className={styles.icon}/>*/}
                {/**/}

                {/*
*/}

                Grupo Alameda S.A.C

              <address >
                Modesto Calle Basadre 723, Tacna- Perú

                052 285395

                  informes@grupoalameda.pe

              </address>

            <Link to={prefixLink("/")} className="footer__copy">© Grupo Alameda 2017</Link>
            Industria y Comunicación Gráfica

    )
  }

}


text:
package swarm.server.app;

import swarm.shared.json.A_JsonFactory;
import swarm.shared.json.JsonHelper;

public abstract class A_ServerJsonFactory extends A_JsonFactory
{
	public abstract void startScope(boolean verboseKeys);

	public abstract void endScope();
}


text:
rm CMakeCache.txt
rm -rf CMakeFiles
rm Makefile
rm tsu-*
rm cmake_install.cmake


text:
<?php

return [
    'app' => [
        'name' => 'OctoberCMS',
        'tagline' => 'Retourner à l'essentiel',
    ],
    'directory' => [
        'create_fail' => "Impossible de créer le répertoire : :name",
    ],
    'file' => [
        'create_fail' => "Impossible de créer le fichier : :name",
    ],
    'combiner' => [
        'not_found' => "Le fichier combiné ':name' est introuvable.",
    ],
    'system' => [
        'name' => 'Système',
        'menu_label' => 'Système',
        'categories' => [
            'cms' => 'CMS',
            'misc' => 'Divers',
            'logs' => 'Journaux',
            'mail' => 'E-mail',
            'shop' => 'Boutique',
            'team' => 'Équipe',
            'users' => 'Utilisateurs',
            'system' => 'Système',
            'social' => 'Social',
            'events' => 'Évènements',
            'customers' => 'Clients',
            'my_settings' => 'Mes réglages',
        ]
    ],
    'theme' => [
        'label' => 'Thème',
        'unnamed' => 'Thème sans nom',
        'name' => [
            'label' => 'Nom du thème',
            'help' => 'Nommer le thème avec un nom de code unique. Par exemple, RainLab.Vanilla'
        ],
    ],
    'themes' => [
        'install' => 'Installer des thèmes',
        'search' => 'Recherche des thème à installer…',
        'installed' => 'Thèmes installés',
        'no_themes' => 'Il n'y a aucun thème installé depuis le Marketplace.',
        'recommended' => 'Recommandé',
        'remove_confirm' => 'Êtes-vous sûr(e) de vouloir supprimer ce thème ?'
    ],
    'plugin' => [
        'label' => 'Plugin',
        'unnamed' => 'Plugin sans nom',
        'name' => [
            'label' => 'Nom du plugin',
            'help' => 'Nommer le plugin avec un nom de code unique. Par exemple, RainLab.Blog',
        ],
    ],
    'plugins' => [
        'manage' => 'Gérer les plugins',
        'enable_or_disable' => 'Activer ou désactiver',
        'enable_or_disable_title' => 'Activer ou désactiver les plugins',
        'install' => 'Installer des plugins',
        'install_products' => 'Installer des produits',
        'search' => 'Recherche des plugins à installer…',
        'installed' => 'Plugins installés',
        'no_plugins' => 'Il n'y a aucun plugin installé depuis le site d'October CMS.',
        'recommended' => 'Recommandé',
        'remove' => 'Supprimer',
        'refresh' => 'Actualiser',
        'disabled_label' => 'Désactivé',
        'disabled_help' => 'Les plugins désactivés sont ignorés par l'application.',
        'frozen_label' => 'Mises à jour bloquées',
        'frozen_help' => 'Les plugins bloqués seront ignorés par le processus de mise à jour.',
        'selected_amount' => 'Plugins sélectionnés : :amount',
        'remove_confirm' => 'Êtes-vous sûr(e) de vouloir supprimer ce plugin ?',
        'remove_success' => "Les plugins ont été supprimés avec succès.",
        'refresh_confirm' => 'Êtes-vous sûr(e) ?',
        'refresh_success' => "Les plugins ont été actualisés avec succès.",
        'disable_confirm' => 'Êtes-vous sûr(e) ?',
        'disable_success' => "Les plugins ont été désactivés avec succès.",
        'enable_success' => "Les plugins ont été activés avec succès.",
        'unknown_plugin' => 'Le plugin a été supprimé du système de fichiers.'
    ],
    'project' => [
        'name' => 'Projet',
        'owner_label' => 'Auteur',
        'attach' => 'Attacher un projet',
        'detach' => 'Détacher le Projet',
        'none' => 'Aucun',
        'id' => [
            'label' => 'ID du projet',
            'help' => 'Comment trouver l'ID de votre projet',
            'missing' => 'Spécifier un ID de projet.',
        ],
        'detach_confirm' => 'Confirmer le détachement de ce projet ?',
        'unbind_success' => 'Le projet a été détaché avec succès.',
    ],
    'settings' => [
        'menu_label' => 'Réglages',
        'not_found' => 'Les paramètres spécifiés sont introuvables.',
        'missing_model' => 'La page de réglages nécessite la définition d'un Model.',
        'update_success' => 'Les réglages pour :name ont étés mis à jour avec succès.',
        'return' => 'Retourner à la page des réglages du système',
        'search' => 'Rechercher'
    ],
    'mail' => [
        'log_file' => 'Fichier journal',
        'menu_label' => 'Configuration des adresses e-mails',
        'menu_description' => 'Gérer la configuration des adresses e-mails.',
        'general' => 'Général',
        'method' => 'Méthode d'envoi',
        'sender_name' => 'Nom de l'expéditeur',
        'sender_email' => 'Adresse e-mail de l'expéditeur',
        'php_mail' => 'Fonction mail de PHP',
        'smtp' => 'SMTP',
        'smtp_address' => 'Adresse SMTP',
        'smtp_authorization' => 'Authentification SMTP requise',
        'smtp_authorization_comment' => 'Cocher cette case si le serveur SMTP nécessite une authentification.',
        'smtp_username' => 'Identifiant',
        'smtp_password' => 'Mot de passe',
        'smtp_port' => 'Port SMTP',
        'smtp_ssl' => 'Connexion SSL requise',
        'smtp_encryption' => 'Protocole de sécurisation des échanges SMTP',
        'smtp_encryption_none' => 'Aucun cryptage',
        'smtp_encryption_tls' => 'TLS',
        'smtp_encryption_ssl' => 'SSL',
        'sendmail' => 'Sendmail',
        'sendmail_path' => 'Chemin vers Sendmail',
        'sendmail_path_comment' => 'Saisir le chemin du programme sendmail.',
        'mailgun' => 'Mailgun',
        'mailgun_domain' => 'Domaine Mailgun',
        'mailgun_domain_comment' => 'Saisir le nom de domaine Mailgun.',
        'mailgun_secret' => 'Clé secrète Mailgun',
        'mailgun_secret_comment' => 'Saisir votre clé API Mailgun.',
        'mandrill' => 'Mandrill',
        'mandrill_secret' => 'Clé secrète Mandrill',
        'mandrill_secret_comment' => 'Saisir votre clé API Mandrill.',
        'ses' => 'SES',
        'ses_key' => 'Clé SES',
        'ses_key_comment' => 'Saisir votre clé API SES',
        'ses_secret' => 'Clé secrète SES',
        'ses_secret_comment' => 'Saisir votre clé secrète de l'API SES',
        'ses_region' => 'Région SES',
        'ses_region_comment' => 'Saisir votre région SES (e.g. us-east-1)',
        'drivers_hint_header' => 'Les drivers ne sont pas installés',
        'drivers_hint_content' => 'Cette méthode d'envoi d'e-mails nécessite que le plugin ":plugin" soit installé avant de pouvoir envoyer des e-mails.'
    ],
    'mail_templates' => [
        'menu_label' => 'Modèles des e-mails',
        'menu_description' => 'Gérer les modèles et maquettes des e-mails envoyés aux utilisateurs et aux administrateurs.',
        'new_template' => 'Nouveau modèle',
        'new_layout' => 'Nouvelle maquette',
        'template' => 'Modèle',
        'templates' => 'Modèles',
        'menu_layouts_label' => 'Maquettes des e-mails',
        'layout' => 'Maquette',
        'layouts' => 'Maquettes',
        'no_layout' => '-- Aucune maquette --',
        'name' => 'Nom',
        'name_comment' => 'Nom unique utilisé pour identifier ce modèle',
        'code' => 'Code',
        'code_comment' => 'Code unique utilisé pour identifier ce modèle',
        'subject' => 'Sujet',
        'subject_comment' => 'Sujet de l'e-mail',
        'description' => 'Description',
        'content_html' => 'HTML',
        'content_css' => 'CSS',
        'content_text' => 'Texte brut',
        'test_send' => 'Envoyer un message de test',
        'test_success' => 'Le message de test a été envoyé avec succès.',
        'test_confirm' => 'Un message de test sera envoyé à :email. Continuer ?',
        'creating' => 'Création du modèle...',
        'creating_layout' => 'Création de la maquette...',
        'saving' => 'Sauvegarde du modèle en cours…',
        'saving_layout' => 'Enregistrement de la maquette...',
        'delete_confirm' => 'Supprimer ce modèle ?',
        'delete_layout_confirm' => 'Supprimer cette maquette ?',
        'deleting' => 'Suppression du modèle...',
        'deleting_layout' => 'Suppression de la maquette...',
        'sending' => 'Envoi du message de test en cours…',
        'return' => 'Retour à la liste des modèles.',
    ],
    'install' => [
        'project_label' => 'Attacher un projet',
        'plugin_label' => 'Installer un plugin',
        'theme_label' => 'Installer un thème',
        'missing_plugin_name' => 'Saisir le nom d'un plugin à installer.',
        'missing_theme_name' => 'Saisir le nom d'un thème à installer.',
        'install_completing' => 'Fin du processus d'installation',
        'install_success' => 'Le plugin a été installé avec succès.',
    ],
    'updates' => [
        'title' => 'Gérer les mises à jour',
        'name' => 'Mise à jour',
        'menu_label' => 'Mise à jour',
        'menu_description' => 'Mise à jour du système, gestion et installation des plugins et thèmes.',
        'return_link' => 'Retourner aux mises à jour du système',
        'check_label' => 'Vérifier les mises à jour',
        'retry_label' => 'Réessayer',
        'plugin_name' => 'Nom',
        'plugin_code' => 'Code',
        'plugin_description' => 'Description',
        'plugin_version' => 'Version',
        'plugin_author' => 'Auteur',
        'plugin_not_found' => 'Plugin not found',
        'core_current_build' => 'Version actuelle',
        'core_build' => 'Version :build',
        'core_build_help' => 'Une nouvelle version est disponible.',
        'core_downloading' => 'Téléchargement des fichiers de l'application',
        'core_extracting' => 'Décompression des fichiers de l'application',
        'plugins' => 'Plugins',
        'themes' => 'Thèmes',
        'disabled' => 'Désactivé',
        'plugin_downloading' => 'Téléchargement du plugin : :name',
        'plugin_extracting' => 'Décompression du plugin : :name',
        'plugin_version_none' => 'Nouveau plugin',
        'plugin_current_version' => 'Version actuelle',
        'theme_new_install' => 'Installation du nouveau thème.',
        'theme_downloading' => 'Téléchargement du thème : :name',
        'theme_extracting' => 'Décompression du thème : :name',
        'update_label' => 'Mettre à jour',
        'update_completing' => 'Finalisation du processus de mise à jour',
        'update_loading' => 'Chargement des mises à jour disponibles…',
        'update_success' => 'Mise à jour terminée avec succès.',
        'update_failed_label' => 'Échec de la mise à jour',
        'force_label' => 'Forcer la mise à jour',
        'found' => [
            'label' => 'Nouvelle mise à jour disponible !',
            'help' => 'Cliquer sur « Mettre à jour » pour démarrer le processus.',
        ],
        'none' => [
            'label' => 'Aucune mise à jour n'est disponible.',
            'help' => 'Aucune mise à jour plus récente n'a été trouvée.',
        ],
        'important_action' => [
            'empty' => 'Sélectionner l'action',
            'confirm' => 'Confirmer la mise à jour',
            'skip' => 'Ignorer ce plugin (cette fois uniquement)',
            'ignore' => 'Ignorer ce plugin (toujours)',
        ],
        'important_action_required' => 'Action requise',
        'important_view_guide' => 'Consulter le guide de mise à jour',
        'important_alert_text' => 'Des mise à jour requièrent votre attention.',
        'details_title' => 'Détails du plugin',
        'details_view_homepage' => 'Voir la page d'accueil',
        'details_readme' => 'Documentation',
        'details_readme_missing' => 'Aucune documentation fournie.',
        'details_changelog' => 'Journal des modifications',
        'details_changelog_missing' => 'Aucun journal des modifications disponible.',
        'details_upgrades' => 'Guide de mise à jour',
        'details_upgrades_missing' => 'Aucune instruction de mise à jour fournie.',
        'details_licence' => 'Licence',
        'details_licence_missing' => 'Aucune licence spécifiée.',
        'details_current_version' => 'Version actuelle',
        'details_author' => 'Auteur',
    ],
    'server' => [
        'connect_error' => 'Erreur lors de la connexion au serveur.',
        'response_not_found' => 'Le serveur de mise à jour n'a pas été trouvé.',
        'response_invalid' => 'Réponse invalide du serveur.',
        'response_empty' => 'Réponse vide du serveur',
        'file_error' => 'Erreur du serveur lors de la transmission du paquet.',
        'file_corrupt' => 'Le fichier provenant du serveur est corrompu.',
    ],
    'behavior' => [
        'missing_property' => 'La classe :class doit définir la propriété $:property utilisée par le behavior :behavior.',
    ],
    'config' => [
        'not_found' => 'Impossible de trouver le fichier de configuration :file défini dans :location.',
        'required' => "La configuration utilisée dans :location doit fournir une valeur ':property'.",
    ],
    'zip' => [
        'extract_failed' => "Impossible de décompresser le fichier ':file'.",
    ],
    'event_log' => [
        'hint' => 'Ce journal affiche une liste des erreurs potentielles de l'application, telles que les exceptions et les informations de débogage.',
        'menu_label' => 'Journal des évènements',
        'menu_description' => 'Affiche les évènements des journaux systèmes avec leur date et les détails.',
        'empty_link' => 'Purger le journal des évènements',
        'empty_loading' => 'Purge du journal des évènements…',
        'empty_success' => 'Le journal des évènements a été purgé avec succès.',
        'return_link' => 'Retour au journal des évènements',
        'id' => 'ID',
        'id_label' => 'ID de l'évènement',
        'created_at' => 'Date et heure',
        'message' => 'Message',
        'level' => 'Niveau',
        'preview_title' => 'Évènement',
    ],
    'request_log' => [
        'hint' => 'Ce journal affiche une liste de requêtes potentiellement suspectes. Par exemple, si un visiteur ouvre une page introuvable du CMS, une ligne avec le code statut 404 est alors créée.',
        'menu_label' => 'Journal des requêtes',
        'menu_description' => 'Affiche les requêtes erronées ou redirigées, comme les erreurs 404.',
        'empty_link' => 'Purger le journal des requêtes',
        'empty_loading' => 'Purge du journal des requêtes…',
        'empty_success' => 'Le journal des requêtes a été purgé avec succès.',
        'return_link' => 'Retour au journal des requêtes',
        'id' => 'ID',
        'id_label' => 'ID du journal',
        'count' => 'Compteur',
        'referer' => 'Référents',
        'url' => 'Adresse URL',
        'status_code' => 'Statut',
        'preview_title' => 'Requête'
    ],
    'permissions' => [
        'name' => 'Système',
        'manage_system_settings' => 'Gérer les paramètres du système',
        'manage_software_updates' => 'Gérer les mises à jour du logiciel',
        'access_logs' => 'Voir les journaux système',
        'manage_mail_templates' => 'Gérer les modèles des e-mails',
        'manage_mail_settings' => 'Gérer les paramètres des e-mail',
        'manage_other_administrators' => 'Gérer les autres administrateurs',
        'manage_preferences' => 'Gérer les préférences de l'interface d'administration',
        'manage_editor' => 'Gérer les préférences de l'éditeur de code',
        'view_the_dashboard' => 'Voir le tableau de bord',
        'manage_branding' => 'Personnaliser l'interface d'administration'
    ],
    'media' => [
        'invalid_path' => "Le chemin du fichier indiqué est invalide : ':path'.",
        'folder_size_items' => 'Articles(s)',
    ],
];


text:
class AddDeliveryMethodToDistribution < ActiveRecord::Migration[6.0]
  def change
    # Default to pick_up
    add_column :distributions, :delivery_method, :integer, default: 0, null: false
  end
end


text:
'use strict';

/*
 You are given an array of objects. Your task is to write a JavaScript code that filters out the numbers of that array (removes all non-number objects).
 Then you should:

 1. Find the Min number,
 2. Find the Max number,
 3. Find the most frequent number.

 Finally you should print out the numbers you have found and the filtered array sorted in descending order.
 */

function filterNumbers(arrInput) {
    //FILTER ARRAY FUNCTION
    var filteredArray = arrInput.filter(function (arrIndex) {
        return !isNaN(arrIndex);
    });
    //GET MIN MAX FUNCTION
    function getMinMax(filtredArray, command) {
        var returnValue = 0;
        switch (command) {
            case 'min':
                returnValue = filtredArray.sort(function (currentIndex, nextIndex) {
                    return currentIndex > nextIndex;
                });
                break;
            case 'max':
                returnValue = filtredArray.sort(function (currentIndex, nextIndex) {
                    return currentIndex < nextIndex;
                });
                break;
        }
        return returnValue[0];
    }

    //CALL GET MIN MAX FUNCTION
    var minValue = getMinMax(filteredArray, 'min'),
        maxValue = getMinMax(filteredArray, 'max');
    //MOST FREQUENT FUNCTION
    function getMostFrequent(filteredArray) {
        var count = 0,
            maxCount = 0,
            result = 0;

        for (var i = 0; i < filteredArray.length; i += 1) {
            if (filteredArray[i] === filteredArray[i + 1]) {
                count += 1;
            } else {
                if (count > maxCount) {
                    maxCount = count;
                    result = i;
                }
                count = 0;
            }
        }
        return filteredArray[result];
    }
    var mostFrequent = getMostFrequent(filteredArray);

    //LOG RESULTS
    console.log('Min number: ' + minValue);
    console.log('Max number: ' + maxValue);
    console.log('Most frequent number: ' + mostFrequent);
    console.log(filteredArray);
}

filterNumbers(["Pesho", 2, "Gosho", 12, 2, "true", 9, undefined, 0, "Penka", {bunniesCount: 10}, [10, 20,
    30, 40]]);


text:
<?php

namespace RainLoop\Providers\TwoFactorAuth;

abstract class AbstractTwoFactorAuth
{
	/**
	 * @return string
	 */
	public function Label()
	{
		return 'Two Factor Authenticator Code';
	}

	/**
	 * @param string $sSecret
	 * @param string $sCode
	 * @return bool
	 */
	public function VerifyCode($sSecret, $sCode)
	{
		return false;
	}
}


text:
package com.novicehacks.autobot.config;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;

import com.novicehacks.autobot.categories.UnitTest;
import com.novicehacks.autobot.config.ResourceConfigParser;
import com.novicehacks.autobot.config.ResourceLoadingException;
import com.novicehacks.autobot.config.ServerConfigLoader;
import com.novicehacks.autobot.core.types.Server;
import com.novicehacks.autobot.core.types.ServerCredential;

public class TestServerConfigLoader {
	private ResourceConfigParser parser;
	private ServerConfigLoader serverConfigLoader;
	@Rule
	public ExpectedException exception = ExpectedException.none ();

	private final String[] DataSet = new String[] {
			"serverid1:servername1:ipaddress1",//
			"serverid2:servername2:ipaddress2:username",//
			"serverid3:servername3:ipaddress3:username:password",//
			"serverid4:servername4:ipaddress4:username1:password1:username2",//
			"serverid5:servername5:ipaddress5:init#command1:username1",//
			"serverid6:servername6:ipaddress6:username1:password1:username2:password2",//
			"serverid7:servername8:ipaddress8:init#command1:init#command2",//
			"serverid8:servername8:ipaddress8:init#command1:username1:password1",//
			"serverid9:servername9:ipaddress9:init#command1:init#command2:init#command3:username:password",
			"serverid10:servername10:ipaddress10:init#command1:init#command2:username1:password1:username2:password2" };

	@Before
	public void setup() {
		parser = mock (ResourceConfigParser.class);
		serverConfigLoader = new ServerConfigLoader ();
		serverConfigLoader = spy (serverConfigLoader);
		when (serverConfigLoader.getResourceConfigParser ()).thenReturn (parser);
		when (serverConfigLoader.getTokenSeperator ()).thenReturn (":");
	}

	@Test
	@Category (UnitTest.class)
	public void testLoadingMultipleServerConfigBean() throws IOException {
		Set<String> configSet = new HashSet<String> ();
		configSet.add (DataSet[2]);
		configSet.add (DataSet[5]);
		configSet.add (DataSet[8]);
		when (parser.getConfigFromFile ()).thenReturn (configSet);

		serverConfigLoader.loadServerConfiguration ();

		assertEquals ("Not all ServerConfig loaded", 3, serverConfigLoader.getServerConfig ()
				.size ());
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithNoCredentials() throws IOException {
		final int datasetIndex = 0;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		exception.expect (ResourceLoadingException.class);
		exception.expectMessage ("Server configuration didn't meet minimum config requirement");
		serverConfigLoader.loadServerConfiguration ();

		fail ("Invalid server config loaded, with no credentials ");
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithInvalidFirstCredential() throws IOException {
		final int datasetIndex = 1;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		exception.expect (ResourceLoadingException.class);
		exception.expectMessage ("Server configuration didn't meet minimum config requirement");
		serverConfigLoader.loadServerConfiguration ();

		fail ("Invalid Server credential config being loaded, without password");
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithOneCredential() throws IOException {
		final int datasetIndex = 2;
		String username = "username";
		String password = "password";
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertCredentialConfiguration (server, false, username);
		assertCredentialConfiguration (server, true, password);
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithInvalidSecondCredential() throws IOException {
		final int datasetIndex = 3;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		exception.expect (ResourceLoadingException.class);
		exception.expectMessage ("Server credential count is incorrect");
		serverConfigLoader.loadServerConfiguration ();

		fail ("Invalid Server credential config being loaded, without password for second credential");
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithInitCommandAndInvalidFirstCredential() throws IOException {
		final int datasetIndex = 4;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		exception.expect (ResourceLoadingException.class);
		exception.expectMessage ("Server credential count is incorrect");
		serverConfigLoader.loadServerConfiguration ();

		fail ("Invalid Server credential config being loaded, without password");
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithTwoSetsOfCredentials() throws IOException {
		int datasetIndex = 5;
		String usernames[] = { "username1", "username2" };
		String passwords[] = { "password1", "password2" };
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertCredentialConfiguration (server, false, usernames);
		assertCredentialConfiguration (server, true, passwords);
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithInitCommandAndNoCredentials() throws IOException {
		final int datasetIndex = 6;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		exception.expect (ResourceLoadingException.class);
		exception.expectMessage ("Server credential count is incorrect");
		serverConfigLoader.loadServerConfiguration ();

		fail ("Invalid Server credential config being loaded, without password");
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithNoInitCommands() throws IOException {
		final int datasetIndex = 2;
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertNotNull ("Empty array to be passed as init commands", server.initCommands ());
		assertEquals ("Empty array to be passed as init commands", 0, server.initCommands ().length);
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithSingleInitCommand() throws IOException {
		final int datasetIndex = 7;
		final String[] expectedInitCommands = { "command1" };
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertInitCommands (server, expectedInitCommands);
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithMultipleInitCommand() throws IOException {
		final int datasetIndex = 8;
		final String[] expectedInitCommands = { "command1", "command2", "command3" };
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertInitCommands (server, expectedInitCommands);
	}

	@Test
	@Category (UnitTest.class)
	public void testServerConfigWithMultipleInitCommandsAndMultipleCredentials() throws IOException {
		final int datasetIndex = 9;
		final String[] expectedInitCommands = { "command1", "command2" };
		String usernames[] = { "username1", "username2" };
		String passwords[] = { "password1", "password2" };
		when (parser.getConfigFromFile ()).thenReturn (mockedServerConfig (datasetIndex));

		serverConfigLoader.loadServerConfiguration ();

		Server server = assertBasicServerConfigAndReturnInstance (datasetIndex);
		assertInitCommands (server, expectedInitCommands);
		assertCredentialConfiguration (server, false, usernames);
		assertCredentialConfiguration (server, true, passwords);
	}

	@Test
	@Category (UnitTest.class)
	public void testResouceNotFoundInConfigParser() throws IOException {
		when (parser.getConfigFromFile ()).thenThrow (new IOException ("Resource not found"));

		exception.expect (IOException.class);
		exception.expectMessage ("Resource not found");
		serverConfigLoader.loadServerConfiguration ();
	}

	private Set<String> mockedServerConfig(int datasetIndex) {
		String config = DataSet[datasetIndex];
		Set<String> configSet = new HashSet<String> ();
		configSet.add (config);
		return configSet;
	}

	private Server assertBasicServerConfigAndReturnInstance(int datasetIndex) {
		String expectedTokens[] = DataSet[datasetIndex].split (":");
		Iterator<Server> serversIterator = serverConfigLoader.getServerConfig ().iterator ();
		Server server = serversIterator.next ();
		assertEquals ("Server id not loaded correctly", expectedTokens[0], server.id ());
		assertEquals ("Server name not loaded correctly", expectedTokens[1], server.name ());
		assertEquals ("Server IPAddress not loaded correctly", expectedTokens[2],
				server.ipaddress ());
		return server;
	}

	private void assertCredentialConfiguration(	Server server,
												boolean isPassword,
												String... expectedCredentialss) {
		ServerCredential[] credentials = server.credentials ();
		assertEquals ("Incorrect no. of credentials loaded", expectedCredentialss.length,
				credentials.length);
		for (int index = 0; index < credentials.length; index++) {
			assertEachCredential (expectedCredentialss[index], credentials[index], isPassword);
		}
	}

	private void assertEachCredential(	String expected,
										ServerCredential actualCredential,
										boolean isPasswordCredential) {
		if (isPasswordCredential)
			assertEquals ("Incorrect login username", expected, actualCredential.getPassword ());
		else
			assertEquals ("Incorrect login username", expected, actualCredential.getLoginid ());
	}

	private void assertInitCommands(Server server, String[] expectedInitCommands) {
		String[] actualCommands = server.initCommands ();
		assertEquals ("Incorrect no. of commands loaded", expectedInitCommands.length,
				actualCommands.length);
		for (int index = 0; index < actualCommands.length; index++)
			assertEquals ("Command loaded incorrectly", expectedInitCommands[index],
					actualCommands[index]);
	}

}


text:
![logon](https://raw.githubusercontent.com/ogycode/JesusPassword/master/merch/readme.png)

*Jesus Password* - password manager for devices running on Windows 8.1/10.
Compared to other similar applications, Jesus Password - free and has a narrow specialization - storage of passwords from your accounts. Also not overloaded extra functionality as in other similar applications.

*Functional*:
 - File Storage with all the information in the cloud OneDrive.
 - Instant synchronization between your devices on which the application is installed.
 - Flexible and customizable password generator.
 - Simple and intuitive user interface.
 - The application also makes it possible to store not only information about the account and any other textual information.

*Links*:

 - ***[App in Windows Store](https://www.microsoft.com/ru-ru/store/apps/jesus-password/9nblggh691x4)***
 -  [*App in Google Play (comig soon, approximately in 2018)](/)
 -  *[Author personal page](https://verloka.github.io)*
 -  *[Application personal page](https://jpassword.pp.ua)*


text:
/**
 * @file
 * @brief Header of the fsw::win_handle class.
 *
 * @copyright Copyright (c) 2014-2015 Enrico M. Crisostomo
 * @license GNU General Public License v. 3.0
 * @author Enrico M. Crisostomo
 * @version 1.8.0
 */
#ifndef FSW_WINDOWS_HANDLE_H
#  define FSW_WINDOWS_HANDLE_H

#  include <windows.h>

namespace fsw
{
  /**
   * @brief A RAII wrapper around Microsoft Windows `HANDLE`.
   *
   * This class is a movable, non-copyable RAII wrapper on `HANDLE`.
   */
  class win_handle
  {
  public:
    /**
     * @brief Checks whether @p handle is valid.
     *
     * A @p handle is valid is if its value is not `null` and if is not
     * `INVALID_HANDLE_VALUE`.
     *
     * @param handle The handle to check.
     * @return Returns @c true if @p handle is valid, @c false otherwise.
     */
    static bool is_valid(const HANDLE & handle);

    /**
     * @brief Constructs an instance wrapping `INVALID_HANDLE_VALUE`.
     */
    win_handle();

    /**
     * @brief Constructs an instance wrapping @p handle.
     */
    win_handle(HANDLE handle);

    /**
     * @brief Destructs a handle.
     *
     * If the handle is valid (is_valid()) it is closed invoking
     * `CloseHandle()`.
     *
     * @see is_valid(const HANDLE &)
     */
    virtual ~win_handle();

    /**
     * @brief Returns the handle value as `HANDLE` instance.
     */
    operator HANDLE() const;

    /**
     * @brief Checks whether the handle is valid.
     *
     * @return Returns @c true if the handle is valid, @c false otherwise.
     * @see is_valid()
     */
    bool is_valid() const;

    /**
     * @brief Deleted copy constructor.
     */
    win_handle(const win_handle&) = delete;

    /**
     * @brief Deleted copy assignment operator.
     */
    win_handle& operator=(const win_handle&) = delete;

    /**
     * @brief Move constructor.
     *
     * The move constructors moves the handle value wrapped by @p other to the
     * target instance.  The handle value in @p other is set to
     * `INVALID_HANDLE_VALUE`.  The previously wrapped instance is closed
     * invoking `CloseHandle` if it is valid.
     *
     * @param other The handle to move.
     */
    win_handle(win_handle&& other) noexcept;

    /**
     * @brief Move assignment operator.
     *
     * The move assignment operator moves the handle value wrapped by @p other
     * to the target instance.  The handle value in @p other is set to
     * `INVALID_HANDLE_VALUE`.  The previously wrapped instance is closed
     * invoking `CloseHandle` if it is valid.
     *
     * @param other The handle to move.
     */
    win_handle& operator=(win_handle&& other) noexcept;

    /**
     * @brief Assigns a @p handle to the current instance.
     *
     * The previously wrapped instance is closed invoking `CloseHandle` if it is
     * valid.
     *
     * @param handle The handle value to assign to the current instance.
     */
    win_handle& operator=(const HANDLE& handle);
  private:
    HANDLE h;
  };
}

#endif  /* FSW_WINDOWS_HANDLE_H */


text:
"""
A tool set for multi- and many-objective optimisation by Matthaus Woolard.
 matthaus.woolard@gmail.com

Copyright 2015 Matthaus Woolard

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

"""


text:
BOOST_AUTO_TEST_SUITE(getarg_tests)

static void
ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);

    // Insert dummy executable name:
    vecArg.insert(vecArg.begin(), "testbitcoin");

    // Convert to char*:
    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}

BOOST_AUTO_TEST_CASE(boolarg)
{
    ResetArgs("-WOOT");
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", false));
    BOOST_CHECK(GetBoolArg("-WOOT", true));

    BOOST_CHECK(!GetBoolArg("-fo"));
    BOOST_CHECK(!GetBoolArg("-fo", false));
    BOOST_CHECK(GetBoolArg("-fo", true));

    BOOST_CHECK(!GetBoolArg("-WOOTo"));
    BOOST_CHECK(!GetBoolArg("-WOOTo", false));
    BOOST_CHECK(GetBoolArg("-WOOTo", true));

    ResetArgs("-WOOT=0");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));

    ResetArgs("-WOOT=1");
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", false));
    BOOST_CHECK(GetBoolArg("-WOOT", true));

    // New 0.6 feature: auto-map -nosomething to !-something:
    ResetArgs("-noWOOT");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));

    ResetArgs("-noWOOT=1");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));

    ResetArgs("-WOOT -noWOOT");  // -WOOT should win
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", false));
    BOOST_CHECK(GetBoolArg("-WOOT", true));

    ResetArgs("-WOOT=1 -noWOOT=1");  // -WOOT should win
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", false));
    BOOST_CHECK(GetBoolArg("-WOOT", true));

    ResetArgs("-WOOT=0 -noWOOT=0");  // -WOOT should win
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));

    // New 0.6 feature: treat -- same as -:
    ResetArgs("--WOOT=1");
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", false));
    BOOST_CHECK(GetBoolArg("-WOOT", true));

    ResetArgs("--noWOOT=1");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));

}

BOOST_AUTO_TEST_CASE(stringarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", "eleven"), "eleven");

    ResetArgs("-WOOT -bar");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", "eleven"), "");

    ResetArgs("-WOOT=");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", "eleven"), "");

    ResetArgs("-WOOT=11");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "11");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", "eleven"), "11");

    ResetArgs("-WOOT=eleven");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "eleven");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", "eleven"), "eleven");

}

BOOST_AUTO_TEST_CASE(intarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", 11), 11);
    BOOST_CHECK_EQUAL(GetArg("-WOOT", 0), 0);

    ResetArgs("-WOOT -bar");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", 11), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);

    ResetArgs("-WOOT=11 -bar=12");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", 0), 11);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);

    ResetArgs("-WOOT=NaN -bar=NotANumber");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", 1), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}

BOOST_AUTO_TEST_CASE(doubledash)
{
    ResetArgs("--WOOT");
    BOOST_CHECK_EQUAL(GetBoolArg("-WOOT"), true);

    ResetArgs("--WOOT=verbose --bar=1");
    BOOST_CHECK_EQUAL(GetArg("-WOOT", ""), "verbose");
    BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}

BOOST_AUTO_TEST_CASE(boolargno)
{
    ResetArgs("-noWOOT");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));

    ResetArgs("-noWOOT=1");
    BOOST_CHECK(!GetBoolArg("-WOOT"));
    BOOST_CHECK(!GetBoolArg("-WOOT", true));
    BOOST_CHECK(!GetBoolArg("-WOOT", false));

    ResetArgs("-noWOOT=0");
    BOOST_CHECK(GetBoolArg("-WOOT"));
    BOOST_CHECK(GetBoolArg("-WOOT", true));
    BOOST_CHECK(GetBoolArg("-WOOT", false));

    ResetArgs("-WOOT --noWOOT");
    BOOST_CHECK(GetBoolArg("-WOOT"));

    ResetArgs("-noWOOT -WOOT"); // WOOT always wins:
    BOOST_CHECK(GetBoolArg("-WOOT"));
}

BOOST_AUTO_TEST_SUITE_END()


text:
"""Test SMHI component setup process."""
from smhi.smhi_lib import APIURL_TEMPLATE

from homeassistant.components.smhi.const import DOMAIN
from homeassistant.core import HomeAssistant

from . import ENTITY_ID, TEST_CONFIG

from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker

async def test_setup_entry(
    hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, api_response: str
) -> None:
    """Test setup entry."""
    uri = APIURL_TEMPLATE.format(TEST_CONFIG["longitude"], TEST_CONFIG["latitude"])
    aioclient_mock.get(uri, text=api_response)
    entry = MockConfigEntry(domain=DOMAIN, data=TEST_CONFIG)
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_ID)
    assert state

async def test_remove_entry(hass: HomeAssistant) -> None:
    """Test remove entry."""
    entry = MockConfigEntry(domain=DOMAIN, data=TEST_CONFIG)
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_ID)
    assert state

    await hass.config_entries.async_remove(entry.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_ID)
    assert not state


text:
// our modules
var config = require("../../config");

// The GameToken model (created in the `module.exports` function below)
var GameToken;

// Create the GameToken model
module.exports = function (mongoose) {
    var Schema = mongoose.Schema;

    // GameToken schema
    var gameTokenSchema = new Schema({
        // The token
        token: {
            type: String,
            required: true,
            unique: true
        },

        // The game
        game: {
            type: Schema.Types.ObjectId,
            ref: "Game",
            required: true
        },

        // The user playing this game
        user: {
            type: Schema.Types.ObjectId,
            ref: "User"
        },

        // The game state
        state: {
            type: Schema.Types.Mixed
        },

        // The SerGIS Client User object
        clientUserObject: {
            type: Schema.Types.Mixed
        },

        // The date that it was created
        created: {
            type: Date,
            default: Date.now
        }
    });

    // GameToken model static method
    /**
     * Make a new game token.
     *
     * @param {Game} game - The game to make a token for.
     * @param {User} [user] - The user who is playing the game (if any).
     *
     * @return {Promise.<GameToken>} The new GameToken.
     */
    gameTokenSchema.statics.makeGameToken = function (game, user) {
        return new Promise(function (resolve, reject) {
            if (!game.isAccessibleByUser(user)) {
                // Ahh! The user doesn't have access to this game!
                return reject();
            }

            // Re-get the game with the JSON data
            var db = require("../db");
            resolve(db.models.Game.findById(game._id)
                             .select("+jsondata")
                             .lean(true)
                             .exec());
        }).then(function (game) {
            var token = Number(randInt(10) + "" + (new Date()).getTime() + "" + randInt(10)).toString(36);
            var gameToken = new GameToken({
                token: token,
                game: game._id,
                user: user ? user._id : undefined,
                state: {
                    gameName: game.name,
                    // Default state
                    currentPromptIndex: null,
                    nextAllowedPromptIndex: null,
                    userChoices: [],
                    userChoiceOrder: []
                },
                clientUserObject: {
                    jumpingBackAllowed: !!game.jsondata.jumpingBackAllowed,
                    jumpingForwardAllowed: !!game.jsondata.jumpingForwardAllowed,
                    alwaysReinitializeMap: !!game.jsondata.alwaysReinitializeMap,
                    layout: game.jsondata.layout,
                    homeURL: config.HTTP_PREFIX + "/games",
                    displayName: user ? user.name : undefined
                }
            });
            return gameToken.save().then(function () {
                return gameToken;
            });
        });
    };

    // GameToken model
    return (GameToken = mongoose.model("GameToken", gameTokenSchema));
};

/**
 * Make a quick and dirty random integer.
 *
 * @param {number} d - The number of digits in the number.
 */
function randInt(d) {
    return Math.floor((Math.random() * 9 + 1) * Math.pow(10, d-1));
}


text:
package tls

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestWildCardValidation(t *testing.T) {
	tests := []struct {
		name  string
		hosts string
	}{
		{
			name:  "Not a valid host name",
			hosts: "*.banzaicloud.com,127.0.0.1,beta.banzaicloud.com",
		},
		{
			name:  "Valid host name",
			hosts: "*.banzaicloud.com,127.0.0.1,alpha.beta.banzaicloud.com",
		},
	}
	for _, test := range tests {
		sHosts := NewSeparatedCertHosts(test.hosts)
		t.Run(test.name, func(t *testing.T) {
			err := sHosts.Validate()
			if err != nil {
				if err.Error() != ErrInvalidHostName.Error() {
					t.Fatal(err)
				}
			}
		})
	}
}

func TestGenerateTLS(t *testing.T) {
	cm, err := NewCertificateManager("localhost,127.0.0.1", "1h")
	if err != nil {
		t.Fatal(err)
	}

	err = cm.NewChain()
	if err != nil {
		t.Fatal(err)
	}

	// Load CA cert
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM([]byte(cm.Chain.CACert))

	serverCert, err := tls.X509KeyPair([]byte(cm.Chain.ServerCert), []byte(cm.Chain.ServerKey))
	if err != nil {
		t.Fatal(err)
	}

	tlsConfig := &tls.Config{
		ClientAuth:               tls.RequireAndVerifyClientCert,
		ClientCAs:                caCertPool,
		PreferServerCipherSuites: true,
		MinVersion:               tls.VersionTLS12,
		Certificates:             []tls.Certificate{serverCert},
	}

	tlsConfig.BuildNameToCertificate()

	server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		_, err := w.Write([]byte("This is an example TLS server.\n"))
		if err != nil {
			t.Fatal(err)
		}
	}))

	server.Listener = tls.NewListener(server.Listener, tlsConfig)

	server.Start()

	// Load client cert
	clientCert, err := tls.X509KeyPair([]byte(cm.Chain.ClientCert), []byte(cm.Chain.ClientKey))
	if err != nil {
		t.Fatal(err)
	}

	// Setup HTTPS client
	clientTLSConfig := &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      caCertPool,
	}
	clientTLSConfig.BuildNameToCertificate()
	transport := &http.Transport{TLSClientConfig: clientTLSConfig}
	client := &http.Client{Transport: transport}

	tests := []string{
		server.Listener.Addr().String(), // Should work with IP address as well
		strings.Replace(server.Listener.Addr().String(), "127.0.0.1", "localhost", 1),
	}

	for _, test := range tests {
		test := test

		t.Run(strings.Split(test, ":")[0], func(t *testing.T) {
			req, err := http.NewRequestWithContext(context.Background(), "GET", "https://"+test, nil)
			if err != nil {
				t.Fatal(err)
			}

			resp, err := client.Do(req)
			if err != nil {
				t.Fatal(err)
			}

			resp.Body.Close()
		})
	}

	server.Close()
}

func TestLoadAndRegenerateTLS(t *testing.T) {
	cmTemp, err := NewCertificateManager("localhost,127.0.0.1", "1h")
	if err != nil {
		t.Fatal(err)
	}

	err = cmTemp.NewChain()
	if err != nil {
		t.Fatal(err)
	}

	cm, err := NewCertificateManager("localhost,127.0.0.1", "1h")
	if err != nil {
		t.Fatal(err)
	}

	// Load an existing certificate authority
	err = cm.LoadCA([]byte(cmTemp.Chain.CACert), []byte(cmTemp.Chain.CAKey), time.Minute*50)
	if err != nil {
		t.Fatal(err)
	}

	// Load CA cert
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM([]byte(cm.Chain.CACert))

	err = cm.GenerateServer()
	// Generate the Server TLS certificate
	if err != nil {
		t.Fatal(err)
	}

	err = cm.GenerateClient()
	// Generate the Client TLS certificate
	if err != nil {
		t.Fatal(err)
	}

	serverCert, err := tls.X509KeyPair([]byte(cm.Chain.ServerCert), []byte(cm.Chain.ServerKey))
	if err != nil {
		t.Fatal(err)
	}

	tlsConfig := &tls.Config{
		ClientAuth:               tls.RequireAndVerifyClientCert,
		ClientCAs:                caCertPool,
		PreferServerCipherSuites: true,
		MinVersion:               tls.VersionTLS12,
		Certificates:             []tls.Certificate{serverCert},
	}

	tlsConfig.BuildNameToCertificate()

	server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		_, err := w.Write([]byte("This is an example TLS server.\n"))
		if err != nil {
			t.Fatal(err)
		}
	}))

	server.Listener = tls.NewListener(server.Listener, tlsConfig)

	server.Start()

	// Load client cert
	clientCert, err := tls.X509KeyPair([]byte(cm.Chain.ClientCert), []byte(cm.Chain.ClientKey))
	if err != nil {
		t.Fatal(err)
	}

	// Setup HTTPS client
	clientTLSConfig := &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      caCertPool,
	}
	clientTLSConfig.BuildNameToCertificate()
	transport := &http.Transport{TLSClientConfig: clientTLSConfig}
	client := &http.Client{Transport: transport}

	tests := []string{
		server.Listener.Addr().String(), // Should work with IP address as well
		strings.Replace(server.Listener.Addr().String(), "127.0.0.1", "localhost", 1),
	}

	for _, test := range tests {
		test := test

		t.Run(strings.Split(test, ":")[0], func(t *testing.T) {
			req, err := http.NewRequestWithContext(context.Background(), "GET", "https://"+test, nil)
			if err != nil {
				t.Fatal(err)
			}

			resp, err := client.Do(req)
			if err != nil {
				t.Fatal(err)
			}

			resp.Body.Close()
		})
	}

	server.Close()
}


text:
using System.IO;
using Yu_Gi_Oh.File_Handling.Miscellaneous_Files;

namespace Yu_Gi_Oh.File_Handling.Pack_Files
{
    public class Shop_Pack : File_Data
    {
        public Shop_Pack()
        {
            CommonCards = new CardCollection();
            RareCards = new CardCollection();
        }

        public CardCollection CommonCards { get; set; }
        public CardCollection RareCards { get; set; }

        public override void Load(BinaryReader reader, long length)
        {
            CommonCards.Clear();
            RareCards.Clear();

            var commonCardCount = reader.ReadInt16();
            var rareCardCount = reader.ReadInt16();

            for (var i = 0; i < commonCardCount; i++) CommonCards.Add(reader.ReadInt16());

            for (var i = 0; i < rareCardCount; i++) RareCards.Add(reader.ReadInt16());
        }

        public override void Save(BinaryWriter writer)
        {
            writer.Write((short) (CommonCards?.CardIds.Count ?? 0));
            writer.Write((short) (RareCards?.CardIds.Count ?? 0));

            if (CommonCards != null)
            {
                CommonCards.Sort();
                foreach (var cardId in CommonCards.CardIds) writer.Write(cardId);
            }

            if (RareCards != null)
            {
                RareCards.Sort();
                foreach (var cardId in RareCards.CardIds) writer.Write(cardId);
            }
        }
    }
}


text:
function score = simplecountscore(cycles)
maxk = 10;
score = 0;
% Simply count the number of 2,3,4,5, etc cycles
for k = 1:maxk
    for i = 1:length(cycles)
        if length(cycles{i}) == k
            score = score + k; % thinking is short cycles aren't so bad, but long cycles are bad
        end
    end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

	<!-- Simple target -->
	<bean id="test" class="org.springframework.aop.interceptor.SideEffectBean">
		<property name="count"><value>10</value></property>
	</bean>

	<bean id="prototypeTest" class="org.springframework.aop.interceptor.SideEffectBean" scope="prototype">
		<property name="count"><value>10</value></property>
	</bean>

	<bean id="prototypeTargetSource" class="org.springframework.aop.target.PrototypeTargetSource">
		<property name="targetBeanName"><value>prototypeTest</value></property>
	</bean>

	<bean id="debugInterceptor" class="org.springframework.aop.interceptor.NopInterceptor" />

	<bean id="singleton" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="interceptorNames"><value>debugInterceptor,test</value></property>
	</bean>

	<!--
		This will create a bean that creates a new target on each invocation.
	-->
	<bean id="prototype" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="targetSource"><ref local="prototypeTargetSource"/></property>
		<property name="interceptorNames"><value>debugInterceptor</value></property>
	</bean>

</beans>


text:
@interface RNAlerts : NSObject <RCTBridgeModule>

@end


text:
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace CSharpGuidelinesAnalyzer.Rules.MiscellaneousDesign
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public sealed class CatchSpecificExceptionAnalyzer : DiagnosticAnalyzer
    {
        private const string Title = "Catch a specific exception instead of Exception, SystemException or ApplicationException";
        private const string MessageFormat = "Catch a specific exception instead of Exception, SystemException or ApplicationException";
        private const string Description = "Don't swallow errors by catching generic exceptions.";

        public const string DiagnosticId = AnalyzerCategory.RulePrefix + "1210";

        [NotNull]
        private static readonly AnalyzerCategory Category = AnalyzerCategory.MiscellaneousDesign;

        [NotNull]
        private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category.DisplayName,
            DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId));

        [NotNull]
        private static readonly Action<CompilationStartAnalysisContext> RegisterCompilationStartAction = RegisterCompilationStart;

#pragma warning disable RS1008 // Avoid storing per-compilation data into the fields of a diagnostic analyzer.
        [NotNull]
        private static readonly Action<SyntaxNodeAnalysisContext, ImmutableArray<INamedTypeSymbol>> AnalyzeCatchClauseAction = AnalyzeCatchClause;
#pragma warning restore RS1008 // Avoid storing per-compilation data into the fields of a diagnostic analyzer.

        [ItemNotNull]
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

        public override void Initialize([NotNull] AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(RegisterCompilationStartAction);
        }

        private static void RegisterCompilationStart([NotNull] CompilationStartAnalysisContext startContext)
        {
            ImmutableArray<INamedTypeSymbol> types = ResolveExceptionTypes(startContext.Compilation);

            if (types.Any())
            {
                startContext.RegisterSyntaxNodeAction(context => AnalyzeCatchClauseAction(context, types), SyntaxKind.CatchClause);
            }
        }

        [ItemNotNull]
        private static ImmutableArray<INamedTypeSymbol> ResolveExceptionTypes([NotNull] Compilation compilation)
        {
            INamedTypeSymbol[] types =
            {
                KnownTypes.SystemException(compilation),
                KnownTypes.SystemSystemException(compilation),
                KnownTypes.SystemApplicationException(compilation)
            };

            return types.Where(type => type != null).ToImmutableArray();
        }

        private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context, [ItemNotNull] ImmutableArray<INamedTypeSymbol> exceptionTypes)
        {
            var catchClause = (CatchClauseSyntax)context.Node;

            if (catchClause.Filter == null)
            {
                ISymbol exceptionType = TryGetExceptionType(catchClause.Declaration, context.SemanticModel, context.CancellationToken);

                if (exceptionType == null || exceptionTypes.Contains(exceptionType))
                {
                    Location location = catchClause.CatchKeyword.GetLocation();

                    var diagnostic = Diagnostic.Create(Rule, location);
                    context.ReportDiagnostic(diagnostic);
                }
            }
        }

        [CanBeNull]
        private static ISymbol TryGetExceptionType([CanBeNull] CatchDeclarationSyntax declaration, [NotNull] SemanticModel model,
            CancellationToken cancellationToken)
        {
            return declaration != null ? model.GetSymbolInfo(declaration.Type, cancellationToken).Symbol : null;
        }
    }
}


text:
package com.dianwuyou.repo;

import com.dianwuyou.model.Task;

import java.util.List;

/**
 * Created by hebowei on 16/6/19.
 */
public interface TaskRepository {
    Task getTaskById(int id);
    List<Task> getByIds(List<Integer> ids);
    List<Task> getByOwnerId(int ownerId);
    List<Task> getPagedTasks(int pageNo, int pageSize); //pageNo starts from 0
    List<Task> getPagedTasks(int pageNo, int pageSize, boolean showFutureTasks);

    void saveTask(Task task);
    void updateTask(Task task);
    void deleteTaskById(int id);
    Long getTaskCount();
}


text:
<?php

namespace Fungio\GoogleMapBundle\Tests\Entity;

use Fungio\GoogleMapBundle\Entity\ScaleControl;

/**
 * Scale control entity test.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class ScaleControlTest extends \PHPUnit_Framework_TestCase
{
    public function testInheritance()
    {
        $this->assertInstanceOf('Fungio\GoogleMap\Controls\ScaleControl', new ScaleControl());
    }
}


text:
<?php

namespace Umpirsky\Country\Importer\Source;

use Umpirsky\Country\Importer\Importer;

/**
 * CLDR importer.
 *
 * @author Саша Стаменковић <umpirsky@gmail.com>
 */
class Cldr extends Importer
{
    /**
     * Cldr constructor.
     */
    public function __construct()
    {
        \Zend_Locale::disableCache(true);
    }

    /**
     * {@inheritdoc}
     */
    public function getLanguages()
    {
        return array_keys(\Zend_Locale::getLocaleList());
    }

    /**
     * {@inheritdoc}
     */
    public function getCountries($language)
    {
		$countries = \Zend_Locale::getTranslationList('territory', $language, 2);
        if (is_array($countries)) {
            asort($countries);
        }

        return $countries;
    }

    /**
     * {@inheritdoc}
     */
    public function getCountryLanguages($language)
    {
		$languages = \Zend_Locale::getTranslationList('language', $language, 2);
        if (is_array($languages)) {
            asort($languages);
        }

        return $languages;
    }
}


text:
<?php

/**
 * base actions class for the gadgets and social modules
 *
 * @package    opOpenSocialPlugin
 * @subpackage action
 * @author     Shogo Kawahara <kawahara@tejimaya.net>
 */
abstract class opOpenSocialServletActions extends sfActions
{
  /**
   * servletExecute
   *
   * @param $servlet A servlet object
   */
  protected function servletExecute($servlet)
  {

    if (!($servlet instanceof HttpServlet) && !($servlet instanceof ApiServlet))
    {
      throw new LogicException();
    }

    $request = $this->getRequest();
    $method = "";
    switch($request->getMethod())
    {
      case sfRequest::GET    : $method = 'doGet';    break;
      case sfRequest::POST   : $method = 'doPost';   break;
      case sfRequest::PUT    : $method = 'doPut';    break;
      case sfRequest::DELETE : $method = 'doDelete';
    }
    if (is_callable(array($servlet, $method)))
    {
      $servlet->$method();
    }
    else
    {
      header("HTTP/1.0 405 Method Not Allowed");
      echo "
405 Method Not Allowed
";
    }
  }
}


text:
package c_time;

import java.time.LocalDate;
import java.time.Month;

class AddOneYear {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2000, Month.FEBRUARY, 29);
        System.out.println(date.plusYears(4));
        System.out.println(date.plusMonths(12));
        System.out.println(date.plusYears(1).plusYears(1).plusYears(1).plusYears(1));
        System.out.println(date.plusMonths(12).plusMonths(12).plusMonths(12).plusMonths(12));

    }
}


text:
<?php

namespace it\icosaedro\io;
require_once __DIR__ . "/../../../all.php";

/**
 * Output stream filter that performs Base64 encoding. Please note that the
 * close() method MUST be called in order to properly complete the writing of
 * the Base64 stream; calling flush() is not enough to this end.
 * Implements the RFC 2045 encoding scheme.
 * @author Umberto Salsi <salsi@icosaedro.it>
 * @version $Date: 2014/11/16 17:27:24 $
 */
class Base64OutputStream extends OutputStream {

	/**
	 * @var OutputStream
	 */
	private $out;

	/**
	 * @var string
	 */
	private $buf = "";

	/**
	 * Creates a new Base64 stream encoder.
	 * @param OutputStream $out Output stream, Base64 encoded.
	 */
	public function __construct($out)
	{
		$this->out = $out;
	}

	/**
	 * Writes a single byte.
	 * @param int $b Byte to write. Only the lower 8 bits are actually
	 * written.
	 * @return void
	 * @throws IOException
	 */
	public function writeByte($b)
	{
		$this->buf .= chr($b & 255);
		$this->flush();
	}

	/**
	 * Writes a string of bytes. Does nothing if the string is NULL
	 * or empty.
	 * @param string $bytes
	 * @return void
	 * @throws IOException
	 */
	public function writeBytes($bytes) {
		if( strlen($bytes) == 0 )
			return;
		$this->buf .= $bytes;
		$this->flush();
	}

	/**
	 * Writes to the output stream as many bytes as possible from the internal
	 * buffer. Please note that, because of the way the Base64 encoding works,
	 * still some bytes may remain in the internal buffer as they can be written
	 * only at the close().
	 * @return void
	 * @throws IOException
	 */
	function flush()
	{
		$len = strlen($this->buf);
		if( $len < 3 )
			return;
		$w = 3 * (int) ($len / 3);
		$this->out->writeBytes(base64_encode(substr($this->buf, 0, $w)));
		if( $w < $len )
			$this->buf = substr($this->buf, $w, $len - $w);
		else
			$this->buf = "";
		parent::flush();
	}

	/**
	 * Closes the file. Does nothing if already closed.
	 * Once closed, this object cannot be used anymore.
	 * This method MUST be called in order to complete the writing of the
	 * Base64 last bytes; if not called, the latest 1 or 2 bytes of the stream
	 * might be lost.
	 * @return void
	 * @throws IOException
	 */
	public function close()
	{
		if( $this->out === NULL )
			return;
		if( strlen($this->buf) > 0 )
			$this->out->writeBytes(base64_encode($this->buf));
		$this->out->close();
		$this->out = NULL;
	}

}


text:
"""
    Kubeflow Training SDK

    Python SDK for Kubeflow Training  # noqa: E501

    The version of the OpenAPI document: v1.5.0
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest
import datetime

from kubeflow.training.models import *
from kubeflow.training.models.kubeflow_org_v1_mx_job_list import KubeflowOrgV1MXJobList  # noqa: E501
from kubeflow.training.rest import ApiException

class TestKubeflowOrgV1MXJobList(unittest.TestCase):
    """KubeflowOrgV1MXJobList unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def make_instance(self, include_optional):
        """Test KubeflowOrgV1MXJobList
            include_option is a boolean, when False only required
            params are included, when True both required and
            optional params are included """
        # model = kubeflow.training.models.kubeflow_org_v1_mx_job_list.KubeflowOrgV1MXJobList()  # noqa: E501
        if include_optional :
            return KubeflowOrgV1MXJobList(
                api_version = '0',
                items = [
                    kubeflow_org_v1_mx_job.KubeflowOrgV1MXJob(
                        api_version = '0',
                        kind = '0',
                        metadata = None,
                        spec = kubeflow_org_v1_mx_job_spec.KubeflowOrgV1MXJobSpec(
                            job_mode = '0',
                            mx_replica_specs = {
                                'key' : V1ReplicaSpec(
                                    replicas = 56,
                                    restart_policy = '0',
                                    template = None, )
                                },
                            run_policy = V1RunPolicy(
                                active_deadline_seconds = 56,
                                backoff_limit = 56,
                                clean_pod_policy = '0',
                                scheduling_policy = V1SchedulingPolicy(
                                    min_available = 56,
                                    min_resources = {
                                        'key' : None
                                        },
                                    priority_class = '0',
                                    queue = '0', ),
                                ttl_seconds_after_finished = 56, ), ),
                        status = V1JobStatus(
                            completion_time = None,
                            conditions = [
                                V1JobCondition(
                                    last_transition_time = None,
                                    last_update_time = None,
                                    message = '0',
                                    reason = '0',
                                    status = '0',
                                    type = '0', )
                                ],
                            last_reconcile_time = None,
                            replica_statuses = {
                                'key' : V1ReplicaStatus(
                                    active = 56,
                                    failed = 56,
                                    label_selector = None,
                                    succeeded = 56, )
                                },
                            start_time = None, ), )
                    ],
                kind = '0',
                metadata = None
            )
        else :
            return KubeflowOrgV1MXJobList(
                items = [
                    kubeflow_org_v1_mx_job.KubeflowOrgV1MXJob(
                        api_version = '0',
                        kind = '0',
                        metadata = None,
                        spec = kubeflow_org_v1_mx_job_spec.KubeflowOrgV1MXJobSpec(
                            job_mode = '0',
                            mx_replica_specs = {
                                'key' : V1ReplicaSpec(
                                    replicas = 56,
                                    restart_policy = '0',
                                    template = None, )
                                },
                            run_policy = V1RunPolicy(
                                active_deadline_seconds = 56,
                                backoff_limit = 56,
                                clean_pod_policy = '0',
                                scheduling_policy = V1SchedulingPolicy(
                                    min_available = 56,
                                    min_resources = {
                                        'key' : None
                                        },
                                    priority_class = '0',
                                    queue = '0', ),
                                ttl_seconds_after_finished = 56, ), ),
                        status = V1JobStatus(
                            completion_time = None,
                            conditions = [
                                V1JobCondition(
                                    last_transition_time = None,
                                    last_update_time = None,
                                    message = '0',
                                    reason = '0',
                                    status = '0',
                                    type = '0', )
                                ],
                            last_reconcile_time = None,
                            replica_statuses = {
                                'key' : V1ReplicaStatus(
                                    active = 56,
                                    failed = 56,
                                    label_selector = None,
                                    succeeded = 56, )
                                },
                            start_time = None, ), )
                    ],
        )

    def testKubeflowOrgV1MXJobList(self):
        """Test KubeflowOrgV1MXJobList"""
        inst_req_only = self.make_instance(include_optional=False)
        inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
    unittest.main()


text:
using System.Runtime.Serialization;

namespace ArchsimLib
{
    [DataContract(IsReference = true)]
    public class HVACZoneVAV : LibraryComponent
    {
        [DataMember]
        public double FanTotalEfficiency { get; set; } = 0.7;
        [DataMember]
        public double FanDeltaPressure { get; set; } = 600;
        [DataMember]
        public double FanMotorEfficiency { get; set; } = 0.9;

        [DataMember]
        public double HeatingSetpoint { get; set; } = 20;//needed for trnsys
        [DataMember]
        public double CoolingSetpoint { get; set; } = 26;//needed for trnsys

        [Units("L/s/p")]
        public double MinFreshAirPerson { get; set; } = 2.5;
        [DataMember]
        [Units("L/s/m2")]
        public double MinFreshAirArea { get; set; } = 0.3;

        //[DataMember]
        //public string HeatingSetpointSchedule { get; set; }= "AllOn";
        //[DataMember]
        //public string CoolingSetpointSchedule { get; set; }= "AllOn";

        //[DataMember]
        //public bool HeatIsOn { get; set; } = true;
        //[DataMember]
        //public bool CoolIsOn { get; set; } = true;
        //[DataMember]
        //public bool MechVentIsOn { get; set; } = false;
        //[DataMember]
        //public bool HumidistatOnOff { get; set; } = false;

        //[DataMember]
        ////[JsonConverter(typeof(StringEnumConverter))]
        //public IdealSystemLimit HeatingLimitType { get; set; } = IdealSystemLimit.NoLimit;// "NoLimit";
        //[DataMember]
        ////[JsonConverter(typeof(StringEnumConverter))]
        //public IdealSystemLimit CoolingLimitType { get; set; } = IdealSystemLimit.NoLimit;// "NoLimit";
        //[DataMember]
        //[Units("W/m2")]
        //public double MaxHeatingCapacity { get; set; } = 100; //W/m2
        //[DataMember]
        //[Units("W/m2")]
        //public double MaxCoolingCapacity { get; set; } = 100;
        //[DataMember]
        //[Units("m3/s/m2")]
        //public double MaxHeatFlow { get; set; } = 100; //m3/s/m2
        //[DataMember]
        //[Units("m3/s/m2")]
        //public double MaxCoolFlow { get; set; } = 100;
        //[DataMember]
        //public string HeatingSchedule { get; set; } = "AllOn";
        //[DataMember]
        //public string CoolingSchedule { get; set; } = "AllOn";

        //[DataMember]
        //public string MechVentSchedule { get; set; } = "AllOn";
        //[DataMember]

        //[DataMember]
        ////[JsonConverter(typeof(StringEnumConverter))]
        //public EconomizerItem EconomizerType { get; set; } = EconomizerItem.NoEconomizer;//"NoEconomizer";
        //[DataMember]
        ////[JsonConverter(typeof(StringEnumConverter))]
        //public HeatRecoveryItem HeatRecoveryType { get; set; } = HeatRecoveryItem.None;// "None";
        //[DataMember]
        //public double HeatRecoveryEfficiencySensible { get; set; } = 0.7;
        //[DataMember]
        //public double HeatRecoveryEfficiencyLatent { get; set; } = 0.65;

        //[DataMember]
        //[Units("RH%")]
        //public double MinHumidity { get; set; } = 20;

        public HVACZoneVAV()
        {
        }
        public override string ToString() { return Serialization.Serialize(this); }
    }

    [DataContract(IsReference = true)]
    public class HVACSystemVAV : LibraryComponent
    {
        [DataMember]
        public double ChillerCOP { get; set; } = 3.2;

        [DataMember]
        public double BoilerEFF { get; set; } = 0.8;

        [DataMember]
        public string SystemAvailabilitySchedule { get; set; } = "AllOn";

        [DataMember]
        public double HeatingCoilSetpoint { get; set; } = 10.0;
        [DataMember]
        public double CoolingCoilSetpoint { get; set; } = 12.8;

        [DataMember]
        [Units("RH%")]
        public double HumidifierSetpoint { get; set; } = 30;
        [DataMember]
        [Units("RH%")]
        public double DehumidificationSetpoint { get; set; } = 80;

        [DataMember]
        public double SupplyFanTotalEfficiency { get; set; } = 0.7;
        [DataMember]
        public double SupplyFanDeltaPressure { get; set; } = 600;
        [DataMember]
        public double SupplyFanMotorEfficiency { get; set; } = 0.9;

        [DataMember]
        //[JsonConverter(typeof(StringEnumConverter))]
        public EconomizerItemHVACTemp EconomizerType { get; set; } = EconomizerItemHVACTemp.NoEconomizer;//"NoEconomizer";
        [DataMember]
        //[JsonConverter(typeof(StringEnumConverter))]
        public HeatRecoveryItem HeatRecoveryType { get; set; } = HeatRecoveryItem.None;// "None";
        [DataMember]
        public double HeatRecoveryEfficiencySensible { get; set; } = 0.7;
        [DataMember]
        public double HeatRecoveryEfficiencyLatent { get; set; } = 0.65;

        public DehumidificationControlType DehumidificationControlType { get; set; } = DehumidificationControlType.None;
        public HumidifierType HumidifierType { get; set; } = HumidifierType.None;

        public FanPartLoadPowerCoefficients FanPartLoadPowerCoefficients { get; set; } = FanPartLoadPowerCoefficients.InletVaneDampers;

        public HVACSystemVAV()
        {
        }
        public override string ToString() { return Serialization.Serialize(this); }
    }
}


text:
@interface IDEInstalliPhoneService : IDERunDeviceService
{
}

+ (id)capability;
- (id)operationWorkerWithLaunchSession:(id)arg1 error:(id *)arg2;

@end


text:
by [Ben Nadel][1] (on [Google+][2])

This is a small ColdFusion component that I use, as a sanity check, to inspect other
ColdFusion components that are cached in a production system. Snooper.cfc works by
injecting a public method that can access the target component's private variables scope.
Snooper.cfc then inspects the private variables and looks for potential variable leaks.

To inspect a component, instantiate the Snooper.cfc and call .snoop() on the target:

```cfc
// Get the manifest of private variables that may be leaking.
manifest = new lib.Snooper()
	// .includeFunctions()
	// .includeComponents()
	.excludeKeys( [ "password", "secretkey", "apiKey" ] )
	.snoop( application.thing )
;

writeDump( label = "Possible Leaks", manifest );
```

By default, private functions and private component references are excluded from the
manifest of private variables. However, you can include them if you want to be calling:

* .includeFunctions()
* .includeComponents()

You can also exclude arbitrary keys by passing an array of strings to:

* .excludeKeys( arrayOfKeys )

The .snoop() method also takes an optional filter function that will exclude keys:

* .snoop( target [, filterClosure] )

----

**CAUTION**: Never run this in "public" - always hide this behind some sort of
authentication or administrative tooling. This could expose very sensitive information
to anyone who can access it.

[1]: http://www.bennadel.com
[2]: https://plus.google.com/108976367067760160494?rel=author