text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RgsParser
{
    [DebuggerDisplay("({Token})")]
    class ParseTreeTokenNode : IParseTreeNode
    {
        private static readonly IParseTreeNode[] EmptyChildren = { };

        public int ChildCount
        {
            get { return 0; }
        }

        public IReadOnlyList<IParseTreeNode> Children
        {
            get { return EmptyChildren; }
        }

        public bool IsTerminal
        {
            get { return true; }
        }

        public Token Token { get; }

        public ParseTreeTokenNode(Token token)
        {
            Debug.Assert(token != null);
            Token = token;
        }

        public void AppendTree(StringBuilder builder)
        {
            builder.Append('"');
            builder.Append(Token.Value);
            builder.Append('"');
        }
    }
}


text:
"""Base class of an axis partition for a Modin Dataframe."""

from abc import ABC, abstractmethod
from typing import Any, Callable, Iterable, Optional, Tuple, Union

class BaseDataframeAxisPartition(ABC):  # pragma: no cover
    """
    An abstract class that represents the parent class for any axis partition class.

    This class is intended to simplify the way that operations are performed.
    """

    @property
    @abstractmethod
    def list_of_blocks(self) -> list:
        """Get the list of physical partition objects that compose this partition."""
        pass

    def apply(
        self,
        func: Callable,
        *args: Iterable,
        num_splits: Optional[int] = None,
        other_axis_partition: Optional["BaseDataframeAxisPartition"] = None,
        maintain_partitioning: bool = True,
        lengths: Optional[Iterable] = None,
        manual_partition: bool = False,
        **kwargs: dict,
    ) -> Any:
        """
        Apply a function to this axis partition along full axis.

        Parameters
        ----------
        func : callable
            The function to apply. This will be preprocessed according to
            the corresponding `BaseDataframePartition` objects.
        *args : iterable
            Positional arguments to pass to `func`.
        num_splits : int, default: None
            The number of times to split the result object.
        other_axis_partition : BaseDataframeAxisPartition, default: None
            Another `BaseDataframeAxisPartition` object to be applied
            to func. This is for operations that are between two data sets.
        maintain_partitioning : bool, default: True
            Whether to keep the partitioning in the same
            orientation as it was previously or not. This is important because we may be
            operating on an individual axis partition and not touching the rest.
            In this case, we have to return the partitioning to its previous
            orientation (the lengths will remain the same). This is ignored between
            two axis partitions.
        lengths : iterable, default: None
            The list of lengths to shuffle the partition into.
        manual_partition : bool, default: False
            If True, partition the result with `lengths`.
        **kwargs : dict
            Additional keywords arguments to be passed in `func`.

        Returns
        -------
        list
            A list of `BaseDataframePartition` objects.

        Notes
        -----
        The procedures that invoke this method assume full axis
        knowledge. Implement this method accordingly.

        You must return a list of `BaseDataframePartition` objects from this method.
        """
        pass

    # Child classes must have these in order to correctly subclass.
    instance_type = None
    partition_type = None

    def _wrap_partitions(self, partitions: list) -> list:
        """
        Wrap remote partition objects with `BaseDataframePartition` class.

        Parameters
        ----------
        partitions : list
            List of remotes partition objects to be wrapped with `BaseDataframePartition` class.

        Returns
        -------
        list
            List of wrapped remote partition objects.
        """
        assert self.partition_type is not None
        assert self.instance_type is not None  # type: ignore

        return [self.partition_type(obj) for obj in partitions]

    def force_materialization(
        self, get_ip: bool = False
    ) -> "BaseDataframeAxisPartition":
        """
        Materialize axis partitions into a single partition.

        Parameters
        ----------
        get_ip : bool, default: False
            Whether to get node ip address to a single partition or not.

        Returns
        -------
        BaseDataframeAxisPartition
            An axis partition containing only a single materialized partition.
        """
        materialized = self.apply(
            lambda x: x, num_splits=1, maintain_partitioning=False
        )
        return type(self)(materialized, get_ip=get_ip)  # type: ignore[call-arg]

    def unwrap(
        self, squeeze: bool = False, get_ip: bool = False
    ) -> Union[list, Tuple[list, list]]:
        """
        Unwrap partitions from this axis partition.

        Parameters
        ----------
        squeeze : bool, default: False
            Flag used to unwrap only one partition.
        get_ip : bool, default: False
            Whether to get node ip address to each partition or not.

        Returns
        -------
        list
            List of partitions from this axis partition.

        Notes
        -----
        If `get_ip=True`, a tuple of lists of Ray.ObjectRef/Dask.Future to node ip addresses and
        unwrapped partitions, respectively, is returned if Ray/Dask is used as an engine
        (i.e. [(Ray.ObjectRef/Dask.Future, Ray.ObjectRef/Dask.Future), ...]).
        """
        if squeeze and len(self.list_of_blocks) == 1:
            if get_ip:
                # TODO(https://github.com/modin-project/modin/issues/5176): Stop ignoring the list_of_ips
                # check once we know that we're not calling list_of_ips on python axis partitions
                return self.list_of_ips[0], self.list_of_blocks[0]  # type: ignore[attr-defined]
            else:
                return self.list_of_blocks[0]
        else:
            if get_ip:
                return list(zip(self.list_of_ips, self.list_of_blocks))  # type: ignore[attr-defined]
            else:
                return self.list_of_blocks

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import assert from 'assert';
import { shallow } from 'enzyme';
import { SelectField } from './SelectField';

describe('<SelectField />', () => {
    const defaultProps = {
        source: 'foo',
        choices: [
            { id: 0, name: 'hello' },
            { id: 1, name: 'world' },
        ],
        translate: x => x,
    };

    it('should return null when the record is not set', () => assert.equal(
        shallow(<SelectField {...defaultProps} />).html(),
        null,
    ));

    it('should return null when the record has no value for the source', () => assert.equal(
        shallow(<SelectField {...defaultProps} record={{}} />).html(),
        null,
    ));

    it('should return null when the record has a value for the source not in the choices', () => assert.equal(
        shallow(<SelectField {...defaultProps} record={{ foo: 2 }} />).html(),
        null,
    ));

    it('should render the choice', () => {
        const wrapper = shallow(<SelectField {...defaultProps} record={{ foo: 0 }} />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });

    it('should use custom styles passed as an elStyle prop', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 1 }}
            elStyle={{ margin: 1 }}
        />);
        const chipElement = wrapper.find('span');
        assert.deepEqual(chipElement.prop('style'), { margin: 1 });
    });

    it('should handle deep fields', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: { bar: 0 } }}
            source="foo.bar"
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });

    it('should use optionValue as value identifier', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            optionValue="foobar"
            choices={[
                { foobar: 0, name: 'hello' },
            ]}
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });

    it('should use optionText with a string value as text identifier', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            optionText="foobar"
            choices={[
                { id: 0, foobar: 'hello' },
            ]}
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });

    it('should use optionText with a function value as text identifier', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            optionText={choice => choice.foobar}
            choices={[
                { id: 0, foobar: 'hello' },
            ]}
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });

    it('should use optionText with an element value as text identifier', () => {
        const Foobar = ({ record }) => <span>{record.foobar}</span>;
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            optionText={<Foobar />}
            choices={[
                { id: 0, foobar: 'hello' },
            ]}
        />);
        const chipElement = wrapper.find('Foobar');
        assert.deepEqual(chipElement.prop('record'), { id: 0, foobar: 'hello' });
    });

    it('should translate the choice by default', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            translate={x => `**${x}**`}
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), '**hello**');
    });

    it('should not translate the choice if translateChoice is false', () => {
        const wrapper = shallow(<SelectField
            {...defaultProps}
            record={{ foo: 0 }}
            translate={x => `**${x}**`}
            translateChoice={false}
        />);
        const chipElement = wrapper.find('span');
        assert.equal(chipElement.children().text(), 'hello');
    });
});


text:
require "spec_helper"

require "fileutils"
require "json"
require "pathname"
require "stringio"
require "tmpdir"

RSpec.describe Todo::FileRepository do
  let(:output) { StringIO.new }
  let(:error_output) { StringIO.new }
  let(:archived_path) { Pathname.pwd.join("archived") }
  let(:index_path) { Pathname.pwd.join("index.json") }

  around do |example|
    Dir.mktmpdir do |dir|
      Dir.chdir(dir) do
        example.run
      end
    end
  end

  describe "#initialize" do
    context "when index file doesn't exist" do
      it "creates index file" do
        expect {
          Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
        }.to change { index_path.exist? }.from(false).to(true)

        index = JSON.parse(index_path.read, symbolize_names: true)
        expect(index).to include({
          todos: {},
          archived: {},
          metadata: {
            lastId: 0,
            missingIds: []
          }
        })
      end
    end

    context "when index file exists" do
      let(:index_json) do
        JSON.pretty_generate({
          todos: {
            "": [1]
          },
          archived: {},
          metadata: {
            lastId: 1,
            missingIds: []
          }
        })
      end

      before do
        index_path.open("wb") { |file| file.puts(index_json) }
      end

      it "doesn't overwrite" do
        Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
        expect(index_path.read.chomp).to eq(index_json)
      end
    end

    context "when archived directory doesn't exist" do
      it "creates archived directory" do
        expect {
          Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
        }.to change { archived_path.exist? }.from(false).to(true)
        expect(archived_path).to be_directory
      end
    end

    context "when archived directory exists" do
      before do
        archived_path.mkdir
      end

      it "doesn't raise any errors" do
        expect {
          Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
        }.not_to raise_error
      end
    end
  end

  describe "#list" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    let(:todo_id) { 1 }
    let(:todo_path) { Pathname.pwd.join("#{todo_id}.md") }
    let(:subtodo_id) { 2 }
    let(:subtodo_path) { Pathname.pwd.join("#{subtodo_id}.md") }
    let(:not_found_todo_id) { 100 }

    shared_context "when a todo file exists" do
      before do
        FileUtils.touch(todo_path)
      end
    end

    shared_context "when a todo file is normal" do
      before do
        todo_path.open("wb+") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: undone
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when a todo file is empty" do
      before do
        todo_path.truncate(0)
      end
    end

    shared_context "when a todo file doesn't include front matter" do
      before do
        todo_path.open("wb+") { |file| file.puts("body") }
      end
    end

    shared_context "when a todo file includes broken front matter" do
      before do
        todo_path.open("wb+") do |file|
          file.puts(<<~TEXT)
            ---
            title: %
            state: undone
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when an index file is normal" do
      before do
        index_path.open("wb+") do |file|
          file.puts(JSON.pretty_generate({
            todos: {
              "": [todo_id]
            },
            archived: {},
            metadata: {
              lastId: todo_id,
              missingIds: []
            }
          }))
        end
      end
    end

    shared_context "when an index file is empty" do
      before do
        index_path.truncate(0)
      end
    end

    shared_context "when an index file includes ID which todo file doesn't exist" do
      before do
        index_path.open("wb+") do |file|
          file.puts(JSON.pretty_generate({
            todos: {
              "": [not_found_todo_id]
            },
            archived: {},
            metadata: {
              lastId: not_found_todo_id,
              missingIds: []
            }
          }))
        end
      end
    end

    shared_context "when a todo has a subtodo" do
      before do
        subtodo_path.open("wb+") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: undone
            ---

            body
          TEXT
        end

        index_path.open("wb+") do |file|
          file.puts(JSON.pretty_generate({
            todos: {
              "": [todo_id],
              "#{todo_id}": [subtodo_id]
            },
            archived: {},
            metadata: {
              lastId: subtodo_id,
              missingIds: []
            }
          }))
        end
      end
    end

    context "when todo doesn't exist" do
      it "returns empty array" do
        expect(repository.list).to be_empty
      end
    end

    context "when a todo exists but the todo file is empty" do
      include_context "when a todo file exists"
      include_context "when a todo file is empty"
      include_context "when an index file is normal"

      it "returns empty array" do
        expect(repository.list).to be_empty
      end

      it "puts message to error output" do
        repository.list
        expect(error_output.string).to eq("todo file is broken: #{todo_path}\n")
      end
    end

    context "when a todo exists but the todo file doesn't include front matter" do
      include_context "when a todo file exists"
      include_context "when a todo file doesn't include front matter"
      include_context "when an index file is normal"

      it "returns empty array" do
        expect(repository.list).to be_empty
      end

      it "puts message to error output" do
        repository.list
        expect(error_output.string).to eq("todo file is broken: #{todo_path}\n")
      end
    end

    context "when a todo exists but the todo file includes broken front matter" do
      include_context "when a todo file exists"
      include_context "when a todo file includes broken front matter"
      include_context "when an index file is normal"

      it "returns empty array" do
        expect(repository.list).to be_empty
      end

      it "puts message to error output" do
        repository.list
        expect(error_output.string).to eq("todo file is broken: #{todo_path}\n")
      end
    end

    context "when a todo exists but an index file is empty" do
      include_context "when a todo file exists"
      include_context "when a todo file is normal"
      include_context "when an index file is empty"

      it "returns empty array" do
        expect(repository.list).to be_empty
      end

      it "puts message to error output" do
        repository.list
        expect(error_output.string).to eq("index file is broken: #{index_path}\n")
      end
    end

    context "when a todo exists but an index file includes ID which todo file doesn't exist" do
      include_context "when a todo file exists"
      include_context "when a todo file is normal"
      include_context "when an index file includes ID which todo file doesn't exist"

      it "returns empty array" do
        expect(repository.list).to be_empty
      end

      it "puts message to error output" do
        repository.list
        not_found_todo_path = Pathname.pwd.join("#{not_found_todo_id}.md")
        expect(error_output.string).to eq("todo file is not found: #{not_found_todo_path}\n")
      end
    end

    context "when a todo file and an index file is normal" do
      include_context "when a todo file exists"
      include_context "when a todo file is normal"
      include_context "when an index file is normal"

      it "returns array containing a todo" do
        expect(repository.list).to contain_exactly(
          an_instance_of(Todo::Todo).and(having_attributes(
            id: todo_id
          ))
        )
      end
    end

    context "when a todo has a subtodo" do
      include_context "when a todo file exists"
      include_context "when a todo file is normal"
      include_context "when an index file is normal"
      include_context "when a todo has a subtodo"

      it "returns array containing a todo with a subtodo" do
        expect(repository.list).to contain_exactly(
          an_instance_of(Todo::Todo).and(having_attributes(
            id: todo_id,
            subtodos: a_collection_containing_exactly(
              an_instance_of(Todo::Todo).and(having_attributes(
                id: subtodo_id
              ))
            )
          ))
        )
      end
    end
  end

  describe "#create" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    shared_context "when title includes square brackets" do
      let(:title) { "[dummy]" }
    end

    shared_context "when title includes colons" do
      let(:title) { ":dummy" }
    end

    shared_context "when title doesn't any special characters" do
      let(:title) { "dummy" }
    end

    shared_context "when tags are empty" do
      let(:tags) { [] }
    end

    shared_context "when tags are present" do
      let(:tags) { ["dummy"] }
    end

    shared_context "when missing IDs are empty" do
      before do
        index_json = JSON.pretty_generate({
          todos: {},
          archived: {},
          metadata: {
            lastId: 0,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when missing IDs are present" do
      let(:missing_id) { 1 }

      before do
        index_json = JSON.pretty_generate({
          todos: {},
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: [missing_id]
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when position is nil" do
      let(:position) { nil }
    end

    shared_context "when position is -1" do
      let(:position) { -1 }

      before do
        index_json = JSON.pretty_generate({
          todos: {"": [1]},
          archived: {},
          metadata: {
            lastId: 1,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when position is 0" do
      let(:position) { 0 }

      before do
        index_json = JSON.pretty_generate({
          todos: {"": [1]},
          archived: {},
          metadata: {
            lastId: 1,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when position is larger than or equal to the length of todos" do
      let(:position) { 10 }

      before do
        index_json = JSON.pretty_generate({
          todos: {"": [1]},
          archived: {},
          metadata: {
            lastId: 1,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when parent_id is given" do
      let!(:parent_id) do
        parent = repository.create(title: "dummy")
        parent.id
      end
    end

    shared_context "when parent_id isn't given" do
      let(:parent_id) { nil }
    end

    context "when missing IDs are empty and position is 0" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is 0"
      include_context "when parent_id isn't given"

      it "updates an index file" do
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [2, 1]
          },
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: []
          }
        })
      end
    end

    context "when missing IDs are empty and position is -1" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is -1"
      include_context "when parent_id isn't given"

      it "updates an index file" do
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [1, 2]
          },
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: []
          }
        })
      end
    end

    context "when missing IDs are empty and position is larger than or equal to the length of todos" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is larger than or equal to the length of todos"
      include_context "when parent_id isn't given"

      it "updates an index file" do
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [1, 2]
          },
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: []
          }
        })
      end
    end

    context "when missing IDs are empty and parent_id isn't given" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is nil"
      include_context "when parent_id isn't given"

      it "creates a todo file" do
        todo_path = Pathname.pwd.join("1.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)

        expect(todo_path.read).to eq(<<~TEXT)
          ---
          title: dummy
          state: undone
          ---

        TEXT
      end

      it "updates an index file" do
        expect {
          repository.create(title: title, position: position, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [1]
          },
          archived: {},
          metadata: {
            lastId: 1,
            missingIds: []
          }
        })
      end
    end

    context "when title includes square brackets, missing IDs are empty and parent_id isn't given" do
      include_context "when title includes square brackets"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is nil"
      include_context "when parent_id isn't given"

      it "creates a todo file with the title double-quoted" do
        todo_path = Pathname.pwd.join("1.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)

        expect(todo_path.read).to eq(<<~TEXT)
          ---
          title: "[dummy]"
          state: undone
          ---

        TEXT
      end
    end

    context "when title includes square brackets, missing IDs are empty and parent_id isn't given" do
      include_context "when title includes colons"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is nil"
      include_context "when parent_id isn't given"

      it "creates a todo file with the title double-quoted" do
        todo_path = Pathname.pwd.join("1.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)

        expect(todo_path.read).to eq(<<~TEXT)
          ---
          title: ":dummy"
          state: undone
          ---

        TEXT
      end
    end

    context "when tags are present, missing IDs are empty and parent_id isn't given" do
      include_context "when title doesn't any special characters"
      include_context "when tags are present"
      include_context "when missing IDs are empty"
      include_context "when position is nil"
      include_context "when parent_id isn't given"

      it "creates a todo file with tags" do
        todo_path = Pathname.pwd.join("1.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)

        expect(todo_path.read).to eq(<<~TEXT)
          ---
          title: dummy
          state: undone
          tags: ["dummy"]
          ---

        TEXT
      end
    end

    context "when missing IDs are empty and parent_id is given" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are empty"
      include_context "when position is nil"
      include_context "when parent_id is given"

      it "creates a todo file" do
        todo_path = Pathname.pwd.join("2.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)

        expect(todo_path.read).to eq(<<~TEXT)
          ---
          title: dummy
          state: undone
          ---

        TEXT
      end

      it "updates an index file" do
        expect {
          repository.create(title: title, position: position, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [1],
            "1": [2]
          },
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: []
          }
        })
      end
    end

    context "when missing IDs are present and parent_id isn't given" do
      include_context "when title doesn't any special characters"
      include_context "when tags are empty"
      include_context "when missing IDs are present"
      include_context "when position is nil"
      include_context "when parent_id isn't given"

      it "creates a todo file with a missing ID" do
        todo_path = Pathname.pwd.join("#{missing_id}.md")
        expect {
          repository.create(title: title, tags: tags, position: position, parent_id: parent_id)
        }.to change { todo_path.exist? }.from(false).to(true)
      end

      it "removes a missing ID" do
        expect {
          repository.create(title: title, parent_id: parent_id)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.to({
          todos: {
            "": [missing_id]
          },
          archived: {},
          metadata: {
            lastId: 2,
            missingIds: []
          }
        })
      end
    end
  end

  describe "#delete" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    let!(:todo) { repository.create(title: "dummy") }
    let!(:subtodo) { repository.create(title: "dummy", parent_id: todo.id) }
    let!(:subsubtodo) { repository.create(title: "dummy", parent_id: subtodo.id) }

    context "when todo file with given ID doesn't exist" do
      let(:ids) { [100] }

      it "outputs message to error output" do
        repository.delete(ids: ids)

        todo_path = Pathname.pwd.join("#{ids.first}.md")
        expect(error_output.string).to eq("todo file is not found: #{todo_path}\n")
      end
    end

    context "when given ID is a parent todo's ID" do
      let(:ids) { [todo.id] }

      it "deletes all descendant todo files" do
        todo_path = Pathname.pwd.join("#{todo.id}.md")
        subtodo_path = Pathname.pwd.join("#{subtodo.id}.md")
        subsubtodo_path = Pathname.pwd.join("#{subsubtodo.id}.md")

        expect { repository.delete(ids: ids) }.to change { todo_path.exist? }.from(true).to(false)
          .and change { subtodo_path.exist? }.from(true).to(false)
          .and change { subsubtodo_path.exist? }.from(true).to(false)
      end

      it "updates index file" do
        before_index = {todos: {"": [todo.id], "#{todo.id}": [subtodo.id], "#{subtodo.id}": [subsubtodo.id]}, archived: {}, metadata: {lastId: subsubtodo.id, missingIds: []}}
        after_index = {todos: {"": []}, archived: {}, metadata: {lastId: subsubtodo.id, missingIds: [todo.id, subtodo.id, subsubtodo.id]}}

        expect {
          repository.delete(ids: ids)
        }.to change {
          JSON.parse(index_path.read, symbolize_names: true)
        }.from(before_index).to(after_index)
      end
    end

    context "when given IDs include a parent todo's ID and subtodo's ID" do
      let(:ids) { [todo.id, subtodo.id] }

      it "doesn't put any messages to error output" do
        repository.delete(ids: ids)
        expect(error_output.string).to be_empty
      end
    end
  end

  describe "#update" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    let!(:todo) { repository.create(title: "dummy") }
    let!(:subtodo) { repository.create(title: "dummy", parent_id: todo.id) }
    let!(:subsubtodo) { repository.create(title: "dummy", parent_id: subtodo.id) }

    context "when todo file with given ID doesn't exist" do
      let(:ids) { [100] }

      it "puts error message to error output" do
        repository.update(ids: ids, state: :undone)

        todo_path = Pathname.pwd.join("#{ids.first}.md")
        expect(error_output.string).to eq("todo file is not found: #{todo_path}\n")
      end
    end

    context "when given ID is a parent todo's ID" do
      let(:ids) { [todo.id] }

      it "updates all descendant todos" do
        todo_path = Pathname.pwd.join("#{todo.id}.md")
        subtodo_path = Pathname.pwd.join("#{subtodo.id}.md")
        subsubtodo_path = Pathname.pwd.join("#{subsubtodo.id}.md")

        expect { repository.update(ids: ids, state: :done) }.to change { todo_path.read.include?("state: done") }.to(true)
          .and change { subtodo_path.read.include?("state: done") }.to(true)
          .and change { subsubtodo_path.read.include?("state: done") }.to(true)
      end
    end

    context "when given IDs include a parent todo's ID and subtodo's ID" do
      let(:ids) { [todo.id, subtodo.id] }

      it "doesn't put any messages to error output" do
        repository.update(ids: ids, state: :done)
        expect(error_output.string).to be_empty
      end
    end
  end

  describe "#archive" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    let(:todo_id) { 1 }
    let(:todo_path) { Pathname.pwd.join("#{todo_id}.md") }
    let(:archived_todo_path) { archived_path.join("#{todo_id}.md") }
    let(:subtodo_id) { 2 }
    let(:subtodo_path) { Pathname.pwd.join("#{subtodo_id}.md") }
    let(:archived_subtodo_path) { archived_path.join("#{subtodo_id}.md") }
    let(:unknown_todo_id) { 100 }

    shared_context "when parent todo is undone" do
      before do
        todo_path.open("wb") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: undone
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when parent todo is done" do
      before do
        todo_path.open("wb") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: done
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when subtodo is undone" do
      before do
        subtodo_path.open("wb") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: undone
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when subtodo is done" do
      before do
        subtodo_path.open("wb") do |file|
          file.puts(<<~TEXT)
            ---
            title: dummy
            state: done
            ---

            body
          TEXT
        end
      end
    end

    shared_context "when index file is normal" do
      before do
        index_json = JSON.pretty_generate({
          todos: {
            "": [todo_id],
            "#{todo_id}": [subtodo_id]
          },
          archived: {},
          metadata: {
            lastId: subtodo_id,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    shared_context "when index file includes ID which todo file doesn't exist" do
      before do
        index_json = JSON.pretty_generate({
          todos: {
            "": [todo_id, unknown_todo_id],
            "#{todo_id}": [subtodo_id]
          },
          archived: {},
          metadata: {
            lastId: subtodo_id,
            missingIds: []
          }
        })
        index_path.open("wb") { |file| file.puts(index_json) }
      end
    end

    context "when both parent todo and subtodo is undone" do
      include_context "when parent todo is undone"
      include_context "when subtodo is undone"
      include_context "when index file is normal"

      it "doesn't move parent todo file and subtodo file" do
        expect { repository.archive }
          .to not_change { todo_path.exist? }
          .and not_change { subtodo_path.exist? }
      end

      it "doesn't update index file" do
        expect { repository.archive }.not_to change { JSON.parse(index_path.read, symbolize_names: true) }
      end
    end

    context "when parent todo is done but subtodo is undone" do
      include_context "when parent todo is done"
      include_context "when subtodo is undone"
      include_context "when index file is normal"

      it "moves both parent todo file and subtodo file into archived directory" do
        expect { repository.archive }
          .to change { todo_path.exist? }.to(false)
          .and change { archived_todo_path.exist? }.to(true)
          .and change { subtodo_path.exist? }.to(false)
          .and change { archived_subtodo_path.exist? }.to(true)
      end

      it "updates index file" do
        expect { repository.archive }.to change { JSON.parse(index_path.read, symbolize_names: true) }.to({
          todos: {},
          archived: {
            "": [todo_id],
            "#{todo_id}": [subtodo_id]
          },
          metadata: {
            lastId: subtodo_id,
            missingIds: []
          }
        })
      end
    end

    context "when parent todo is undone but subtodo is done" do
      include_context "when parent todo is undone"
      include_context "when subtodo is done"
      include_context "when index file is normal"

      it "moves only subtodo file into archived directory" do
        expect { repository.archive }
          .to not_change { todo_path.exist? }
          .and change { subtodo_path.exist? }.to(false)
          .and change { archived_subtodo_path.exist? }.to(true)
      end

      it "updates index file" do
        expect { repository.archive }.to change { JSON.parse(index_path.read, symbolize_names: true) }.to({
          todos: {
            "": [todo_id]
          },
          archived: {
            "#{todo_id}": [subtodo_id]
          },
          metadata: {
            lastId: subtodo_id,
            missingIds: []
          }
        })
      end
    end

    context "when both parent todo and subtodo is done" do
      include_context "when parent todo is done"
      include_context "when subtodo is done"
      include_context "when index file is normal"

      it "moves both parent todo file and subtodo file into archived directory" do
        expect { repository.archive }
          .to change { todo_path.exist? }.to(false)
          .and change { archived_todo_path.exist? }.to(true)
          .and change { subtodo_path.exist? }.to(false)
          .and change { archived_subtodo_path.exist? }.to(true)
      end

      it "updates index file" do
        expect { repository.archive }.to change { JSON.parse(index_path.read, symbolize_names: true) }.to({
          todos: {},
          archived: {
            "": [todo_id],
            "#{todo_id}": [subtodo_id]
          },
          metadata: {
            lastId: subtodo_id,
            missingIds: []
          }
        })
      end
    end

    context "when index file includes ID which todo file doesn't exist" do
      include_context "when parent todo is done"
      include_context "when subtodo is done"
      include_context "when index file includes ID which todo file doesn't exist"

      it "puts error message to error output" do
        repository.archive

        unknown_todo_path = Pathname.pwd.join("#{unknown_todo_id}.md")
        expect(error_output.string).to eq("todo file is not found: #{unknown_todo_path}\n")
      end
    end
  end

  describe "#move" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    before do
      index_path.open("wb") do |file|
        file.puts(JSON.pretty_generate({
          todos: {
            "": [1, 2, 3],
            "1": [4]
          },
          archived: {
            "": [5],
            "5": [6]
          },
          metadata: {
            lastId: 6,
            missingIds: []
          }
        }))
      end

      1.upto(6) do |id|
        todo_path = Pathname.pwd.join("#{id}.md")
        todo_path.open("wb") do |file|
          file.puts <<~TEXT
            ---
            title: dummy
            state: done
            ---

            body
          TEXT
        end
      end
    end

    [
      [[2, nil, -1], {todos: {"": [1, 3, 2], "1": [4]}}],
      [[2, nil, 1], {todos: {"": [2, 1, 3], "1": [4]}}],
      [[2, nil, 3], {todos: {"": [1, 3, 2], "1": [4]}}],
      [[2, nil, 4], {todos: {"": [1, 3, 2], "1": [4]}}],
      [[4, nil, 4], {todos: {"": [1, 2, 3, 4]}}],
      [[2, 1, 1], {todos: {"": [1, 3], "1": [2, 4]}}],
      [[2, 3, 1], {todos: {"": [1, 3], "1": [4], "3": [2]}}]
    ].each do |(id, parent_id, position), expected_index|
      context "when id: #{id}, parent_id: #{parent_id}, position: #{position}" do
        it "updates index file" do
          expect {
            repository.move(id: id, parent_id: parent_id, position: position)
          }.to change {
            JSON.parse(index_path.read, symbolize_names: true)
          }.to(a_hash_including(expected_index))
        end
      end
    end

    [
      [[100, nil, 1], "todo is not found: 100"],
      [[1, 100, 1], "parent is not found: 100"],
      [[1, 1, 1], "moving a todo under itself is forbidden"],
      [[5, nil, 1], "moving an archived todo is forbidden"],
      [[1, 6, 1], "moving a todo under an archived todo is forbidden"]
    ].each do |(id, parent_id, position), error_message|
      context "when id: #{id}, parent_id: #{parent_id}, position: #{position}" do
        it "puts error message to error output" do
          repository.move(id: id, parent_id: parent_id, position: position)
          expect(error_output.string).to eq(error_message + "\n")
        end
      end
    end
  end

  describe "#open" do
    let!(:repository) do
      Todo::FileRepository.new(root_path: Pathname.pwd, error_output: error_output)
    end

    context "when a todo with given ID exists" do
      let(:id) { 1 }
      let(:todo_path) { Pathname.pwd.join("#{id}.md") }

      before do
        FileUtils.touch(todo_path)
      end

      it "calls Kernel#.system with `open path/to/todo_file.md`" do
        expect(repository).to receive(:system).with("open #{todo_path}")
        repository.open(id: id)
      end
    end

    context "when a todo with given ID exists and is archived" do
      let(:id) { 1 }
      let(:todo_path) { archived_path.join("1.md") }

      before do
        FileUtils.touch(todo_path)
      end

      it "calls Kernel#.system with `open path/to/archived/todo_file.md`" do
        expect(repository).to receive(:system).with("open #{todo_path}")
        repository.open(id: id)
      end
    end

    context "when a todo with given ID doesn't exist" do
      let(:id) { 1 }

      it "puts error message to error output" do
        repository.open(id: id)
        expect(error_output.string).to eq("todo is not found: #{id}\n")
      end
    end
  end
end


text:
const HTTP_CODE = {
	OK: 200,
	BAD_REQUEST: 400
};

class ResponseHelper {
	/**
	 * @description
	 * Sends success response to the user
	 *
	 * @param {Object} res response object
	 * @param {Object} [data] content to return
	 */
	static success(res, data) {
		const result = data || {};
		result.status = 'ok';
		res.send(HTTP_CODE.OK, result);
	}

	/**
	 * @description
	 * Sends error response to the user
	 *
	 * @param {Object} res response object
	 * @param {Object} [data] content to return
	 * @param {Number} [code=400] error code
	 */
	static fail(res, data, code) {
		const result = data || {};
		result.status = 'error';
		result.code = code || HTTP_CODE.BAD_REQUEST;
		res.send(data.code, result);
	}

	/**
	 * @description
	 * Recoursively masks fields in object
	 *
	 * @param {Object} object
	 * @param {Array<String>} fields List of field names to mask
	 * @returns {Object}
	 */
	static maskFields(object, fields) {
		Object.keys(object).forEach(propertyName => {
			if (fields.indexOf(propertyName) !== -1)
				object[propertyName] = '******';
			else if (
				typeof object[propertyName] === 'object' &&
				!Array.isArray(object)
			) {
				object[propertyName] = ResponseHelper.maskFields(
					object[propertyName],
					fields
				);
			}
		});
		return object;
	}
}

module.exports = ResponseHelper;


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/html/HTMLInputElement10";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "input");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
    	catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*
    The maxLength attribute is the maximum number of text characters for text
    fields, when type has the value of Text or Password.

    Retrieve the maxLenght attribute of the 1st INPUT element and examine
    its value.

* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-54719353
*/
function HTMLInputElement10() {
   var success;
    if(checkInitialization(builder, "HTMLInputElement10") != null) return;
    var nodeList;
      var testNode;
      var vmaxlength;
      var doc;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "input");
      nodeList = doc.getElementsByTagName("input");
      assertSize("Asize",9,nodeList);
testNode = nodeList.item(0);
      vmaxlength = testNode.maxLength;

      assertEquals("maxlengthLink",5,vmaxlength);

}

function runTest() {
   HTMLInputElement10();
}


text:
import os
import sys
import codecs
import time

PY3 = sys.version_info >= (3,)
if PY3:
    basestring = str  # no basestring in python 3

from .defaultpaths import DEFAULT_DATA_DIR
from .log import LoggerFactory
from .yamlmgr import yamler
from .packer import packer

# Global logger for this part
logger = LoggerFactory.create_logger('configuration')

ZONE_KEYS_DIRECTORY_NAME = 'zone_keys'

class ConfigurationManager(object):
    # The parameter for the main cluster class is list here, and we will give back to it what we did read in the
    # local.yaml file (one set ones)
    cluster_parameters = {
        'display_name'                          : {'type': 'string', 'mapto': 'display_name'},
        'process_name'                          : {'type': 'string', 'mapto': 'process_name'},
        'port'                                  : {'type': 'int', 'mapto': 'port'},
        'data'                                  : {'type': 'path', 'mapto': 'data_dir'},
        'libexec'                               : {'type': 'path', 'mapto': 'libexec_dir'},
        'log'                                   : {'type': 'path', 'mapto': 'log_dir'},
        'lock'                                  : {'type': 'path', 'mapto': 'lock_path'},
        'socket'                                : {'type': 'path', 'mapto': 'socket_path'},
        'log_level'                             : {'type': 'string', 'mapto': 'log_level'},
        'bootstrap'                             : {'type': 'bool', 'mapto': 'bootstrap'},
        'seeds'                                 : {'type': 'list', 'mapto': 'seeds'},
        'groups'                                : {'type': 'list', 'mapto': 'groups'},
        'node-zone'                             : {'type': 'string', 'mapto': 'zone'},
        'proxy-node'                            : {'type': 'bool', 'mapto': 'is_proxy'},
        'service_discovery_topic_enabled'       : {'type': 'bool', 'mapto': 'service_discovery_topic_enabled'},
        'automatic_detection_topic_enabled'     : {'type': 'bool', 'mapto': 'automatic_detection_topic_enabled'},
        'monitoring_topic_enabled'              : {'type': 'bool', 'mapto': 'monitoring_topic_enabled'},
        'metrology_topic_enabled'               : {'type': 'bool', 'mapto': 'metrology_topic_enabled'},
        'configuration_automation_topic_enabled': {'type': 'bool', 'mapto': 'configuration_automation_topic_enabled'},
        'system_compliance_topic_enabled'       : {'type': 'bool', 'mapto': 'system_compliance_topic_enabled'},
    }

    def __init__(self):
        # Keep a list of the knowns cfg objects type we will encounter
        # NOTE: will be extend once with the modules types
        self.known_types = set(['check', 'service', 'compliance', 'generator', 'zone', 'tutorial'])

        # The cluster starts with defualt parameters, but of course configuration can set them too
        # so we will load them (in the local.yaml file) and give it back to the cluster when it will need it
        self.parameters_for_cluster_from_configuration = {}

        # Maybe we did found other variables in the main configuration file or another?
        self.additionnal_variables = {}

        # Cluster parameters
        self.data_dir = os.path.abspath(os.path.join(DEFAULT_DATA_DIR))  # '/var/lib/opsbro/'

        # For each pack, we keep the parameters.yml data
        self.pack_parameters = {}

    def get_data_dir(self):
        return self.data_dir

    def get_monitoringmgr(self):
        # Import at runtime, to avoid loop
        from .monitoring import monitoringmgr
        return monitoringmgr

    def get_handlermgr(self):
        from .handlermgr import handlermgr
        return handlermgr

    def get_compliancemgr(self):
        from .compliancemgr import compliancemgr
        return compliancemgr

    def get_zonemgr(self):
        from .zonemanager import zonemgr
        return zonemgr

    def get_tutorialmgr(self):
        from .tutorial import tutorialmgr
        return tutorialmgr

    def get_modulemanager(self):
        from .modulemanager import modulemanager
        return modulemanager

    def get_generatormgr(self):
        from .generatormgr import generatormgr
        return generatormgr

    def get_detecter(self):
        from .detectormgr import detecter
        return detecter

    def get_dashboarder(self):
        from .dashboardmanager import get_dashboarder
        return get_dashboarder()

    # the cluster is asking me which parameters are set in the local.yaml file
    def get_parameters_for_cluster_from_configuration(self):
        return self.parameters_for_cluster_from_configuration

    def load_main_cfg_dir(self, cfg_dir):
        self.main_cfg_directory = cfg_dir
        # also compute other directories from this
        self.zone_keys_directory = os.path.join(self.main_cfg_directory, ZONE_KEYS_DIRECTORY_NAME)
        self.load_cfg_dir(self.main_cfg_directory, load_focus='agent')

    def load_cfg_dir(self, cfg_dir, load_focus, pack_name='', pack_level=''):
        if not os.path.exists(cfg_dir):
            logger.error('ERROR: the configuration directory %s is missing' % cfg_dir)
            return
        for root, dirs, files in os.walk(cfg_dir):
            for name in files:
                fp = os.path.join(root, name)
                # Only yml are interesting
                if not name.endswith('.yml'):
                    continue
                logger.debug('Loader: looking for cfg file: %s' % fp)
                # Note: for parameters, if we don't trick the document by adding a first dummy entry
                # at the start of the document, the first key won't be able to have before line comments
                # because they will be put in the document one
                force_document_comment_to_first_entry = False
                if load_focus == 'parameter':
                    force_document_comment_to_first_entry = True
                obj = self.__get_object_from_cfg_file(fp, force_document_comment_to_first_entry=force_document_comment_to_first_entry)
                # agent: pid, log, graoups, etc
                # and zones
                if load_focus == 'agent':
                    self.load_agent_parameters(obj)
                elif load_focus == 'monitoring':
                    self.load_monitoring_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'generator':
                    self.load_generator_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'detector':
                    self.load_detector_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'dashboard':
                    self.load_dashboard_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'parameter':
                    self.load_pack_parameters(obj, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'compliance':
                    self.load_compliance_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                elif load_focus == 'tutorial':
                    self.load_tutorial_object(obj, fp, pack_name=pack_name, pack_level=pack_level)
                else:
                    raise Exception('Unknown load focus type! %s' % load_focus)

    def __get_object_from_cfg_file(self, fp, force_document_comment_to_first_entry=False):
        with codecs.open(fp, 'r', 'utf8') as f:
            buf = f.read()
            try:
                o = yamler.loads(buf, force_document_comment_to_first_entry=force_document_comment_to_first_entry)
                logger.debug("Configuration, opening file data", o, fp)
                return o
            except Exception as exp:
                logger.error('ERROR: the configuration file %s malformed: %s' % (fp, exp))
                sys.exit(2)

    # pid, log & zones
    def load_agent_parameters(self, o):
        if 'zone' in o:
            zone = o['zone']
            zonemgr = self.get_zonemgr()
            zonemgr.add_zone(zone)

        # grok all others data so we can use them in our checks
        cluster_parameters = self.__class__.cluster_parameters
        for (k, v) in o.items():
            # check, service, ... are already managed
            if k in self.known_types:
                continue

            # if k is not a internal parameters, use it in the cfg_data part
            if k not in cluster_parameters:
                logger.debug("Setting raw variable/value from file: %s=>%s" % (k, v))
                self.additionnal_variables[k] = v
            else:  # cannot be check and service here
                e = cluster_parameters[k]
                _type = e['type']
                mapto = e['mapto']
                if _type == 'int':
                    try:
                        int(v)
                    except ValueError:
                        logger.error('The parameter %s is not an int' % k)
                        return
                elif _type in ['path', 'string']:
                    if not isinstance(v, basestring):
                        logger.error('The parameter %s is not a string' % k)
                        return
                elif _type == 'bool':
                    if not isinstance(v, bool):
                        logger.error('The parameter %s is not a bool' % k)
                        return
                elif _type == 'list':
                    if not isinstance(v, list):
                        logger.error('The parameter %s is not a list' % k)
                        return
                else:
                    logger.error('Unknown parameter type %s' % k)
                    return
                # Save it, and in the cluster point of view (setattr for it)
                self.parameters_for_cluster_from_configuration[mapto] = v

    # Monitoring objects: check, service and handler
    def load_monitoring_object(self, o, fp, pack_name, pack_level):
        if 'check' in o:
            check = o['check']
            if not isinstance(check, dict):
                logger.error('ERROR: the check from the file %s is not a valid dict (%s found)' % (fp, type(check)))
                sys.exit(2)
            fname = fp
            mod_time = int(os.path.getmtime(fp))
            cname = os.path.splitext(fname)[0]
            monitoringmgr = self.get_monitoringmgr()
            monitoringmgr.import_check(check, 'file:%s' % fname, cname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

        if 'service' in o:
            service = o['service']
            if not isinstance(service, dict):
                logger.error('ERROR: the service from the file %s is not a valid dict (%s found)' % (fp, type(service)))
                sys.exit(2)

            mod_time = int(os.path.getmtime(fp))
            fname = fp
            sname = os.path.splitext(fname)[0]
            monitoringmgr = self.get_monitoringmgr()
            monitoringmgr.import_service(service, 'file:%s' % fname, sname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

    # Compliance object
    def load_compliance_object(self, o, fp, pack_name, pack_level):
        if 'compliance' in o:
            compliance = o['compliance']

            mod_time = int(os.path.getmtime(fp))
            fname = fp
            hname = os.path.splitext(os.path.basename(fname))[0]
            compliancemgr = self.get_compliancemgr()
            compliancemgr.import_compliance(compliance, fp, hname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

    # Compliance object
    def load_tutorial_object(self, o, fp, pack_name, pack_level):
        if 'tutorial' in o:
            tutorial = o['tutorial']
            mgr = self.get_tutorialmgr()
            mgr.import_tutorial(tutorial, fp, pack_name=pack_name, pack_level=pack_level)

    def load_generator_object(self, o, fp, pack_name, pack_level):
        if 'generator' in o:
            generator = o['generator']
            if not isinstance(generator, dict):
                logger.error('ERROR: the generator from the file %s is not a valid dict (%s found)' % (fp, type(generator)))
                sys.exit(2)

            mod_time = int(os.path.getmtime(fp))
            fname = fp
            gname = os.path.splitext(os.path.basename(fname))[0]
            generatormgr = self.get_generatormgr()
            generatormgr.import_generator(generator, fname, gname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

    def load_detector_object(self, o, fp, pack_name, pack_level):
        if 'detector' in o:
            detector = o['detector']
            if not isinstance(detector, dict):
                logger.error('ERROR: the detector from the file %s is not a valid dict (%s found)' % (fp, type(detector)))
                sys.exit(2)
            mod_time = int(os.path.getmtime(fp))
            fname = fp
            gname = os.path.splitext(fname)[0]
            detecter = self.get_detecter()
            detecter.import_detector(detector, 'file:%s' % fname, gname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

    def load_dashboard_object(self, o, fp, pack_name, pack_level):
        if 'dashboard' in o:
            dashboard = o['dashboard']
            if not isinstance(dashboard, dict):
                logger.error('ERROR: the dashboard from the file %s is not a valid dict (%s found)' % (fp, type(dashboard)))
                sys.exit(2)
            mod_time = int(os.path.getmtime(fp))
            fname = fp
            gname = os.path.splitext(fname)[0]
            dashboarder = self.get_dashboarder()
            dashboarder.import_dashboard(dashboard, fname, gname, mod_time=mod_time, pack_name=pack_name, pack_level=pack_level)

    def load_pack_parameters(self, o, pack_name, pack_level):
        # If not already create entry, we can do it
        if pack_name not in self.pack_parameters:
            self.pack_parameters[pack_name] = {'pack_level': pack_level, 'properties': {}}
        pack_entry = self.pack_parameters[pack_name]
        for (k, v) in o.items():
            pack_entry['properties'][k] = v

    def get_parameters_from_pack(self, pack_name):
        entry = self.pack_parameters.get(pack_name, None)
        if entry is None:
            return {}
        return entry['properties']

    def load_modules_from_packs(self):
        modulemanager = self.get_modulemanager()
        pack_directories = packer.give_pack_directories_to_load()

        for (pname, level, dir) in pack_directories:
            module_directory = os.path.join(dir, 'module')
            if os.path.exists(module_directory):
                modulemanager.add_module_directory_to_load(module_directory, pname, level)

        modulemanager.load_module_sources()

    def load_configuration_from_packs(self):
        pack_directories = packer.give_pack_directories_to_load()

        for (pname, level, dir) in pack_directories:
            # We load the sub directories, but we don't want to have a big mess of objects
            # so must respect for each type
            # dir, load_focus
            _types = [('monitoring', 'monitoring'),
                      ('generators', 'generator'), ('parameters', 'parameter'),
                      ('detectors', 'detector'),
                      ('compliance', 'compliance'), ('dashboards', 'dashboard'),
                      ('tutorials', 'tutorial'),
                      ]
            for sub_dir, load_focus in _types:
                full_sub_dir = os.path.join(dir, sub_dir)
                if os.path.exists(full_sub_dir):
                    self.load_cfg_dir(full_sub_dir, load_focus=load_focus, pack_name=pname, pack_level=level)

    def load_collectors_from_packs(self):
        # Load at running to avoid endless import loop
        from .collectormanager import collectormgr
        pack_directories = packer.give_pack_directories_to_load()

        for (pname, level, dir) in pack_directories:
            # Now load collectors, an important part for packs :)
            collector_dir = os.path.join(dir, 'collectors')
            if os.path.exists(collector_dir):
                collectormgr.load_directory(collector_dir, pack_name=pname, pack_level=level)

        # now collectors class are loaded, load instances from them
        collectormgr.load_all_collectors()

    def load_hostingdrivers_from_packs(self):
        # Load at running to avoid endless import loop
        from .hostingdrivermanager import get_hostingdrivermgr
        hostingctxmgr = get_hostingdrivermgr()
        pack_directories = packer.give_pack_directories_to_load()

        for (pname, level, dir) in pack_directories:
            # Now load collectors, an important part for packs :)
            hostingdriver_dir = os.path.join(dir, 'hostingdrivers')
            if os.path.exists(hostingdriver_dir):
                hostingctxmgr.load_directory(hostingdriver_dir, pack_name=pname, pack_level=level)

        # now hosting driver class are loaded, we can detect which one is our own
        hostingctxmgr.detect()

    def load_compliancebackends_from_packs(self):
        # Load at running to avoid endless import loop
        from .compliancemgr import compliancemgr
        pack_directories = packer.give_pack_directories_to_load()

        for (pname, level, dir) in pack_directories:
            # Now load collectors, an important part for packs :)
            drv_dir = os.path.join(dir, 'compliancebackends')
            if os.path.exists(drv_dir):
                compliancemgr.load_directory(drv_dir, pack_name=pname, pack_level=level)

        # now hosting driver class are loaded, we can load all
        compliancemgr.load_backends()

    def finish_to_load_configuration_and_objects(self):
        t0 = time.time()
        # Now that packs are load and clean, we can load collector code from it
        self.load_collectors_from_packs()
        logger.debug('configmgr.load_collectors_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # load all compliance drivers
        self.load_compliancebackends_from_packs()
        logger.debug('configmgr.load_compliancebackends_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # Now that packs are load and clean, we can load modules code from it
        self.load_modules_from_packs()
        logger.debug('configmgr.load_modules_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # We load configuration from packs, but only the one we are sure we must load
        self.load_configuration_from_packs()
        logger.debug('configmgr.load_configuration_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # also load hosting driver (like EC2 or scaleway) from packs too
        configmgr.load_hostingdrivers_from_packs()
        logger.debug('configmgr.load_hostingdrivers_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # We can now give configuration to the collectors
        from .collectormanager import collectormgr
        collectormgr.get_parameters_from_packs()
        logger.debug('configmgr.get_parameters_from_packs :: %.3f' % (time.time() - t0))

        t0 = time.time()
        # We can now give configuration to the modules
        from .modulemanager import modulemanager
        modulemanager.get_parameters_from_packs()
        logger.debug('modulemanager.get_parameters_from_packs :: %.3f' % (time.time() - t0))

    ############## Http interface
    # We must create http callbacks in running because
    # we must have the self object
    def export_http(self):
        from .httpdaemon import http_export, response

        @http_export('/configuration/parameters')
        def dump_parameters():
            response.content_type = 'application/json'
            r = self.dump_parameters()
            logger.error('DUMP PARAMETERS: %s' % r)
            return r

configmgr = ConfigurationManager()


text:
/// <reference path="drawUtilities.js" />
/// <reference path="DrawWithJS.js" />


text:
from django.conf import settings
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import messages
from horizon import tables
from horizon import tabs
from horizon.utils import memoized
from horizon import workflows

from openstack_dashboard import api
from openstack_dashboard.api import keystone
from openstack_dashboard import policy
from openstack_dashboard import usage
from openstack_dashboard.usage import quotas

from openstack_dashboard.dashboards.identity.projects \
    import tables as project_tables
from openstack_dashboard.dashboards.identity.projects \
    import tabs as project_tabs
from openstack_dashboard.dashboards.identity.projects \
    import workflows as project_workflows
from openstack_dashboard.dashboards.project.overview \
    import views as project_views
from openstack_dashboard.utils import identity

PROJECT_INFO_FIELDS = ("domain_id",
                       "domain_name",
                       "name",
                       "description",
                       "enabled")

INDEX_URL = "horizon:identity:projects:index"

class TenantContextMixin(object):
    @memoized.memoized_method
    def get_object(self):
        tenant_id = self.kwargs['tenant_id']
        try:
            return api.keystone.tenant_get(self.request, tenant_id, admin=True)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve project information.'),
                              redirect=reverse(INDEX_URL))

    def get_context_data(self, **kwargs):
        context = super(TenantContextMixin, self).get_context_data(**kwargs)
        context['tenant'] = self.get_object()
        return context

class IndexView(tables.DataTableView):
    table_class = project_tables.TenantsTable
    template_name = 'identity/projects/index.html'
    page_title = _("Projects")

    def needs_filter_first(self, table):
        return self._needs_filter_first

    def has_more_data(self, table):
        return self._more

    def get_data(self):
        tenants = []
        marker = self.request.GET.get(
            project_tables.TenantsTable._meta.pagination_param, None)
        self._more = False
        filters = self.get_filters()

        self._needs_filter_first = False

        if policy.check((("identity", "identity:list_projects"),),
                        self.request):

            # If filter_first is set and if there are not other filters
            # selected, then search criteria must be provided and
            # return an empty list
            filter_first = getattr(settings, 'FILTER_DATA_FIRST', {})
            if filter_first.get('identity.projects', False) and len(
                    filters) == 0:
                self._needs_filter_first = True
                self._more = False
                return tenants

            domain_id = identity.get_domain_id_for_operation(self.request)
            try:
                tenants, self._more = api.keystone.tenant_list(
                    self.request,
                    domain=domain_id,
                    paginate=True,
                    filters=filters,
                    marker=marker)
            except Exception:
                exceptions.handle(self.request,
                                  _("Unable to retrieve project list."))
        elif policy.check((("identity", "identity:list_user_projects"),),
                          self.request):
            try:
                tenants, self._more = api.keystone.tenant_list(
                    self.request,
                    user=self.request.user.id,
                    paginate=True,
                    marker=marker,
                    filters=filters,
                    admin=False)
            except Exception:
                exceptions.handle(self.request,
                                  _("Unable to retrieve project information."))
        else:
            msg = \
                _("Insufficient privilege level to view project information.")
            messages.info(self.request, msg)

        if api.keystone.VERSIONS.active >= 3:
            domain_lookup = api.keystone.domain_lookup(self.request)
            for t in tenants:
                t.domain_name = domain_lookup.get(t.domain_id)

        return tenants

class ProjectUsageView(usage.UsageView):
    table_class = usage.ProjectUsageTable
    usage_class = usage.ProjectUsage
    template_name = 'identity/projects/usage.html'
    csv_response_class = project_views.ProjectUsageCsvRenderer
    csv_template_name = 'project/overview/usage.csv'
    page_title = _("Project Usage")

    def get_data(self):
        super(ProjectUsageView, self).get_data()
        return self.usage.get_instances()

class CreateProjectView(workflows.WorkflowView):
    workflow_class = project_workflows.CreateProject

    def get_initial(self):
        initial = super(CreateProjectView, self).get_initial()

        # Set the domain of the project
        domain = api.keystone.get_default_domain(self.request)
        initial["domain_id"] = domain.id
        initial["domain_name"] = domain.name

        return initial

class UpdateProjectView(workflows.WorkflowView):
    workflow_class = project_workflows.UpdateProject

    def get_initial(self):
        initial = super(UpdateProjectView, self).get_initial()

        project_id = self.kwargs['tenant_id']
        initial['project_id'] = project_id

        try:
            # get initial project info
            project_info = api.keystone.tenant_get(self.request, project_id,
                                                   admin=True)
            for field in PROJECT_INFO_FIELDS:
                initial[field] = getattr(project_info, field, None)

            if keystone.VERSIONS.active >= 3:
                # get extra columns info
                ex_info = getattr(settings, 'PROJECT_TABLE_EXTRA_INFO', {})
                for ex_field in ex_info:
                    initial[ex_field] = getattr(project_info, ex_field, None)

                # Retrieve the domain name where the project belong
                try:
                    if policy.check((("identity", "identity:get_domain"),),
                                    self.request):
                        domain = api.keystone.domain_get(self.request,
                                                         initial["domain_id"])
                        initial["domain_name"] = domain.name

                    else:
                        domain = api.keystone.get_default_domain(self.request)
                        initial["domain_name"] = domain.name

                except Exception:
                    exceptions.handle(self.request,
                                      _('Unable to retrieve project domain.'),
                                      redirect=reverse(INDEX_URL))
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve project details.'),
                              redirect=reverse(INDEX_URL))
        return initial

class UpdateQuotasView(workflows.WorkflowView):
    workflow_class = project_workflows.UpdateQuota

    def get_initial(self):
        initial = super(UpdateQuotasView, self).get_initial()
        project_id = self.kwargs['tenant_id']
        initial['project_id'] = project_id
        try:
            # get initial project quota
            if keystone.is_cloud_admin(self.request):
                quota_data = quotas.get_tenant_quota_data(self.request,
                                                          tenant_id=project_id)
                for field in quotas.QUOTA_FIELDS:
                    initial[field] = quota_data.get(field).limit
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve project quotas.'),
                              redirect=reverse(INDEX_URL))
        initial['disabled_quotas'] = quotas.get_disabled_quotas(self.request)
        return initial

class DetailProjectView(tabs.TabView):
    tab_group_class = project_tabs.ProjectDetailTabs
    template_name = 'horizon/common/_detail.html'
    page_title = "{{ project.name }}"

    def get_context_data(self, **kwargs):
        context = super(DetailProjectView, self).get_context_data(**kwargs)
        project = self.get_data()
        table = project_tables.TenantsTable(self.request)
        context["project"] = project
        context["url"] = reverse(INDEX_URL)
        context["actions"] = table.render_row_actions(project)

        return context

    @memoized.memoized_method
    def get_data(self):
        try:
            project_id = self.kwargs['project_id']
            project = api.keystone.tenant_get(self.request, project_id)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve project details.'),
                              redirect=reverse(INDEX_URL))
        return project

    def get_tabs(self, request, *args, **kwargs):
        project = self.get_data()
        return self.tab_group_class(request, project=project, **kwargs)


text:
CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
    aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    region: ENV['AWS_REGION']
  }
  config.fog_directory = ENV['IKIDOWINAN_AUDIO_UPLOAD_BUCKET']

  if Rails.env.test? or Rails.env.cucumber?
    config.storage = :file
    config.enable_processing = false
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Luval.AzureSync
{
    public class HashProvider
    {
        private readonly MD5CryptoServiceProvider _md5;
        private static HashProvider _instance;

        public HashProvider()
        {
            _md5 = new MD5CryptoServiceProvider();
        }

        public string GetHash(Stream stream)
        {
            string hash;
            using (var bytes = new MemoryStream())
            {
                using (stream)
                {
                    stream.CopyTo(bytes);
                    hash = GetHash(bytes.ToArray());
                }
            }
            return hash;
        }

        public string GetHash(byte[] data)
        {
            var hash = _md5.ComputeHash(data);
            return Convert.ToBase64String(hash);
        }

        public static HashProvider Instance
        {
            get { return _instance ?? (_instance = new HashProvider()); }
        }

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap 101 Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

         Navbar Example
         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#hamburger-navigation">
           Navigation toggle

         </button>

             Follow us!

Current Pagecurrent

Link

             Dropdown

Option one

Option two

The Team


text:
/**
 * $Id: GameEffects.java 204 2005-07-11 15:51:19Z yaric $
 */
package ng.games.bombman.media;

import ng.games.bombman.BombmanDAO;

/**
 * Class to perform game effects.
 *
Copyright: Copyright (c) 2005

 *
Company: NewGround

 * @author Yaroslav Omelyanenko
 * @version 1.0
 */
public class GameEffects
{
  /** true if device has sound support */
  public static final boolean hasSound = true;

  /**
   * Default constructor.
   * @param dao the DAO to acquire resources.
   */
  public GameEffects( BombmanDAO dao ){}

  /**
   * Starts playing title music.
   */
  public void startTitleMusic(){}

  /**
   * Stops playing title music.
   */
  public void stopTitleMusic(){}

  /**
   * Bomb explosion
   */
  public void bombExplosion(){}

  /**
   * Pickup bonus
   */
  public void pickUpBonus(){}

  /**
   * Scream
   */
  public final void scream()
  {
  }

  /**
   * Win sound
   */
  public final void winSound()
  {
  }

  /**
   * Method to destroy all resources associated with this class.
   */
  public final void destroy(){}
}


text:
"""Version-independent api tests"""

import httplib2
from oslo_serialization import jsonutils

from glance.tests import functional

class TestApiVersions(functional.FunctionalTest):

    def test_version_configurations(self):
        """Test that versioning is handled properly through all channels"""
        # v1 and v2 api enabled
        self.start_servers(**self.__dict__.copy())

        url = 'http://127.0.0.1:%d/v%%s/' % self.api_port
        versions = {'versions': [
            {
                'id': 'v2.3',
                'status': 'CURRENT',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.2',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v1.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
            {
                'id': 'v1.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
        ]}
        versions_json = jsonutils.dumps(versions)

        # Verify version choices returned.
        path = 'http://%s:%d' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(versions_json, content)

    def test_v2_api_configuration(self):
        self.api_server.enable_v1_api = False
        self.api_server.enable_v2_api = True
        self.start_servers(**self.__dict__.copy())

        url = 'http://127.0.0.1:%d/v%%s/' % self.api_port
        versions = {'versions': [
            {
                'id': 'v2.3',
                'status': 'CURRENT',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.2',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
        ]}
        versions_json = jsonutils.dumps(versions)

        # Verify version choices returned.
        path = 'http://%s:%d' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(versions_json, content)

    def test_v1_api_configuration(self):
        self.api_server.enable_v1_api = True
        self.api_server.enable_v2_api = False
        self.start_servers(**self.__dict__.copy())

        url = 'http://127.0.0.1:%d/v%%s/' % self.api_port
        versions = {'versions': [
            {
                'id': 'v1.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
            {
                'id': 'v1.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
        ]}
        versions_json = jsonutils.dumps(versions)

        # Verify version choices returned.
        path = 'http://%s:%d' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(versions_json, content)

class TestApiPaths(functional.FunctionalTest):
    def setUp(self):
        super(TestApiPaths, self).setUp()
        self.start_servers(**self.__dict__.copy())

        url = 'http://127.0.0.1:%d/v%%s/' % self.api_port
        versions = {'versions': [
            {
                'id': 'v2.3',
                'status': 'CURRENT',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.2',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v2.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '2'}],
            },
            {
                'id': 'v1.1',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
            {
                'id': 'v1.0',
                'status': 'SUPPORTED',
                'links': [{'rel': 'self', 'href': url % '1'}],
            },
        ]}
        self.versions_json = jsonutils.dumps(versions)
        images = {'images': []}
        self.images_json = jsonutils.dumps(images)

    def test_get_root_path(self):
        """Assert GET / with `no Accept:` header.
        Verify version choices returned.
        Bug lp:803260  no Accept header causes a 500 in glance-api
        """
        path = 'http://%s:%d' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_images_path(self):
        """Assert GET /images with `no Accept:` header.
        Verify version choices returned.
        """
        path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_v1_images_path(self):
        """GET /v1/images with `no Accept:` header.
        Verify empty images list returned.
        """
        path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(200, response.status)

    def test_get_root_path_with_unknown_header(self):
        """Assert GET / with Accept: unknown header
        Verify version choices returned. Verify message in API log about
        unknown accept header.
        """
        path = 'http://%s:%d/' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        headers = {'Accept': 'unknown'}
        response, content = http.request(path, 'GET', headers=headers)
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_root_path_with_openstack_header(self):
        """Assert GET / with an Accept: application/vnd.openstack.images-v1
        Verify empty image list returned
        """
        path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        headers = {'Accept': 'application/vnd.openstack.images-v1'}
        response, content = http.request(path, 'GET', headers=headers)
        self.assertEqual(200, response.status)
        self.assertEqual(self.images_json, content)

    def test_get_images_path_with_openstack_header(self):
        """Assert GET /images with a
        `Accept: application/vnd.openstack.compute-v1` header.
        Verify version choices returned. Verify message in API log
        about unknown accept header.
        """
        path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        headers = {'Accept': 'application/vnd.openstack.compute-v1'}
        response, content = http.request(path, 'GET', headers=headers)
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_v10_images_path(self):
        """Assert GET /v1.0/images with no Accept: header
        Verify version choices returned
        """
        path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)

    def test_get_v1a_images_path(self):
        """Assert GET /v1.a/images with no Accept: header
        Verify version choices returned
        """
        path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)

    def test_get_va1_images_path(self):
        """Assert GET /va.1/images with no Accept: header
        Verify version choices returned
        """
        path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_versions_path(self):
        """Assert GET /versions with no Accept: header
        Verify version choices returned
        """
        path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_versions_path_with_openstack_header(self):
        """Assert GET /versions with the
        `Accept: application/vnd.openstack.images-v1` header.
        Verify version choices returned.
        """
        path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        headers = {'Accept': 'application/vnd.openstack.images-v1'}
        response, content = http.request(path, 'GET', headers=headers)
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_v1_versions_path(self):
        """Assert GET /v1/versions with `no Accept:` header
        Verify 404 returned
        """
        path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(404, response.status)

    def test_get_versions_choices(self):
        """Verify version choices returned"""
        path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_images_path_with_openstack_v2_header(self):
        """Assert GET /images with a
        `Accept: application/vnd.openstack.compute-v2` header.
        Verify version choices returned. Verify message in API log
        about unknown version in accept header.
        """
        path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        headers = {'Accept': 'application/vnd.openstack.images-v10'}
        response, content = http.request(path, 'GET', headers=headers)
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)

    def test_get_v12_images_path(self):
        """Assert GET /v1.2/images with `no Accept:` header
        Verify version choices returned
        """
        path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'GET')
        self.assertEqual(300, response.status)
        self.assertEqual(self.versions_json, content)


text:
package org.factcenter.qilin.primitives;

import org.factcenter.qilin.util.ByteEncoder;
import org.factcenter.qilin.util.GenericsUtils;
import org.factcenter.qilin.util.GlobalTestParams;
import org.junit.Test;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Random;

import static org.junit.Assert.*;

/**
 * Test class for generic group
 * Actual tests should extend this class.
 * @author talm
 *
 * @param <G>
 */
public abstract class GroupTest<G> implements GlobalTestParams {

	abstract protected Group<G> getGroup();
	abstract protected ByteEncoder<G> getEncoder();
	abstract protected Random getRand();

	/**
	 * Check that the order of the group divides orderUpperBound()
	 */
	@Test
	public void testOrder() {
		Group<G> g = getGroup();
		Random rand = getRand();
		BigInteger ord = g.orderUpperBound();
		G zero = g.zero();
		for (int i = 0; i < CONFIDENCE; ++i) {
			G e = g.sample(rand);
			G test = g.multiply(e, ord);
			assertTrue("Order of group does not divide upper bound", GenericsUtils.deepEquals(test, zero));
		}
	}

	/**
	 * Check that random returns a value in the group,
	 * and that the number of different values it returns
	 * is at least 1/4 the expected number. Note
	 * that this test assumes orderUpperBound will return at most
	 * twice the actual upper bound.
	 */
	@Test
	public void testRandom() {
		Group<G> g = getGroup();
		Random rand = getRand();
		HashSet<G> set = new HashSet<G>();
		float expSize = 0;
		float groupOrder = g.orderUpperBound().floatValue();
		for (int i = 0; i < CONFIDENCE; ++i) {
			expSize += 1 - set.size()/groupOrder;
			G e = g.sample(rand);
			assertTrue("Random element isn't member of group", g.contains(e));
			set.add(e);
		}

		assertTrue("Random set is too small", set.size() > expSize / 4);
	}

	/**
	 * Check that random elements of the group are associative with
	 * respect to addition.
	 */
	@Test
	public void testAssociativeness() {
		Group<G> g = getGroup();
		Random rand = getRand();
		for (int i = 0; i < CONFIDENCE; ++i) {
			G e1 = g.sample(rand);
			//assertTrue("Random element isn't member of group", g.contains(e1));
			G e2 = g.sample(rand);
			//assertTrue("Random element isn't member of group", g.contains(e2));
			G e3 = g.sample(rand);
			//assertTrue("Random element isn't member of group", g.contains(e3));

			assertTrue("Random elements aren't associative", g.add(g.add(e1, e2),e3).equals(g.add(e1, g.add(e2, e3))));
		}
	}

	/**
	 * Check that the neutral element of the group obeys axioms.
	 */
	@Test
	public void testZero() {
		Group<G> g = getGroup();
		Random rand = getRand();
		G zero = g.zero();

		assertTrue("-0 != 0", GenericsUtils.deepEquals(zero, g.negate(zero)));

		for (int i = 0; i < CONFIDENCE; ++i) {
			G e1 = g.sample(rand);
			//assertTrue("Random element isn't member of group", g.contains(e1));
			assertTrue("r+0 != r", g.add(e1, zero).equals(e1));
			assertTrue("0+r != r", g.add(zero, e1).equals(e1));
			assertTrue("r+(-r) != 0", g.add(e1, g.negate(e1)).equals(zero));
			assertTrue("(-r)+r != 0", g.add(g.negate(e1), e1).equals(zero));
		}
	}

	/**
	 * Check distributivity of multiplication.
	 */
	@Test
	public void testMultiply() {
		Group<G> g = getGroup();
		Random rand = getRand();
		BigInteger TWO = new BigInteger("2");
		int maxBits = g.orderUpperBound().bitLength();
		for (int i = 0; i < CONFIDENCE; ++i) {
			G e1 = g.sample(rand);
			//assertTrue("Random element isn't member of group", g.contains(e1));
			assertTrue("r+r != 2r", g.add(e1, e1).equals(g.multiply(e1, TWO)));
			BigInteger a = new BigInteger(maxBits, rand);
			BigInteger b = new BigInteger(maxBits, rand);
			assertTrue("ar+br != (a+b)r",
					g.add(g.multiply(e1, a), g.multiply(e1, b)).equals(g.multiply(e1, a.add(b))));
		}
	}

	/**
	 * Check that random elements have inverses.
	 */
	 @Test
	 public void testInverse() {
		 Group<G> g = getGroup();
		 Random rand = getRand();
		 final G zero = g.zero();
		 for (int i = 0; i < CONFIDENCE; ++i) {
			 G e1 = g.sample(rand);
			 G e2 = g.negate(e1);

			 //assertTrue("Random element isn't member of group", g.contains(e1));
			 assertTrue("r+ (-r) != 0", g.add(e1, e2).equals(zero));
		 }
	 }

	/**
	 * Check that we can encode arbitrary messages as group elements.
	 */
	@Test
	public void testInjectiveEncodeDecode() throws Exception {
		Group<G> g = getGroup();
		Random rand = getRand();

        int msgLen = g.getInjectiveEncodeMsgLength();
        if (msgLen > 0) {
            for (int i = 0; i < CONFIDENCE; ++i) {
                byte[] msg = new byte[msgLen];
                rand.nextBytes(msg);
                G encoded = g.injectiveEncode(msg, rand);
                byte[] decoded = g.injectiveDecode(encoded);

                assertArrayEquals("Decoded message is different from original at i=" + i, msg, decoded);
            }
        }
	}

    /**
     * Check that encoding zero-pads short messages.
     */
    @Test
    public void testInjectiveEncodeDecodeShort() throws Exception {
        Group<G> g = getGroup();
        Random rand = getRand();

        int msgLen = g.getInjectiveEncodeMsgLength();
        if (msgLen > 2) {
            for (int i = 0; i < CONFIDENCE; ++i) {
                int shortLen = rand.nextInt(msgLen - 2) + 1;
                byte[] msg = new byte[shortLen];
                rand.nextBytes(msg);
                G encoded = g.injectiveEncode(msg, rand);
                byte[] decoded = g.injectiveDecode(encoded);
                assertEquals("Message is not correct length at i=" + i, msgLen, decoded.length);

                byte[] prefix = new byte[msg.length];
                System.arraycopy(decoded, 0, prefix, 0, prefix.length);

                assertArrayEquals("Decoded message is different from original at i=" + i, msg, prefix);
                for (int j = prefix.length; j < decoded.length; ++j)
                    assertEquals("Padding is not zero at i=" + i, 0, decoded[j]);
            }
        }
    }

}