text:
import {GithubConfig, setConfig} from '../../../../utils/config.js';
import {
  getMockGitClient,
  installSandboxGitClient,
  SandboxGitClient,
  SandboxGitRepo,
} from '../../../../utils/testing/index.js';
import {ReleaseConfig} from '../../../config/index.js';
import {ReleaseNotes} from '../../../notes/release-notes.js';
import {prepareTempDirectory} from '../test-utils/action-mocks.js';
import {changelogPattern, parse} from '../test-utils/test-utils.js';

describe('release notes generation', () => {
  let releaseConfig: ReleaseConfig;
  let githubConfig: GithubConfig;
  let client: SandboxGitClient;

  beforeEach(() => {
    // Clear the temporary directory used by the sandbox git client. We do not want
    // the repo state to persist between tests.
    prepareTempDirectory();

    releaseConfig = {
      npmPackages: [{name: 'test-pkg'}],
      representativeNpmPackage: 'test-pkg',
      buildPackages: async () => [],
    };
    githubConfig = {owner: 'angular', name: 'dev-infra-test', mainBranchName: 'main'};
    setConfig({github: githubConfig, release: releaseConfig});
    client = getMockGitClient(githubConfig, /* useSandboxGitClient */ true);

    installSandboxGitClient(client);
  });

  describe('changelog', () => {
    describe('categorization', () => {
      it('should group commits by scope by default', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(@angular-devkit/core): commit *1')
          .commit('fix(@angular-devkit/core): commit *2')
          .commit('fix(@angular-devkit/test): commit *3')
          .commit('fix(@angular-devkit/test): commit *4');

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### @angular-devkit/core
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | commit *1 |
          | <..> | fix | commit *2 |
          ### @angular-devkit/test
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | commit *3 |
          | <..> | fix | commit *4 |
          ## Special Thanks
        `);
      });

      it('should support custom group names', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): commit *1')
          .commit('fix(cdk/platform): commit *2')
          .commit('fix(material/autocomplete): commit *3')
          .commit('fix(material/slide-toggle): commit *4');

        releaseConfig.releaseNotes = {
          // Group commits in the release notes by package name.
          categorizeCommit: (commit) => ({groupName: commit.scope.split('/', 1)[0]}),
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | commit *1 |
          | <..> | fix | commit *2 |
          ### material
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | commit *3 |
          | <..> | fix | commit *4 |
          ## Special Thanks
        `);
      });

      it('should support custom descriptions', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): fix module definition')
          .commit('fix(cdk/platform): fix detection of chromium');

        releaseConfig.releaseNotes = {
          // Includes the secondary entry-point name in the commit description. This
          // replicates a scenario in the `angular/components` repository where the
          // commits are grouped by package name (e.g. `cdk`) but we still want to
          // incorporate the entry-point information in the release notes.
          categorizeCommit: (commit) => {
            const entryPoint = commit.scope.split('/')[1];
            return {description: `${entryPoint}: ${commit.subject}`};
          },
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk/a11y
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | a11y: fix module definition |
          ### cdk/platform
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | platform: fix detection of chromium |
          ## Special Thanks
        `);
      });

      it('should support custom group names together with custom descriptions', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): fix module definition')
          .commit('fix(cdk/platform): fix detection of chromium')
          .commit('fix(material/slider/testing): missing stabilization');

        releaseConfig.releaseNotes = {
          // Includes the secondary entry-point name in the commit description. This
          // replicates a scenario in the `angular/components` repository where the
          // commits are grouped by package name (e.g. `cdk`) but we still want to
          // incorporate the entry-point information in the release notes.
          categorizeCommit: (commit) => {
            const [packageName, ...entryPointParts] = commit.scope.split('/');
            const entryPoint = entryPointParts.join('/');
            return {
              groupName: packageName,
              description: `${entryPoint}: ${commit.subject}`,
            };
          },
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | a11y: fix module definition |
          | <..> | fix | platform: fix detection of chromium |
          ### material
          | Commit | Type | Description |
          | -- | -- | -- |
          | <..> | fix | slider/testing: missing stabilization |
          ## Special Thanks
        `);
      });
    });

    it('should convert pull request references to links', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .createTagForHead('startTag')
        .commit('fix(@angular-devkit/test): commit #1')
        .commit('fix(@angular-devkit/test): commit (#2)');

      const releaseNotes = await ReleaseNotes.forRange(client, parse('13.0.0'), 'startTag', 'HEAD');

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ### @angular-devkit/test
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | commit ([#2](<..>/pull/2)) |
        | <..> | fix | commit [#1](<..>/pull/1) |
        ## Special Thanks
      `);
    });

    it('should capture breaking changes', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with breaking change\n\n' +
            'BREAKING CHANGE: Description of breaking change.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Breaking Changes
        ### cdk/a11y
        - Description of breaking change.
        ### cdk/a11y
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | not yet released *1 |
        | <..> | refactor | with breaking change |
        ## Special Thanks
      `);
    });

    it('should capture multiple breaking changes from a single commit', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with breaking change\n\n' +
            'BREAKING CHANGE: Description of breaking change.\n\n' +
            'BREAKING CHANGE: Description of breaking change 2.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Breaking Changes
        ### cdk/a11y
        - Description of breaking change.
        - Description of breaking change 2.
        ### cdk/a11y
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | not yet released *1 |
        | <..> | refactor | with breaking change |
        ## Special Thanks
      `);
    });

    it('should indent breaking changes with bullets', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with breaking change\n\n' +
            'BREAKING CHANGE:\n' +
            'Description of breaking change.\n' +
            '- point 1\n' +
            '- point 2\n',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Breaking Changes
        ### cdk/a11y
        - Description of breaking change.
          - point 1
          - point 2
        ### cdk/a11y
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | not yet released *1 |
        | <..> | refactor | with breaking change |
        ## Special Thanks
      `);
    });

    it('should capture deprecations', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with deprecation\n\n' + 'DEPRECATED: Description of deprecation.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Deprecations
        ### cdk/a11y
        - Description of deprecation.
        ### cdk/a11y
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | not yet released *1 |
        | <..> | refactor | with deprecation |
        ## Special Thanks
      `);
    });

    it('should capture multiple deprecations from a single commit', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with deprecation\n\n' +
            'DEPRECATED: Description of deprecation.\n\n' +
            'DEPRECATED: Description of deprecation 2.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getChangelogEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Deprecations
        ### cdk/a11y
        - Description of deprecation.
        - Description of deprecation 2.
        ### cdk/a11y
        | Commit | Type | Description |
        | -- | -- | -- |
        | <..> | fix | not yet released *1 |
        | <..> | refactor | with deprecation |
        ## Special Thanks
      `);
    });
  });

  describe('github release notes', () => {
    describe('categorization', () => {
      it('should group commits by scope by default', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(@angular-devkit/core): commit *1')
          .commit('fix(@angular-devkit/core): commit *2')
          .commit('fix(@angular-devkit/test): commit *3')
          .commit('fix(@angular-devkit/test): commit *4');

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### @angular-devkit/core
          | Commit | Description |
          | -- | -- |
          | <..> | commit *1 |
          | <..> | commit *2 |
          ### @angular-devkit/test
          | Commit | Description |
          | -- | -- |
          | <..> | commit *3 |
          | <..> | commit *4 |
          ## Special Thanks
        `);
      });

      it('should support custom group names', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): commit *1')
          .commit('fix(cdk/platform): commit *2')
          .commit('fix(material/autocomplete): commit *3')
          .commit('fix(material/slide-toggle): commit *4');

        releaseConfig.releaseNotes = {
          // Group commits in the release notes by package name.
          categorizeCommit: (commit) => ({groupName: commit.scope.split('/', 1)[0]}),
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk
          | Commit | Description |
          | -- | -- |
          | <..> | commit *1 |
          | <..> | commit *2 |
          ### material
          | Commit | Description |
          | -- | -- |
          | <..> | commit *3 |
          | <..> | commit *4 |
          ## Special Thanks
        `);
      });

      it('should support custom descriptions', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): fix module definition')
          .commit('fix(cdk/platform): fix detection of chromium');

        releaseConfig.releaseNotes = {
          // Includes the secondary entry-point name in the commit description. This
          // replicates a scenario in the `angular/components` repository where the
          // commits are grouped by package name (e.g. `cdk`) but we still want to
          // incorporate the entry-point information in the release notes.
          categorizeCommit: (commit) => {
            const entryPoint = commit.scope.split('/')[1];
            return {description: `${entryPoint}: ${commit.subject}`};
          },
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk/a11y
          | Commit | Description |
          | -- | -- |
          | <..> | a11y: fix module definition |
          ### cdk/platform
          | Commit | Description |
          | -- | -- |
          | <..> | platform: fix detection of chromium |
          ## Special Thanks
        `);
      });

      it('should support custom group names together with custom descriptions', async () => {
        SandboxGitRepo.withInitialCommit(githubConfig)
          .createTagForHead('startTag')
          .commit('fix(cdk/a11y): fix module definition')
          .commit('fix(cdk/platform): fix detection of chromium')
          .commit('fix(material/slider/testing): missing stabilization');

        releaseConfig.releaseNotes = {
          // Includes the secondary entry-point name in the commit description. This
          // replicates a scenario in the `angular/components` repository where the
          // commits are grouped by package name (e.g. `cdk`) but we still want to
          // incorporate the entry-point information in the release notes.
          categorizeCommit: (commit) => {
            const [packageName, ...entryPointParts] = commit.scope.split('/');
            const entryPoint = entryPointParts.join('/');
            return {
              groupName: packageName,
              description: `${entryPoint}: ${commit.subject}`,
            };
          },
        };

        const releaseNotes = await ReleaseNotes.forRange(
          client,
          parse('13.0.0'),
          'startTag',
          'HEAD',
        );

        expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
          # 13.0.0 <..>
          ### cdk
          | Commit | Description |
          | -- | -- |
          | <..> | a11y: fix module definition |
          | <..> | platform: fix detection of chromium |
          ### material
          | Commit | Description |
          | -- | -- |
          | <..> | slider/testing: missing stabilization |
          ## Special Thanks
        `);
      });
    });

    it('should capture breaking changes', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with breaking change\n\n' +
            'BREAKING CHANGE: Description of breaking change.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Breaking Changes
        ### cdk/a11y
        - Description of breaking change.
        ### cdk/a11y
        | Commit | Description |
        | -- | -- |
        | <..> | not yet released *1 |
        | <..> | with breaking change |
        ## Special Thanks
      `);
    });

    it('should capture multiple breaking changes from a single commit', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with breaking change\n\n' +
            'BREAKING CHANGE: Description of breaking change.\n\n' +
            'BREAKING CHANGE: Description of breaking change 2.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Breaking Changes
        ### cdk/a11y
        - Description of breaking change.
        - Description of breaking change 2.
        ### cdk/a11y
        | Commit | Description |
        | -- | -- |
        | <..> | not yet released *1 |
        | <..> | with breaking change |
        ## Special Thanks
      `);
    });

    it('should capture deprecations', async () => {
      SandboxGitRepo.withInitialCommit(githubConfig)
        .commit('fix(cdk/a11y): already released *1')
        .createTagForHead('13.0.0-next.0')
        .commit('fix(cdk/a11y): not yet released *1')
        .commit(
          'refactor(cdk/a11y): with deprecation\n\n' + 'DEPRECATED: Description of deprecation.',
        );

      const releaseNotes = await ReleaseNotes.forRange(
        client,
        parse('13.0.0'),
        '13.0.0-next.0',
        'HEAD',
      );

      expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
        # 13.0.0 <..>
        ## Deprecations
        ### cdk/a11y
        - Description of deprecation.
        ### cdk/a11y
        | Commit | Description |
        | -- | -- |
        | <..> | not yet released *1 |
        | <..> | with deprecation |
        ## Special Thanks
      `);
    });
  });

  it('should capture multiple deprecations from a single commit', async () => {
    SandboxGitRepo.withInitialCommit(githubConfig)
      .commit('fix(cdk/a11y): already released *1')
      .createTagForHead('13.0.0-next.0')
      .commit('fix(cdk/a11y): not yet released *1')
      .commit(
        'refactor(cdk/a11y): with deprecation\n\n' +
          'DEPRECATED: Description of deprecation.\n\n' +
          'DEPRECATED: Description of deprecation 2.',
      );

    const releaseNotes = await ReleaseNotes.forRange(
      client,
      parse('13.0.0'),
      '13.0.0-next.0',
      'HEAD',
    );

    expect(await releaseNotes.getGithubReleaseEntry()).toMatch(changelogPattern`
      # 13.0.0 <..>
      ## Deprecations
      ### cdk/a11y
      - Description of deprecation.
      - Description of deprecation 2.
      ### cdk/a11y
      | Commit | Description |
      | -- | -- |
      | <..> | not yet released *1 |
      | <..> | with deprecation |
      ## Special Thanks
    `);
  });

  it('should determine the number of commits included in the entry', async () => {
    SandboxGitRepo.withInitialCommit(githubConfig)
      .createTagForHead('0.0.0')
      .commit('fix: first thing fixed')
      .commit('feat: first new thing')
      .commit('feat: second new thing')
      .commit('build: rework everything')
      .commit('fix: fix what we broke');

    const releaseNotes = await ReleaseNotes.forRange(client, parse('0.0.1'), '0.0.0', 'HEAD');

    expect(await releaseNotes.getCommitCountInReleaseNotes()).toBe(4);
  });

  it('should insert correct shortened and full shas for commits', async () => {
    const sandboxRepo = SandboxGitRepo.withInitialCommit(githubConfig)
      .createTagForHead('startTag')
      .commit('fix(ng-dev): commit *1', 1);

    const fullSha = sandboxRepo.getShaForCommitId(1, 'long');
    const shortSha = sandboxRepo.getShaForCommitId(1, 'short');

    const releaseNotes = await ReleaseNotes.forRange(client, parse('13.0.0'), 'startTag', 'HEAD');
    const changelog = await releaseNotes.getChangelogEntry();

    expect(changelog).toContain(
      `| [${shortSha}](https://github.com/angular/dev-infra-test/commit/${fullSha}) | fix | commit *1 |`,
    );
  });
});


text:
"use strict";

var _ = require("../helpers");
var timer = require('../timer');

/**
 *  Fire an event every day
 */
exports.DayTimer = function (paramd) {
    timer.Timer.call(this);
    this.schedule(_.defaults(paramd, {
        id: 'timer',
        name: "once per day",
        hour: 0,
        day_repeat: 1
    }));
};

exports.DayTimer.prototype = new timer.Timer();
exports.day_timer = _.make_function(exports.DayTimer, "day_repeat");

redpajama_set_name: RedPajamaGithub


text:
package trie

/*
 * ASCII tries are a special case because the maximum size of the
 * children is already known.
 * Mulitple implementations are provided, depending on the need:
 * - ASCIITrie: simple naive approach. Use for small alphabets.
 * - ASCIIReduxTrie: uses alphabet reduction. Use for larger alphabets.
 */

import "fmt"

// invalid is used as a return value when a string could not be parsed
const invalid = -1

// NewASCIITrie creates a new trie holding strings.
func NewASCIITrie() *ASCIITrie {
	return &ASCIITrie{isRoot: true}
}

func newASCIITrieNode() *ASCIITrie {
	return &ASCIITrie{isRoot: false}
}

// Add adds a new word to an existing string trie.
func (t *ASCIITrie) Add(s string) error {
	if len(s) == 0 {
		t.isFullWord = true
		return nil
	}
	c, err := next(s)
	if err != nil {
		return err
	}
	if t.children[c] == nil {
		t.children[c] = newASCIITrieNode()
	}
	t.children[c].data = byte(c)
	return t.children[c].Add(s[1:])
}

// Contains returns true if a string trie contains the given word.
func (t *ASCIITrie) Contains(s string) bool {
	if s == "" {
		return false
	}
	c, err := next(s)
	if err != nil {
		return false
	}
	if t.children[c] == nil {
		return false
	}
	if len(s) == 1 {
		return true
	}
	return t.children[c].Contains(s[1:])
}

func next(s string) (byte, error) {
	c := s[0]
	if c > 255 {
		return byte(0), fmt.Errorf("Unexpected character in %v", s)
	}
	return c, nil
}

// NewASCIIReduxTrie creates a new trie holding strings.
func NewASCIIReduxTrie() *ASCIIReduxTrie {
	return &ASCIIReduxTrie{isRoot: true, suffixByteMask: true}
}

func newASCIIReduxTrieNode(byteMask bool) *ASCIIReduxTrie {
	return &ASCIIReduxTrie{isRoot: false, suffixByteMask: byteMask}
}

// Add adds a new word to an existing string trie.
func (t *ASCIIReduxTrie) Add(s string) error {
	if len(s) == 0 {
		t.isFullWord = true
		return nil
	}
	data, err := next4(s, t.suffixByteMask)
	if err != nil {
		return err
	}
	if t.children[data] == nil {
		t.children[data] = newASCIIReduxTrieNode(!t.suffixByteMask)
	}
	t.children[data].data = byte(data)
	if t.suffixByteMask {
		return t.children[data].Add(s[1:])
	} else {
		return t.children[data].Add(s)
	}
}

// Contains returns true if a string trie contains the given word.
func (t *ASCIIReduxTrie) Contains(s string) bool {
	if s == "" {
		return false
	}
	c, err := next4(s, t.suffixByteMask)
	if err != nil {
		return false
	}
	if t.children[c] == nil {
		return false
	}
	if len(s) == 1 {
		return true
	}
	if t.suffixByteMask {
		return t.children[c].Contains(s[1:])
	} else {
		return t.children[c].Contains(s)
	}
}

// Returns the next 4 bits word in the given string
func next4(s string, suffixByteMask bool) (int, error) {
	c := s[0]
	if c > 255 {
		return invalid, fmt.Errorf("Unexpected character in %v", s)
	}
	data := int(c)
	if suffixByteMask {
		data = data & 0x0f
	} else {
		data = data >> 4 // shift to obtain a 4 bit integer
	}
	return data, nil
}


text:
package dataMapper.diagram.edit.helpers;

/**
 * @generated
 */
public class OperatorBasicContainerEditHelper extends
		dataMapper.diagram.edit.helpers.DataMapperBaseEditHelper {
}


text:
MenuBarModel::MenuBarModel() noexcept
    : manager (nullptr)
{
}

MenuBarModel::~MenuBarModel()
{
    setApplicationCommandManagerToWatch (nullptr);
}

//==============================================================================
void MenuBarModel::menuItemsChanged()
{
    triggerAsyncUpdate();
}

void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) noexcept
{
    if (manager != newManager)
    {
        if (manager != nullptr)
            manager->removeListener (this);

        manager = newManager;

        if (manager != nullptr)
            manager->addListener (this);
    }
}

void MenuBarModel::addListener (Listener* const newListener) noexcept
{
    listeners.add (newListener);
}

void MenuBarModel::removeListener (Listener* const listenerToRemove) noexcept
{
    // Trying to remove a listener that isn't on the list!
    // If this assertion happens because this object is a dangling pointer, make sure you've not
    // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
    jassert (listeners.contains (listenerToRemove));

    listeners.remove (listenerToRemove);
}

//==============================================================================
void MenuBarModel::handleAsyncUpdate()
{
    listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
}

void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
{
    listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
}

void MenuBarModel::applicationCommandListChanged()
{
    menuItemsChanged();
}


text:
SELECT c.CompanyName, a.AddressLine1, a.City, 'Billing' AS AddressType
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Main Office';

-- Shipping addresses
SELECT c.CompanyName, a.AddressLine1, a.City, 'Shipping' AS AddressType
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Shipping';

-- All customer addresses
SELECT c.CompanyName, a.AddressLine1, a.City, 'Billing' AS AddressType
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Main Office'
UNION ALL
SELECT c.CompanyName, a.AddressLine1, a.City, 'Shipping' AS AddressType
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Shipping'
ORDER BY c.CompanyName, AddressType;


text:
<bill session="115" type="s" number="1815" updated="2017-09-26T04:30:39Z">
  <state datetime="2017-09-14">REFERRED</state>
  <status>
    <introduced datetime="2017-09-14"/>
  </status>
  <introduced datetime="2017-09-14"/>
  <titles>
    <title type="short" as="introduced">Data Broker Accountability and Transparency Act of 2017</title>
    <title type="short" as="introduced">Data Broker Accountability and Transparency Act of 2017</title>
    <title type="official" as="introduced">A bill to require data brokers to establish procedures to ensure the accuracy of collected personal information, and for other purposes.</title>
    <title type="display">Data Broker Accountability and Transparency Act of 2017</title>
  </titles>
  <sponsor bioguide_id="M000133"/>
  <cosponsors>
    <cosponsor bioguide_id="B001277" joined="2017-09-14"/>
    <cosponsor bioguide_id="F000457" joined="2017-09-14"/>
    <cosponsor bioguide_id="S000033" joined="2017-09-14"/>
    <cosponsor bioguide_id="W000802" joined="2017-09-14"/>
  </cosponsors>
  <actions>
    <action datetime="2017-09-14">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-09-14" state="REFERRED">
      <text>Read twice and referred to the Committee on Commerce, Science, and Transportation.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSCM" name="Senate Commerce, Science, and Transportation" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Science, technology, communications"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
{
  "title": "I'm absolutely blown away by the quality and quantity of submissions for week 1 of #TidyTuesday ! Thanks to all who participated or spread the word. I have compiled the plots into a blog post, take a look! https://t.co/hyO9Ruuepp #rstats #R4DS #blogdown #DataViz @kierisi https://t.co/MzIAYijRps",
  "date": "2018-04-07"
}

# blogdown

> **Thomas Mock** (@thomas_mock; 77/25): I'm absolutely blown away by the quality and quantity of submissions for week 1 of #TidyTuesday ! Thanks to all who participated or spread the word.
>
I have compiled the plots into a blog post, take a look!
>
https://t.co/hyO9Ruuepp
>
#rstats #R4DS #blogdown #DataViz @kierisi https://t.co/MzIAYijRps  [↪](https://twitter.com/xieyihui/status/982243552808787968)

<!-- -->

> **Athanasia Mowinckel** (@DrMowinckels; 1/1): #rstats #blogdown #GAMM #academia #statistics  [↪](https://twitter.com/xieyihui/status/982135026232975363)

<!-- -->

> **Scott Chamberlain** (@sckottie; 0/3): Any #rstats peeps do blogdown consulting? DM me or similar if interested | #pdxrlang  [↪](https://twitter.com/xieyihui/status/982292145749962753)

<!-- -->

# bookdown

> **SAKAUE Akkuş Tatsuya** (@sakaue; 2/0): ひろたんも充実してきたし,マニュアルは bookdown で書いてみようかな...。https://t.co/pNQjMl54C0  [↪](https://twitter.com/xieyihui/status/982164489289150464)

<!-- -->

> **Denis Schluppeck** (@schluppeck; 1/0): took some time to start converting my materials from reStructuredText to #markdown + https://t.co/3ToA7nVGTR - amazingly good @rstudio @xieyihui  [↪](https://twitter.com/xieyihui/status/982280055329034240)

<!-- -->

> **Burak AYDIN** (@Burak_AYD1N; 0/0): @kylehamilton @tcarpenter216 @lysanderjames Thanks Kyle. Bookdown is a great package, we tried to make use of it.  [↪](https://twitter.com/xieyihui/status/982300167125729282)

<!-- -->

> **まつーらとしお** (@yearman; 0/0): bookdownなるものがあるのね  [↪](https://twitter.com/xieyihui/status/982143196808400899)

<!-- -->

# knitr

> **Sean Davis** (@seandavis12; 3/1): The poster is a beamerposter with figures and data generated dynamically from the repository using the ever-amazing knitr #rstats package from @xieyihui and a combo of the tm, wordcloud, ggplot, dplyr, stringr, and gh packages.  [↪](https://twitter.com/xieyihui/status/982226580876345345)

<!-- -->

# xaringan

> **Alison Hill** (@apreshill; 24/14): #xaringan slides + GitHub repo for my "Take A Sad Plot & Make It Better" talk today: https://t.co/h7Aph173Kw #ggplot2 #rstats https://t.co/p50d4QocRj  [↪](https://twitter.com/xieyihui/status/982424211590230016)

<!-- -->

> **Martin John Hadley** (@martinjhnhadley; 0/0): The best thing about using the xaringan RMarkdown presentation format over slidy? I no longer need to escape @ in Markdown links 😍 https://t.co/f89K9P1lk2  [↪](https://twitter.com/xieyihui/status/982201746557550597)

<!-- -->


text:
package org.keycloak.testsuite.util;

import java.util.List;
import static org.junit.Assert.assertEquals;

/**
 *
 * @author tkyjovsk
 */
public class AttributesAssert {

    public static void assertEqualsStringAttributes(String a1, String a2) {
        if (a1 == null) {
            a1 = "";
        }
        if (a2 == null) {
            a2 = "";
        }
        assertEquals(a1, a2);
    }

    public static void assertEqualsBooleanAttributes(Boolean a1, Boolean a2) {
        if (a1 == null) {
            a1 = false;
        }
        if (a2 == null) {
            a2 = false;
        }
        assertEquals(a1, a2);
    }

    public static void assertEqualsListAttributes(List a1, List a2) {
        if (a1 == null || a1.isEmpty()) {
            a1 = null;
        }
        if (a2 == null || a2.isEmpty()) {
            a2 = null;
        }
        assertEquals(a1, a2);
    }

}


text:
package info.dgjones.abora.ug2java.transform.method.intra;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import info.dgjones.abora.ug2java.JavaMethod;
import info.dgjones.abora.ug2java.javatoken.JavaCallEnd;
import info.dgjones.abora.ug2java.javatoken.JavaCallStart;
import info.dgjones.abora.ug2java.javatoken.JavaCast;
import info.dgjones.abora.ug2java.javatoken.JavaKeyword;
import info.dgjones.abora.ug2java.javatoken.JavaToken;
import info.dgjones.abora.ug2java.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.abora.ug2java.transform.tokenmatcher.TokenMatcher;
import info.dgjones.abora.ug2java.transform.tokenmatcher.TokenMatcherFactory;

public class TransformUnaryOperator extends AbstractMethodBodyTransformation {

	private static final Map operators;
	static {
		Map map = new HashMap();
		map.put("not", "!");
		map.put("bitInvert", "~");
		map.put("negated", "-");
		operators = Collections.unmodifiableMap(map);
	}

	private static final Map operatorCasts;
	static {
		Map map = new HashMap();
		map.put("asDouble", "double");
		map.put("asFloat", "float");
		map.put("asInteger", "int");
		operatorCasts = Collections.unmodifiableMap(map);
	}

	public TransformUnaryOperator() {
		super();
	}

	public TransformUnaryOperator(TokenMatcherFactory factory) {
		super(factory);
	}

	protected TokenMatcher matchers(TokenMatcherFactory factory) {
		return factory.seq(
				factory.token(JavaCallStart.class, regularExpressionOr(operators.keySet(), operatorCasts.keySet())),
				factory.token(JavaCallEnd.class));
	}

	protected int transform(JavaMethod javaMethod, List tokens, int i) {
		String smalltalkCall = ((JavaCallStart)tokens.get(i)).value;
		int expressionStart = javaMethod.methodBody.findStartOfExpressionMinimal(i-1);
		tokens.remove(i + 1);
		tokens.remove(i);
		JavaToken operator;
		String match = (String)operators.get(smalltalkCall);
		if (match != null) {
			operator = new JavaKeyword(match);
		} else {
			match = (String)operatorCasts.get(smalltalkCall);
			operator = new JavaCast(match);
		}
		tokens.add(expressionStart, operator);

		return i;
	}
}


text:
guid: 98ee02b5-4599-4332-a377-cc032d9d9dad
type: Live
reformat: True
shortenReferences: True
categories: bootstrap 4
scopes: InHtmlLikeFile
parameterOrder: size, stripped, hover, border, inverse
size-expression: list(",table-sm")
stripped-expression: list(",table-stripped")
hover-expression: list(",table-hover")
border-expression: list(",table-bordered")
inverse-expression: list(",table-inverse")
reflow-expression: list(",table-reflow")
---

# bs4-table-responsive

Table responsive

```
<div class="table-responsive">
	<table class="table $size$ $stripped$ $hover$ $border$ $inverse$ $reflow$">
	    <thead>
	        <tr>
	            <th>Header</th>
	        </tr>
	    </thead>
	    <tbody>
	        <tr>
	            <td>Content</td>
	        </tr>
	    </tbody>
	</table>
</div>
```


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/*--------------------------------------------------------------------------- */

package image

import (
	dyn "github.com/OpenNebula/one/src/oca/go/src/goca/dynamic"
	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/image/keys"
)

// Types is a type used to enumerate image types
type Types string

const (
	// Virtual Machine disks
	Datablock Types = "DATABLOCK"
	CDRom     Types = "CDROM"
	OS        Types = "OS"

	// File types, can be registered only in File Datastores
	Kernel  Types = "KERNEL"
	RamDisk Types = "RAMDISK"
	Context Types = "CONTEXT"
)

// Template is the dynamic part of the image entity
type Template struct {
	dyn.Template
}

// NewTemplate returns an image template
func NewTemplate() *Template {
	return &Template{
		dyn.Template{},
	}
}

// Get return the string value of a template image key
func (t *Template) Get(key keys.Template) (string, error) {
	return t.GetStr(string(key))
}

// GetI returns the integer value for an image template key
func (n *Template) GetI(key keys.Template) (int, error) {
	return n.GetInt(string(key))
}

// Add adds an image template key, value pair
func (t *Template) Add(key keys.Template, value interface{}) {
	t.AddPair(string(key), value)
}

// SetType set an Image type
func (t *Template) SetType(typ Types) {
	pair, err := t.GetPair(string(keys.Type))
	if err != nil {
		t.AddPair(string(keys.Type), string(typ))
	} else {
		pair.Value = string(typ)
	}
}


text:
package ru.parsersqlru;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by nikolay on 31/07/17.
 */
public class MyTimer extends TimerTask {
    /**
     * Flag for stop threads.
     */
    private static volatile boolean flag = true;
    /**
     * Capacity of queue.
     */
    private static final int CAPACITY = 1000;
    /**
     * Logger.
     */
    private static final Logger LOGGER = LogManager.getRootLogger();
    /**
     * Nums of avalable procs.
     */
    private static final int N_THREADS = Runtime.getRuntime().availableProcessors();
    /**
     * Start parse.
     * @param lastParse - date of last parse.
     */
    private void startParse(Date lastParse) {
        final BlockingQueue<String> bq = new ArrayBlockingQueue<>(CAPACITY);
        final ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);

        Runnable producer;
        producer = new Runnable() {
            public void run() {
                LinkParser linkParser = new LinkParser(bq, lastParse);
                linkParser.parse("http://www.sql.ru/forum/");

                while (true) {
                    if (bq.isEmpty()) {
                        flag = false;
                        executor.shutdown();
                        try {
                            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                                executor.shutdownNow();
                            }
                        } catch (InterruptedException e) {
                            LOGGER.error(e.getMessage());
                        }
                        break;
                    }
                }
            }
        };
        executor.execute(producer);

        Runnable consumer;
        for (int i = 0; i < N_THREADS; i++) {
            consumer = new Runnable() {
                public void run() {
                    WorkWithDB db = new WorkWithDB();
                    AdParser adParser = new AdParser(db);
                    do {
                        try {
                            adParser.parse(bq.take());
                        } catch (InterruptedException e) {
                            LOGGER.info("End of thread " + Thread.currentThread().getName());
                        }
                    } while (flag);
                }
            };
            executor.execute(consumer);
        }
    }
    /**
     * Write date of last parse to file.
     * @param path - path to file.
     */
    private void writeDate(String path) {
        try (FileWriter writer = new FileWriter(path, false)) {
            writer.write(String.valueOf(new Date().getTime()));
            writer.append('\n');
            writer.flush();
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void run() {
        Date lastParse = null;
        String path = "parser.data";

        File file = new File(path);
        if (file.exists()) {
            try (BufferedReader in = new BufferedReader(new FileReader(file.getAbsoluteFile()))) {
                String s;
                while ((s = in.readLine()) != null) {
                    lastParse = new Date(Long.parseLong(s));
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (NumberFormatException e) {
                writeDate(path);
            }
            writeDate(path);
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                LOGGER.fatal(e.getMessage());
            }
            writeDate(path);
        }

        startParse(lastParse);
    }
}


text:
local module = require("hs.battery.internal")
local fnutils = require("hs.fnutils")

-- private variables and methods -----------------------------------------

local check_list = {}
for i,v in pairs(module) do check_list[#check_list + 1] = i end

local __tostring_for_tables = function(self)
    local result = ""
    local width = 0
    for i,v in fnutils.sortByKeys(self) do
        if type(i) == "string" and width < i:len() then width = i:len() end
    end
    for i,v in fnutils.sortByKeys(self) do
        if type(i) == "string" then
            result = result..string.format("%-"..tostring(width).."s %s\n", i, tostring(v))
        end
    end
    return result
end

-- Public interface ------------------------------------------------------

module.watcher = require("hs.battery.watcher")

--- hs.battery.getAll() -> table
--- Function
--- Get all available battery information
---
--- Parameters:
---  * None
---
--- Returns:
---  * A table containing all the information provided by the separate functions in hs.battery
---
--- Notes:
---  * If you require multiple pieces of information about a battery, this function may be more efficient than calling several other functions separately
module.getAll = function()
    local t = {}

    for i, v in ipairs(check_list) do
        t[v] = module[v]()
        if t[v] == nil then t[v] = "n/a" end
    end

    return setmetatable(t, {__tostring = __tostring_for_tables })
end

-- Return Module Object --------------------------------------------------

return module


text:
CONTEXT(OCDSpecIntegerSpec)
{
    describe(@"toBeFailing",
             it(@"is a failling test",
                ^{
                    expectTruth(false);
                }),

             nil); // Don't forget the terminating nil
}


text:
package overview.ovp.viz;

import java.util.*;
import java.util.concurrent.*;
import overview.util.*;
import processing.core.*;

import processing.opengl.*;

public class ForceVisualization implements Renderer {

	private PApplet r2;
	private ForceEntity toplevel;
	private Map<String, ForceEntity> entities;
	private Set communications;

	private HashMap<ForceEntity, Integer> entityColor;

	float cx = 0, cy = 0;
	float dx = 0, dy = 0;
	float d = 0;
	float mx = 0, my = 0;
	float dim;
	float camx, camy, cams;

	private ForceEntity preselected = null;
	int c = 0;
	public long startTime;
	private boolean firstEvent = true;

	public ForceVisualization(PApplet r) {

		r2 = r; // render to r
		dim = Math.min(r2.width, r2.height) / 2;
		camx = 0;
		camy = 0;
		cams = dim;
		r2.textFont(r2.loadFont("trebuchetms.vlw"), 12);
		// initialize the entity tree
		toplevel = new ForceEntity("toplevel", r2.height / 2, r2.width / 2);
		entities = new ConcurrentHashMap<String, ForceEntity>();
		communications = Collections.synchronizedSet(new HashSet<Communication>());

		entityColor = new HashMap<ForceEntity, Integer>();
	}

	public void draw() {

		r2.background(0);
		r2.pushMatrix();

		// translate so that the centroid is in the center of the visualization
		r2.translate((r2.width / 2) - cx, (r2.height / 2) - cy);
		// forces
		if (r2.mousePressed && preselected != null) {
			preselected.vx += (mx - preselected.x) / 2;
			preselected.vy += (my - preselected.y) / 2;
		}
		// repel all other entities
		for (Iterator i = entities.values().iterator(); i.hasNext();) {
			ForceEntity e = (ForceEntity) i.next();
			for (Iterator j = entities.values().iterator(); j.hasNext();)
				e.repel((ForceEntity) j.next());

		}

		synchronized (communications) {
			for (Iterator i = communications.iterator(); i.hasNext();)
				((Communication) i.next()).update();
		}

		for (Iterator i = entities.values().iterator(); i.hasNext();)
			((ForceEntity) i.next()).resolve();

		// draw communications
		synchronized (communications) {
			for (Iterator k = communications.iterator(); k.hasNext();) {
				Communication comm = (Communication) k.next();
				r2.strokeWeight(dim / cams);
				comm.draw();
				r2.line(comm.source.x, comm.source.y, comm.target.x, comm.target.y);
			}
		}

		// draw entities
		for (Iterator l = entities.values().iterator(); l.hasNext();)
			((ForceEntity) l.next()).draw();

		// find camera position using the centroid
		int c = 0;
		cx = 0;
		cy = 0;
		for (ForceEntity fe : entities.values()) {
			++c;
			cx += fe.x;
			cy += fe.y;
		}

		if (c != 0) {
			cx /= c;
			cy /= c;
		}

		// find distance to furthest point from centroid
		d = 0;
		for (Iterator i = entities.values().iterator(); i.hasNext();) {
			ForceEntity e = (ForceEntity) i.next();

			d = Math.max(d, r2.dist(cx, cy, e.x, e.y) + 32);
		}

		// scale camera using furthest point in each axis
		dx = 0;
		dy = 0;
		for (ForceEntity fe : entities.values()) {
			dx = Math.max(dx, Math.abs(cx - fe.x));
			dy = Math.max(dy, Math.abs(cy - fe.y));
		}

		mx = (r2.mouseX - r2.width / 2) * cams / dim + camx;
		my = (r2.mouseY - r2.height / 2) * cams / dim + camy;

		r2.popMatrix();
		// draw conventions
		int c1 = 1;
		for (ForceEntity fe : entityColor.keySet()) {
			r2.fill(entityColor.get(fe));
			r2.stroke(entityColor.get(fe));
			r2.ellipse(r2.width - 150, (r2.height - 100) - (20 * c1), 10, 10);
			r2.text(fe.getName(), r2.width - 130, (r2.height - 100) - (20 * c1));
			c1++;
		}
		r2.fill(255);
		r2.textAlign(r2.LEFT);
	}

	void position(String name) {
		if (!entities.containsKey(name))
			entities.put(name, new ForceEntity(name, r2.random(camx - cams, camx + cams), r2.random(camy - cams, camy
					+ cams)));
	}

	void deletion(String name) {
		entities.remove(name);
		synchronized (communications) {
			for (Iterator i = communications.iterator(); i.hasNext();) {
				Communication c = (Communication) i.next();

				if (c.source.name.equals(name) || c.target.name.equals(name))
					i.remove();
			}
		}
	}

	void mousePressed() {
		System.out.println("MOUSE PRESSED");
		System.out.println(r2.mouseX + "," + r2.mouseY);
		ForceEntity selected = null;
		for (Iterator i = entities.values().iterator(); i.hasNext();) {
			ForceEntity e = (ForceEntity) i.next();
			if (e.inside(mx, my))
				selected = e;
		}

		if (r2.mouseButton == r2.LEFT) {
			if (selected == null) {
				if (preselected == null)
					position("ForceEntity " + c++);

				preselected = null;
			} else {
				if (preselected == null)
					preselected = selected;

				else {
					communicate(preselected, selected);
					preselected = null;
				}
			}
		}

		else if (r2.mouseButton == r2.RIGHT) {
			if (selected != null)
				deletion(selected.name);

			preselected = null;
		}
	} // closes mouse pressed

	private void communicate(ForceEntity alice, ForceEntity bob) {
		synchronized (communications) {
			try {
				communications.add(new Communication(alice, bob));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private ForceEntity getEntity(String name) {
		return getEntity(name, null);
	}

	private ForceEntity getEntity(String name, ForceEntity parent) {

		// if such an entity exists, return it
		if (entities.containsKey(name)) {
			ForceEntity c = entities.get(name);

			// handle migratory cases
			// skip migration if parent is null.
			if (parent != null && c.getParent() != parent)
				c.setParent(parent);

			return c;

		}

		// otherwise, put a new entry in the map and return THAT
		ForceEntity c = parent == null ? new ForceEntity(name, toplevel, toplevel) : new ForceEntity(name, parent,
				toplevel);

		entities.put(name, c);
		return c;
	}

	public void handle(String[] event) {
		if (firstEvent && entities.size() > 8) {
			startTime = System.currentTimeMillis();
			firstEvent = false;
		}
		for (int i = 0; i < event.length; i++)
			System.out.print("-" + event[i]);
		System.out.print("\n");

		for (int i = 0; i < event.length; i++)
			if (event[i].trim().length() == 0) {
				System.err.println("ZERO LENGTH EVENT OR EVENT ARGUMENT RECEIVED");
				return;
			}

		if (event == null || event.length == 0) {
			System.err.println("NULL EVENT RECEIVED.");
			return;
		}
		// creation and migration are handled EXACTLY the same.
		// I think this is a failing of the event selection in OverView.
		// I would merge the two into a single event, but I'm not yet
		// sure if the will always be the same (ie. in other types of
		// visualizations).
		else if (event[0].equals("creation") || event[0].equals("migration")) {
			if (event.length == 3) {
				// System.out.println("MIGRATION!!!");
				getEntity(event[1], getEntity(event[2]));
				return;
			}

			else if (event.length == 2) {
				getEntity(event[1]);
				return;
			}
		}

		else if (event[0].equals("deletion") && event.length == 2) {
			// getEntity (event[1]).hibernate ();
			// System.out.println("ENTITY DELETED.");
			return;
		}

		else if (event[0].equals("communication") && event.length == 3) {
			if (!event[1].equals(event[2]))
				communicate(getEntity(event[1]), getEntity(event[2]));
			return;
		}

		System.err.println("BAD EVENT: " + event[0] + " (" + Strings.join(", ", event, 1) + ")");
	}

	public void unhandle(String[] event) {
		if (event == null || event.length == 0)
			System.err.println("NULL UNDO EVENT RECEIVED.");

		// roll back the entity's state.
		// I love how creation, migration, and deletion are all
		// handled the exact same way
		else if (event[0].equals("creation") || event[0].equals("migration") || event[0].equals("deletion")) {
			getEntity(event[1]).rollback();
		}

		else if (event[0].equals("communication") && event.length == 3) {
			if (!event[1].equals(event[2]))
				communicate(getEntity(event[1]), getEntity(event[2]));
			return;
		}

		else
			System.err.println("BAD UNDO EVENT: " + event[0] + " (" + Strings.join(", ", event, 1) + ")");

	}

	public class ForceEntity {

		static final float k = 4096;
		public int level;
		public float x, y, tx, ty, tr, vx, vy;

		private ForceEntity toplevel;
		private Stack<ForceEntity> parent;
		private List<ForceEntity> children, orphans;
		private Integer containerColor;

		public String name;

		boolean container, drawn;

		// create toplevel entity
		public ForceEntity(String name, float x, float y) {
			this.x = x;
			this.y = y;
			this.name = name;

			toplevel = this;
			container = false;
			parent = null; // toplevel HAS no parent
			System.out.println("ENTITY CREATED name:" + name + " at coordinates: " + this.x + "," + this.y);

			double vx = 0;
			double vy = 0;

			children = Collections.synchronizedList(new LinkedList<ForceEntity>());
			orphans = Collections.synchronizedList(new LinkedList<ForceEntity>());
		}

		// create an entity inside a parent
		public ForceEntity(String n, ForceEntity p, ForceEntity t) {

			this.name = n;
			this.x = r2.random(0, r2.width);
			this.y = r2.random(0, r2.height);
			// TODO: assign values to tx and ty
			parent = new Stack<ForceEntity>();
			toplevel = t;
			container = p == t;
			drawn = false;

			children = Collections.synchronizedList(new LinkedList<ForceEntity>());
			setParent(p);

			System.out.println("ENTITY CREATED name:" + p.name + "," + name + " at coordinates: " + this.x + ","
					+ this.y);
		}

		void repel(ForceEntity e) {
			if (e == this /* || this.container || e.container */)
				return;

			double dx = x - e.x;
			double dy = y - e.y;
			double d2 = Math.pow(dx, 2) + Math.pow(dy, 2);
			double d = Math.sqrt(d2);
			double f = k / d2; // coulomb's law - masses are not considered

			vx += dx * f / d;
			vy += dy * f / d;

		}

		void resolve() {
			x += vx;
			vx = 0;
			y += vy;
			vy = 0;
		}

		void draw() {
			if (parent != null && !parent.isEmpty()) {
				int color = 0;
				// get color assigned to parent
				if (entityColor.containsKey(parent.peek()))
					color = (Integer) entityColor.get(parent.peek());
				else {
					// generate color
					System.out.println("GENERATING RANDOM COLOR...");
					Random randomGenerator = new Random();
					color = r2.color(randomGenerator.nextInt(256), randomGenerator.nextInt(256), randomGenerator
							.nextInt(256));
					entityColor.put(parent.peek(), color);
					System.out.println(color);
				}
				r2.fill(color);
				r2.stroke(color);
				r2.ellipse(this.x, this.y, 20, 20);
			} else {
				r2.fill(0);
				r2.stroke(255);
				r2.ellipse(this.x, this.y, 20, 20);
				// r2.text("orphan"+"."+name, x, y + 4);
			}
			// r2.fill(255);
			// r2.text(name, x+15, y);
		}

		boolean inside(float x, float y) {
			return r2.dist(this.x, this.y, x, y) < 16;
		}

		// public void hibernate() {
		// ForceEntity p = getParent();
		// if (p != null) {
		// tx = p.tx;
		// ty = p.ty;
		// }
		// tr = 0;
		// setParent(null); // no parent for me
		//
		// // note that we're now orphaned
		// toplevel.addOrphan(this);
		// }

		public ForceEntity getParent() {
			if (parent == null)
				return null; // toplevel has no parent

			try {
				return parent.peek();
			} // return the parent if it exists
			catch (EmptyStackException e) {
				return null;
			} // or not
		}

		public void setParent(ForceEntity p) {
			// if we have a parent, remove ourselves from their children
			ForceEntity par = getParent();
			if (par != null)
				par.removeChild(this);

			// otherwise, this is a creation message.
			// add ourselves to our new parent
			if (p != null) {
				p.addChild(this);
				level = p.level + 1;
			}
			if (parent != null)
				parent.push(p);

			// same as above. if p is not null, ensure we're not orphaned
			// otherwise, make sure we are
			if (p != null)
				toplevel.removeOrphan(this);
			else
				toplevel.addOrphan(this);
		}

		public void addOrphan(ForceEntity orphan) {
			if (orphans != null)
				orphans.add(orphan);
		}

		public void removeOrphan(ForceEntity orphan) {
			if (orphans != null)
				orphans.remove(orphan);
		}

		public void addChild(ForceEntity child) {
			children.add(child);
			// repositionChildren ();
		}

		public void removeChild(ForceEntity child) {
			children.remove(child);
			// repositionChildren ();
		}

		public void rollback() {
			if (parent == null)
				return; // toplevel can't roll back, silly

			ForceEntity par = null;

			try {
				par = parent.pop();
				if (par != null)
					par.removeChild(this);

				ForceEntity par2 = parent.peek();

				// this is undoing a deletion
				// so, we move to the parent, like we would in a
				// creation
				if (par == null) {
					x = par2.x;
					y = par2.y;

				}

				if (par2 != null)
					par2.addChild(this);

				// undo creation
				else
					throw new Exception();

				// if we've been orphaned, note it
				if (par2 == null)
					toplevel.addOrphan(this);
				else
					toplevel.removeOrphan(this);
			}

			// either we rolled back to the beginning (empty stack)
			// or we undid a creation message
			// draw ourselves disappear
			catch (Exception e) {
				if (par != null) {
					tx = par.tx;
					ty = par.ty;
				}
				tr = 0;

				// we're orphaned
				toplevel.addOrphan(this);
			}
		}

		public String getName() {
			return this.name;
		}

		public float getX() {
			return this.x;
		}

		public float getY() {
			return this.y;
		}

	} // closes ForceEntity

	// TODO: message instead of communication
	public class Communication {
		static final double k = .0625, l = 64;

		ForceEntity source, target;

		public Communication(ForceEntity a, ForceEntity b) throws Exception {
			if (a == null || b == null)
				throw new Exception("communications can't have null pointers!");
			this.source = a;
			this.target = b;

		}

		void update() {
			double dx = this.target.x - this.source.x == 0 ? 1 : this.target.x - this.source.x;
			double dy = this.target.y - this.source.y == 0 ? 0 : this.target.y - this.source.y;

			double d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
			double f = k * (d - l);

			source.vx += dx * f / d;
			target.vx -= dx * f / d;
			source.vy += dy * f / d;
			target.vy -= dy * f / d;
		}

		void draw() {
			r2.stroke(255);
			r2.strokeWeight(dim / cams);
			r2.line(source.x, source.y, target.x, target.y);
		}

		public ForceEntity getSource() {
			return this.source;
		}

		public ForceEntity getTarget() {
			return this.target;
		}

		// the two below line are used to make sure that A => B is the same as B
		// => A, for efficient checking.
		// however, this demands that a HashSet is used, otherwise hashCode sits
		// doing nothing.
		public boolean equals(Object rhs) {
			return rhs instanceof Communication && hashCode() == rhs.hashCode();
		}

		public int hashCode() {
			return source.hashCode() ^ target.hashCode();
		}
	}

} // closes ForceVisualization


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arthonia dendritella Nyl.

### Remarks
null


text:
import pathlib
from typing import Any

import pytest
from yarl import URL

from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher

@pytest.fixture
def router():
    return UrlDispatcher()

def test_get(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.get("/", handler)])
    assert len(router.routes()) == 2  # GET and HEAD

    route = list(router.routes())[1]
    assert route.handler is handler
    assert route.method == "GET"
    assert str(route.url_for()) == "/"

    route2 = list(router.routes())[0]
    assert route2.handler is handler
    assert route2.method == "HEAD"

def test_head(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.head("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "HEAD"
    assert str(route.url_for()) == "/"

def test_options(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.options("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "OPTIONS"
    assert str(route.url_for()) == "/"

def test_post(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.post("/", handler)])

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "POST"
    assert str(route.url_for()) == "/"

def test_put(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.put("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "PUT"
    assert str(route.url_for()) == "/"

def test_patch(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.patch("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "PATCH"
    assert str(route.url_for()) == "/"

def test_delete(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.delete("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "DELETE"
    assert str(route.url_for()) == "/"

def test_route(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.route("OTHER", "/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "OTHER"
    assert str(route.url_for()) == "/"

def test_static(router: Any) -> None:
    folder = pathlib.Path(__file__).parent
    router.add_routes([web.static("/prefix", folder)])
    assert len(router.resources()) == 1  # 2 routes: for HEAD and GET

    resource = list(router.resources())[0]
    info = resource.get_info()
    assert info["prefix"] == "/prefix"
    assert info["directory"] == folder
    url = resource.url_for(filename="aiohttp.png")
    assert url == URL("/prefix/aiohttp.png")

def test_head_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.head("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "HEAD"
    assert str(route.url_for()) == "/path"

def test_get_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.get("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 2

    route1 = list(router.routes())[0]
    assert route1.method == "HEAD"
    assert str(route1.url_for()) == "/path"

    route2 = list(router.routes())[1]
    assert route2.method == "GET"
    assert str(route2.url_for()) == "/path"

def test_post_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.post("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "POST"
    assert str(route.url_for()) == "/path"

def test_put_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.put("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "PUT"
    assert str(route.url_for()) == "/path"

def test_patch_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.patch("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "PATCH"
    assert str(route.url_for()) == "/path"

def test_delete_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.delete("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "DELETE"
    assert str(route.url_for()) == "/path"

def test_options_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.options("/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "OPTIONS"
    assert str(route.url_for()) == "/path"

def test_route_deco(router: Any) -> None:
    routes = web.RouteTableDef()

    @routes.route("OTHER", "/path")
    async def handler(request):
        pass

    router.add_routes(routes)

    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.method == "OTHER"
    assert str(route.url_for()) == "/path"

def test_routedef_sequence_protocol() -> None:
    routes = web.RouteTableDef()

    @routes.delete("/path")
    async def handler(request):
        pass

    assert len(routes) == 1

    info = routes[0]
    assert isinstance(info, web.RouteDef)
    assert info in routes
    assert list(routes)[0] is info

def test_repr_route_def() -> None:
    routes = web.RouteTableDef()

    @routes.get("/path")
    async def handler(request):
        pass

    rd = routes[0]
    assert repr(rd) == "<RouteDef GET /path -> 'handler'>"

def test_repr_route_def_with_extra_info() -> None:
    routes = web.RouteTableDef()

    @routes.get("/path", extra="info")
    async def handler(request):
        pass

    rd = routes[0]
    assert repr(rd) == "<RouteDef GET /path -> 'handler', extra='info'>"

def test_repr_static_def() -> None:
    routes = web.RouteTableDef()

    routes.static("/prefix", "/path", name="name")

    rd = routes[0]
    assert repr(rd) == "<StaticDef /prefix -> /path, name='name'>"

def test_repr_route_table_def() -> None:
    routes = web.RouteTableDef()

    @routes.get("/path")
    async def handler(request):
        pass

    assert repr(routes) == "<RouteTableDef count=1>"


text:
<?xml version="1.0" ?><para version="5.0" xml:lang="zh" xmlns="http://docbook.org/ns/docbook">

Description of policy configuration options

    <col width="50%"/>
    <col width="50%"/>

        Configuration option = Default value
        描述

        [DEFAULT]

        <option>policy_default_rule</option> = <replaceable>默认值</replaceable>
        (StrOpt) Default rule. Enforced when a requested rule is not found.

        <option>policy_dirs</option> = <replaceable>['policy.d']</replaceable>
        (MultiStrOpt) Directories where policy configuration files are stored. They can be relative to any directory in the search path defined by the config_dir option, or absolute paths. The file defined by policy_file must exist for these directories to be searched.

        <option>policy_file</option> = <replaceable>policy.json</replaceable>
        (StrOpt) The JSON file that defines policies.

</para>


text:
package org.apache.lucene.queryParser.ext;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.TestQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

/**
 * Testcase for the class {@link ExtendableQueryParser}
 */
public class TestExtendableQueryParser extends TestQueryParser {
  private static char[] DELIMITERS = new char[] {
      Extensions.DEFAULT_EXTENSION_FIELD_DELIMITER, '-', '|' };

  public TestExtendableQueryParser(String name) {
    super(name);
  }

  @Override
  public QueryParser getParser(Analyzer a) throws Exception {
    return getParser(a, null);
  }

  public QueryParser getParser(Analyzer a, Extensions extensions)
      throws Exception {
    if (a == null)
      a = new SimpleAnalyzer(TEST_VERSION_CURRENT);
    QueryParser qp = extensions == null ? new ExtendableQueryParser(
        TEST_VERSION_CURRENT, "field", a) : new ExtendableQueryParser(
        TEST_VERSION_CURRENT, "field", a, extensions);
    qp.setDefaultOperator(QueryParser.OR_OPERATOR);
    return qp;
  }

  public void testUnescapedExtDelimiter() throws Exception {
    Extensions ext = newExtensions(':');
    ext.add("testExt", new ExtensionStub());
    ExtendableQueryParser parser = (ExtendableQueryParser) getParser(null, ext);
    try {
      parser.parse("aField:testExt:\"foo \\& bar\"");
      fail("extension field delimiter is not escaped");
    } catch (ParseException e) {
    }
  }

  public void testExtFieldUnqoted() throws Exception {
    for (int i = 0; i < DELIMITERS.length; i++) {
      Extensions ext = newExtensions(DELIMITERS[i]);
      ext.add("testExt", new ExtensionStub());
      ExtendableQueryParser parser = (ExtendableQueryParser) getParser(null,
          ext);
      String field = ext.buildExtensionField("testExt", "aField");
      Query query = parser.parse(String.format("%s:foo bar", field));
      assertTrue("expected instance of BooleanQuery but was "
          + query.getClass(), query instanceof BooleanQuery);
      BooleanQuery bquery = (BooleanQuery) query;
      BooleanClause[] clauses = bquery.getClauses();
      assertEquals(2, clauses.length);
      BooleanClause booleanClause = clauses[0];
      query = booleanClause.getQuery();
      assertTrue("expected instance of TermQuery but was " + query.getClass(),
          query instanceof TermQuery);
      TermQuery tquery = (TermQuery) query;
      assertEquals("aField", tquery.getTerm()
          .field());
      assertEquals("foo", tquery.getTerm().text());

      booleanClause = clauses[1];
      query = booleanClause.getQuery();
      assertTrue("expected instance of TermQuery but was " + query.getClass(),
          query instanceof TermQuery);
      tquery = (TermQuery) query;
      assertEquals("field", tquery.getTerm().field());
      assertEquals("bar", tquery.getTerm().text());
    }
  }

  public void testExtDefaultField() throws Exception {
    for (int i = 0; i < DELIMITERS.length; i++) {
      Extensions ext = newExtensions(DELIMITERS[i]);
      ext.add("testExt", new ExtensionStub());
      ExtendableQueryParser parser = (ExtendableQueryParser) getParser(null,
          ext);
      String field = ext.buildExtensionField("testExt");
      Query parse = parser.parse(String.format("%s:\"foo \\& bar\"", field));
      assertTrue("expected instance of TermQuery but was " + parse.getClass(),
          parse instanceof TermQuery);
      TermQuery tquery = (TermQuery) parse;
      assertEquals("field", tquery.getTerm().field());
      assertEquals("foo & bar", tquery.getTerm().text());
    }
  }

  public Extensions newExtensions(char delimiter) {
    return new Extensions(delimiter);
  }

  public void testExtField() throws Exception {
    for (int i = 0; i < DELIMITERS.length; i++) {
      Extensions ext = newExtensions(DELIMITERS[i]);
      ext.add("testExt", new ExtensionStub());
      ExtendableQueryParser parser = (ExtendableQueryParser) getParser(null,
          ext);
      String field = ext.buildExtensionField("testExt", "afield");
      Query parse = parser.parse(String.format("%s:\"foo \\& bar\"", field));
      assertTrue("expected instance of TermQuery but was " + parse.getClass(),
          parse instanceof TermQuery);
      TermQuery tquery = (TermQuery) parse;
      assertEquals("afield", tquery.getTerm().field());
      assertEquals("foo & bar", tquery.getTerm().text());
    }
  }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.resources.samples;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.Disk;
import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage;
import com.azure.resourcemanager.compute.models.VirtualMachine;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.network.models.Network;
import com.azure.resourcemanager.network.models.Subnet;
import com.azure.resourcemanager.resources.fluentcore.model.Creatable;
import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources;
import com.azure.resourcemanager.resources.models.LockLevel;
import com.azure.resourcemanager.resources.models.ManagementLock;
import com.azure.resourcemanager.resources.models.ResourceGroup;
import com.azure.resourcemanager.samples.Utils;
import com.azure.resourcemanager.storage.models.StorageAccount;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

/**
 * This sample shows examples of management locks usage on various resources.
 *  - Create a number of various resources to apply locks to
 *  - Apply various locks to the resources
 *  - Retrieve and show lock information
 *  - Remove the locks and clean up
 */
public final class ManageLocks {
    /**
     * Main function which runs the actual sample.
     * @param azureResourceManager instance of the azure client
     * @return true if sample runs successfully
     */
    public static boolean runSample(AzureResourceManager azureResourceManager) {

        final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 15);
        final String vmName = Utils.randomResourceName(azureResourceManager, "vm", 15);
        final String storageName = Utils.randomResourceName(azureResourceManager, "st", 15);
        final String diskName = Utils.randomResourceName(azureResourceManager, "dsk", 15);
        final String netName = Utils.randomResourceName(azureResourceManager, "net", 15);
        final Region region = Region.US_WEST;

        ResourceGroup resourceGroup;
        ManagementLock lockGroup = null,
            lockVM = null,
            lockStorage = null,
            lockDiskRO = null,
            lockDiskDel = null,
            lockSubnet = null;

        try {
            //=============================================================
            // Create a shared resource group for all the resources so they can all be deleted together
            //
            resourceGroup = azureResourceManager.resourceGroups().define(rgName)
                .withRegion(region)
                .create();
            System.out.println("Created a new resource group - " + resourceGroup.id());

            //============================================================
            // Create various resources for demonstrating locks
            //

            // Define a network to apply a lock to
            Creatable<Network> netDefinition = azureResourceManager.networks().define(netName)
                .withRegion(region)
                .withExistingResourceGroup(resourceGroup)
                .withAddressSpace("10.0.0.0/28");

            // Define a managed disk for testing locks on that
            Creatable<Disk> diskDefinition = azureResourceManager.disks().define(diskName)
                .withRegion(region)
                .withExistingResourceGroup(resourceGroup)
                .withData()
                .withSizeInGB(100);

            // Define a VM to apply a lock to
            Creatable<VirtualMachine> vmDefinition = azureResourceManager.virtualMachines().define(vmName)
                .withRegion(region)
                .withExistingResourceGroup(resourceGroup)
                .withNewPrimaryNetwork(netDefinition)
                .withPrimaryPrivateIPAddressDynamic()
                .withoutPrimaryPublicIPAddress()
                .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                .withRootUsername("tester")
                .withSsh(Utils.sshPublicKey())
                .withNewDataDisk(diskDefinition, 1, CachingTypes.NONE)
                .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"));

            // Define a storage account to apply a lock to
            Creatable<StorageAccount> storageDefinition = azureResourceManager.storageAccounts().define(storageName)
                .withRegion(region)
                .withExistingResourceGroup(resourceGroup);

            // Create resources in parallel to save time
            System.out.println("Creating the needed resources...");
            Flux.merge(
                storageDefinition.createAsync().subscribeOn(Schedulers.parallel()),
                vmDefinition.createAsync().subscribeOn(Schedulers.parallel()))
                .blockLast();
            System.out.println("Resources created.");

            VirtualMachine vm = (VirtualMachine) vmDefinition;
            StorageAccount storage = (StorageAccount) storageDefinition;
            Disk disk = (Disk) diskDefinition;
            Network network = vm.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork();
            Subnet subnet = network.subnets().values().iterator().next();

            //============================================================
            // Create various locks for the created resources
            //

            // Locks can be created serially, and multiple can be applied to the same resource:
            System.out.println("Creating locks sequentially...");

            // Apply a ReadOnly lock to the disk
            lockDiskRO = azureResourceManager.managementLocks().define("diskLockRO")
                .withLockedResource(disk)
                .withLevel(LockLevel.READ_ONLY)
                .create();

            // Apply a lock preventing the disk from being deleted
            lockDiskDel = azureResourceManager.managementLocks().define("diskLockDel")
                .withLockedResource(disk)
                .withLevel(LockLevel.CAN_NOT_DELETE)
                .create();

            // Locks can also be created in parallel, for better overall performance:
            System.out.println("Creating locks in parallel...");

            // Define a subnet lock
            Creatable<ManagementLock> lockSubnetDef = azureResourceManager.managementLocks().define("subnetLock")
                .withLockedResource(subnet.innerModel().id())
                .withLevel(LockLevel.READ_ONLY);

            // Define a VM lock
            Creatable<ManagementLock> lockVMDef = azureResourceManager.managementLocks().define("vmlock")
                .withLockedResource(vm)
                .withLevel(LockLevel.READ_ONLY)
                .withNotes("vm readonly lock");

            // Define a resource group lock
            Creatable<ManagementLock> lockGroupDef = azureResourceManager.managementLocks().define("rglock")
                .withLockedResource(resourceGroup.id())
                .withLevel(LockLevel.CAN_NOT_DELETE);

            // Define a storage lock
            Creatable<ManagementLock> lockStorageDef = azureResourceManager.managementLocks().define("stLock")
                .withLockedResource(storage)
                .withLevel(LockLevel.CAN_NOT_DELETE);

            @SuppressWarnings("unchecked")
            CreatedResources<ManagementLock> created = azureResourceManager.managementLocks().create(
                lockVMDef,
                lockGroupDef,
                lockStorageDef,
                lockSubnetDef);

            lockVM = created.get(lockVMDef.key());
            lockStorage = created.get(lockStorageDef.key());
            lockGroup = created.get(lockGroupDef.key());
            lockSubnet = created.get(lockSubnetDef.key());

            System.out.println("Locks created.");

            //============================================================
            // Retrieve and show lock information
            //

            // Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources)
            int lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(vm.id()));
            System.out.println("Number of locks applied to the virtual machine: " + lockCount);
            lockCount = Utils.getSize(azureResourceManager.managementLocks().listByResourceGroup(resourceGroup.name()));
            System.out.println("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount);
            lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(storage.id()));
            System.out.println("Number of locks applied to the storage account: " + lockCount);
            lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(disk.id()));
            System.out.println("Number of locks applied to the managed disk: " + lockCount);
            lockCount = Utils.getSize(azureResourceManager.managementLocks().listForResource(network.id()));
            System.out.println("Number of locks applied to the network (including its subnets): " + lockCount);

            // Locks can be retrieved using their ID
            lockVM = azureResourceManager.managementLocks().getById(lockVM.id());
            lockGroup = azureResourceManager.managementLocks().getByResourceGroup(resourceGroup.name(), "rglock");
            lockStorage = azureResourceManager.managementLocks().getById(lockStorage.id());
            lockDiskRO = azureResourceManager.managementLocks().getById(lockDiskRO.id());
            lockDiskDel = azureResourceManager.managementLocks().getById(lockDiskDel.id());
            lockSubnet = azureResourceManager.managementLocks().getById(lockSubnet.id());

            // Show the locks
            Utils.print(lockGroup);
            Utils.print(lockVM);
            Utils.print(lockDiskDel);
            Utils.print(lockDiskRO);
            Utils.print(lockStorage);
            Utils.print(lockSubnet);

            // List all locks within a subscription
            PagedIterable<ManagementLock> locksSubscription = azureResourceManager.managementLocks().list();
            System.out.println("Total number of locks within this subscription: " + Utils.getSize(locksSubscription));
            return true;
        } catch (Exception f) {
            System.out.println(f.getMessage());
            f.printStackTrace();

        } finally {

            //============================================================
            // Delete locks and clean up
            //

            try {
                // Clean up (remember to unlock resources before deleting the resource group)
                azureResourceManager.managementLocks().deleteByIds(
                    lockGroup.id(),
                    lockVM.id(),
                    lockDiskRO.id(),
                    lockDiskDel.id(),
                    lockStorage.id(),
                    lockSubnet.id());
                System.out.println("Deleting Resource Group: " + rgName);
                azureResourceManager.resourceGroups().beginDeleteByName(rgName);
            } catch (NullPointerException npe) {
                System.out.println("Did not create any resources in Azure. No clean up is necessary");
            } catch (Exception g) {
                g.printStackTrace();
            }
        }
        return false;
    }

    /**
     * Main entry point.
     *
     * @param args the parameters
     */
    public static void main(String[] args) {
        try {
            //=================================================================
            // Authenticate

            final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
            final TokenCredential credential = new DefaultAzureCredentialBuilder()
                .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                .build();

            AzureResourceManager azureResourceManager = AzureResourceManager
                .configure()
                .withLogLevel(HttpLogDetailLevel.BASIC)
                .authenticate(credential, profile)
                .withDefaultSubscription();

            runSample(azureResourceManager);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    private ManageLocks() {
    }
}


text:
package com.github.edgar615.gateway.plugin.appkey;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;

import com.github.edgar615.gateway.core.definition.ApiDefinition;
import com.github.edgar615.gateway.core.definition.ApiPlugin;
import com.github.edgar615.gateway.core.definition.SimpleHttpEndpoint;
import com.github.edgar615.gateway.core.dispatch.ApiContext;
import com.github.edgar615.gateway.core.dispatch.Filter;
import com.github.edgar615.gateway.core.utils.Filters;
import com.github.edgar615.util.exception.DefaultErrorCode;
import com.github.edgar615.util.exception.SystemException;
import com.github.edgar615.util.vertx.task.Task;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by edgar on 16-10-28.
 */
@RunWith(VertxUnitRunner.class)
public class AppKeyRestrictionFilterTest {

    private final List<Filter> filters = new ArrayList<>();

    Filter filter;

    private ApiContext apiContext;

    private String groupKey = "roles";

    @Before
    public void setUp() {
        Multimap<String, String> params = ArrayListMultimap.create();
        params.put("q3", "v3");
        Multimap<String, String> headers = ArrayListMultimap.create();
        headers.put("h3", "v3");
        headers.put("h3", "v3.2");

        apiContext =
                ApiContext.create(HttpMethod.GET, "/devices", headers, params, null);
        SimpleHttpEndpoint httpEndpoint =
                SimpleHttpEndpoint.http("add_device", HttpMethod.GET, "devices/",
                                        80, "localhost");

        groupKey = UUID.randomUUID().toString();
        ApiDefinition definition = ApiDefinition
                .create("get_device", HttpMethod.GET, "devices/", Lists.newArrayList(httpEndpoint));
        apiContext.setApiDefinition(definition);
        apiContext.addVariable("client_appKey", "testGroup");

        JsonObject config = new JsonObject().put("blacklist", new JsonArray().add("guest"))
                .put("whitelist", new JsonArray().add("group1"));

        filter = Filter.create(AppKeyRestrictionFilter.class.getSimpleName(), Vertx.vertx(),
                               new JsonObject().put("appKey.restriction", config));

        filters.clear();
        filters.add(filter);
    }

    @Test
    public void testNoAppKeyShouldSuccess(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("testGroup");
        apiContext.variables().remove("client_appKey");
        apiContext.apiDefinition().addPlugin(plugin);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    async.complete();
                }).onFailure(t -> {
            testContext.fail();
        });
    }

    @Test
    public void testGlobalBlackGroupShouldForbidden(TestContext testContext) {
//    AppKeyRestriction plugin =
//            (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
//    plugin.addBlacklist("testGroup");
//    apiContext.apiDefinition().addPlugin(plugin);
        apiContext.addVariable("client_appKey", "guest");
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    testContext.fail();
                }).onFailure(t -> {
            SystemException ex = (SystemException) t;
            testContext.assertEquals(DefaultErrorCode.PERMISSION_DENIED, ex.getErrorCode());
            async.complete();
        });
    }

    @Test
    public void testGlobalWhiteShouldAlwaysAllow(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("group1");
        apiContext.addVariable("client_appKey", "group1");
        apiContext.apiDefinition().addPlugin(plugin);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    async.complete();
                }).onFailure(t -> {
            testContext.fail();
        });
    }

    @Test
    public void testBlackGroupShouldForbidden(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("testGroup");
        apiContext.apiDefinition().addPlugin(plugin);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    testContext.fail();
                }).onFailure(t -> {
            SystemException ex = (SystemException) t;
            testContext.assertEquals(DefaultErrorCode.PERMISSION_DENIED, ex.getErrorCode());
            async.complete();
        });
    }

    @Test
    public void testWildcardBlackShouldForbidden(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("*");
        apiContext.apiDefinition().addPlugin(plugin);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    testContext.fail();
                }).onFailure(t -> {
            SystemException ex = (SystemException) t;
            testContext.assertEquals(DefaultErrorCode.PERMISSION_DENIED, ex.getErrorCode());
            async.complete();
        });
    }

    @Test
    public void testWhiteShouldAlwaysAllow(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("testGroup");
        plugin.addWhitelist("testGroup");
        apiContext.apiDefinition().addPlugin(plugin);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    async.complete();
                }).onFailure(t -> {
            testContext.fail();
        });
    }

    @Test
    public void testWildcardWhiteShouldAlwaysAllow(TestContext testContext) {
        AppKeyRestriction plugin =
                (AppKeyRestriction) ApiPlugin.create(AppKeyRestriction.class.getSimpleName());
        plugin.addBlacklist("testGroup");
        plugin.addWhitelist("*");
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filters.doFilter(task, filters)
                .andThen(context -> {
                    async.complete();
                }).onFailure(t -> {
            testContext.fail();
        });
    }

}