text:
import json

from unittest.mock import patch

from django.test import TestCase
from draftjs_exporter.dom import DOM
from draftjs_exporter.html import HTML as HTMLExporter

from wagtail.admin.rich_text.converters.contentstate import (
    ContentstateConverter, persist_key_for_block)
from wagtail.embeds.models import Embed

def content_state_equal(v1, v2, match_keys=False):
    "Test whether two contentState structures are equal, ignoring 'key' properties if match_keys=False"
    if type(v1) != type(v2):
        return False

    if isinstance(v1, dict):
        if set(v1.keys()) != set(v2.keys()):
            return False
        return all(
            (k == 'key' and not match_keys) or content_state_equal(v, v2[k], match_keys=match_keys)
            for k, v in v1.items()
        )
    elif isinstance(v1, list):
        if len(v1) != len(v2):
            return False
        return all(
            content_state_equal(a, b, match_keys=match_keys) for a, b in zip(v1, v2)
        )
    else:
        return v1 == v2

class TestHtmlToContentState(TestCase):
    fixtures = ['test.json']

    def assertContentStateEqual(self, v1, v2, match_keys=False):
        "Assert that two contentState structures are equal, ignoring 'key' properties if match_keys is False"
        self.assertTrue(
            content_state_equal(v1, v2, match_keys=match_keys),
            "%s does not match %s" % (json.dumps(v1, indent=4), json.dumps(v2, indent=4))
        )

    def test_paragraphs(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

Hello world!

Goodbye world!

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Goodbye world!', 'depth': 0, 'type': 'unstyled', 'key': '00001', 'entityRanges': []},
            ]
        }, match_keys=True)

    def test_unknown_block_becomes_paragraph(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''
            <foo>Hello world!</foo>
            <foo>I said hello world!</foo>

Goodbye world!

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'I said hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Goodbye world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_bare_text_becomes_paragraph(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''
            before

paragraph

            between

paragraph

            after
            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'before', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'paragraph', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'between', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'paragraph', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'after', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_ignore_unrecognised_tags_in_blocks(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

Hello <foo>frabjuous</foo> world!

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Hello frabjuous world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_inline_styles(self):
        converter = ContentstateConverter(features=['bold', 'italic'])
        result = json.loads(converter.from_database_format(
            '''

You do not talk about Fight Club.

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {
                    'inlineStyleRanges': [
                        {'offset': 4, 'length': 11, 'style': 'BOLD'}, {'offset': 7, 'length': 3, 'style': 'ITALIC'}
                    ],
                    'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []
                },
            ]
        })

    def test_inline_styles_at_top_level(self):
        converter = ContentstateConverter(features=['bold', 'italic'])
        result = json.loads(converter.from_database_format(
            '''
            You do not talk about Fight Club.
            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {
                    'inlineStyleRanges': [
                        {'offset': 4, 'length': 11, 'style': 'BOLD'}, {'offset': 7, 'length': 3, 'style': 'ITALIC'}
                    ],
                    'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []
                },
            ]
        })

    def test_inline_styles_at_start_of_bare_block(self):
        converter = ContentstateConverter(features=['bold', 'italic'])
        result = json.loads(converter.from_database_format(
            '''Seriously, stop talking about Fight Club already.'''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {
                    'inlineStyleRanges': [
                        {'offset': 0, 'length': 9, 'style': 'BOLD'},
                        {'offset': 30, 'length': 10, 'style': 'ITALIC'},
                    ],
                    'text': 'Seriously, stop talking about Fight Club already.', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []
                },
            ]
        })

    def test_inline_styles_depend_on_features(self):
        converter = ContentstateConverter(features=['italic', 'just-made-it-up'])
        result = json.loads(converter.from_database_format(
            '''

You do not talk about Fight Club.

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {
                    'inlineStyleRanges': [
                        {'offset': 7, 'length': 3, 'style': 'ITALIC'}
                    ],
                    'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []
                },
            ]
        })

    def test_ordered_list(self):
        converter = ContentstateConverter(features=['h1', 'ol', 'bold', 'italic'])
        result = json.loads(converter.from_database_format(
            '''

The rules of Fight Club

You do not talk about Fight Club.

You do not talk about Fight Club.

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'The rules of Fight Club', 'depth': 0, 'type': 'header-one', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'ordered-list-item', 'key': '00001', 'entityRanges': []},
                {
                    'inlineStyleRanges': [
                        {'offset': 4, 'length': 11, 'style': 'BOLD'}, {'offset': 7, 'length': 3, 'style': 'ITALIC'}
                    ],
                    'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'ordered-list-item', 'key': '00002', 'entityRanges': []
                },
            ]
        }, match_keys=True)

    def test_nested_list(self):
        converter = ContentstateConverter(features=['h1', 'ul'])
        result = json.loads(converter.from_database_format(
            '''

Shopping list

Milk

                    Flour

Plain

Self-raising

Eggs

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Shopping list', 'depth': 0, 'type': 'header-one', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Milk', 'depth': 0, 'type': 'unordered-list-item', 'key': '00001', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Flour', 'depth': 0, 'type': 'unordered-list-item', 'key': '00002', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Plain', 'depth': 1, 'type': 'unordered-list-item', 'key': '00003', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Self-raising', 'depth': 1, 'type': 'unordered-list-item', 'key': '00004', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Eggs', 'depth': 0, 'type': 'unordered-list-item', 'key': '00005', 'entityRanges': []},
            ]
        }, match_keys=True)

    def test_external_link(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''

an external link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'http://wagtail.org'}}
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_link_in_bare_text(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''an external link'''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'http://wagtail.org'}}
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_link_at_start_of_bare_text(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''an external link and another'''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'http://wagtail.org'}},
                '1': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'http://torchbox.com'}},
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link and another', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [
                        {'offset': 0, 'length': 16, 'key': 0},
                        {'offset': 21, 'length': 7, 'key': 1},
                    ]
                },
            ]
        })

    def test_page_link(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''

an internal link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'LINK',
                    'data': {'id': 3, 'url': '/events/', 'parentId': 2}
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an internal link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_broken_page_link(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''

an internal link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'LINK',
                    'data': {
                        'id': 9999, 'url': None, 'parentId': None,
                    }
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an internal link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_link_to_root_page(self):
        converter = ContentstateConverter(features=['link'])
        result = json.loads(converter.from_database_format(
            '''

an internal link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'LINK',
                    'data': {'id': 1, 'url': None, 'parentId': None}
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an internal link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_document_link(self):
        converter = ContentstateConverter(features=['document-link'])
        result = json.loads(converter.from_database_format(
            '''

a document link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'DOCUMENT',
                    'data': {'id': 1, 'url': '/documents/1/test.pdf', 'filename': 'test.pdf'}
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'a document link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 2, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_broken_document_link(self):
        converter = ContentstateConverter(features=['document-link'])
        result = json.loads(converter.from_database_format(
            '''

a document link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'DOCUMENT',
                    'data': {'id': 9999}
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'a document link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 2, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_document_link_with_missing_id(self):
        converter = ContentstateConverter(features=['document-link'])
        result = json.loads(converter.from_database_format(
            '''

a document link

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'mutability': 'MUTABLE', 'type': 'DOCUMENT',
                    'data': {}
                }
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'a document link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 2, 'length': 8, 'key': 0}]
                },
            ]
        })

    def test_image_embed(self):
        converter = ContentstateConverter(features=['image'])
        result = json.loads(converter.from_database_format(
            '''

before

            <embed embedtype="image" alt="an image" id="1" format="left" />

after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {
                '0': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                }
            }
        })

    def test_add_spacer_paragraph_between_image_embeds(self):
        converter = ContentstateConverter(features=['image'])
        result = json.loads(converter.from_database_format(
            '''
            <embed embedtype="image" alt="an image" id="1" format="left" />
            <embed embedtype="image" alt="an image" id="1" format="left" />
            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
                '1': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
            }
        })

    def test_image_after_list(self):
        """
        There should be no spacer paragraph inserted between a list and an image
        """
        converter = ContentstateConverter(features=['ul', 'image'])
        result = json.loads(converter.from_database_format(
            '''

Milk

Eggs

            <embed embedtype="image" alt="an image" id="1" format="left" />

More milk

More eggs

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {
                '0': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
            },
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Milk', 'depth': 0, 'type': 'unordered-list-item', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Eggs', 'depth': 0, 'type': 'unordered-list-item', 'key': '00000', 'entityRanges': []},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'inlineStyleRanges': [], 'text': 'More milk', 'depth': 0, 'type': 'unordered-list-item', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'More eggs', 'depth': 0, 'type': 'unordered-list-item', 'key': '00000', 'entityRanges': []},
            ]
        })

    @patch('wagtail.embeds.embeds.get_embed')
    def test_media_embed(self, get_embed):
        get_embed.return_value = Embed(
            url='https://www.youtube.com/watch?v=Kh0Y2hVe_bw',
            max_width=None,
            type='video',
            html='test html',
            title='what are birds',
            author_name='look around you',
            provider_name='YouTube',
            thumbnail_url='http://test/thumbnail.url',
            width=1000,
            height=1000,
        )

        converter = ContentstateConverter(features=['embed'])
        result = json.loads(converter.from_database_format(
            '''

before

            <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />

after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {
                '0': {
                    'data': {
                        'thumbnail': 'http://test/thumbnail.url',
                        'embedType': 'video',
                        'providerName': 'YouTube',
                        'title': 'what are birds',
                        'authorName': 'look around you',
                        'url': 'https://www.youtube.com/watch?v=Kh0Y2hVe_bw'
                    },
                    'mutability': 'IMMUTABLE', 'type': 'EMBED'
                }
            }
        })

    @patch('wagtail.embeds.embeds.get_embed')
    def test_add_spacer_paras_between_media_embeds(self, get_embed):
        get_embed.return_value = Embed(
            url='https://www.youtube.com/watch?v=Kh0Y2hVe_bw',
            max_width=None,
            type='video',
            html='test html',
            title='what are birds',
            author_name='look around you',
            provider_name='YouTube',
            thumbnail_url='http://test/thumbnail.url',
            width=1000,
            height=1000,
        )

        converter = ContentstateConverter(features=['embed'])
        result = json.loads(converter.from_database_format(
            '''
            <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />
            <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />
            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {
                    'data': {
                        'thumbnail': 'http://test/thumbnail.url',
                        'embedType': 'video',
                        'providerName': 'YouTube',
                        'title': 'what are birds',
                        'authorName': 'look around you',
                        'url': 'https://www.youtube.com/watch?v=Kh0Y2hVe_bw'
                    },
                    'mutability': 'IMMUTABLE', 'type': 'EMBED'
                },
                '1': {
                    'data': {
                        'thumbnail': 'http://test/thumbnail.url',
                        'embedType': 'video',
                        'providerName': 'YouTube',
                        'title': 'what are birds',
                        'authorName': 'look around you',
                        'url': 'https://www.youtube.com/watch?v=Kh0Y2hVe_bw'
                    },
                    'mutability': 'IMMUTABLE', 'type': 'EMBED'
                },
            }
        })

    def test_hr(self):
        converter = ContentstateConverter(features=['hr'])
        result = json.loads(converter.from_database_format(
            '''

before

after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {
                '0': {
                    'data': {},
                    'mutability': 'IMMUTABLE', 'type': 'HORIZONTAL_RULE'
                }
            }
        })

    def test_add_spacer_paragraph_between_hrs(self):
        converter = ContentstateConverter(features=['hr'])
        result = json.loads(converter.from_database_format(
            '''

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {
                    'data': {},
                    'mutability': 'IMMUTABLE', 'type': 'HORIZONTAL_RULE'
                },
                '1': {
                    'data': {},
                    'mutability': 'IMMUTABLE', 'type': 'HORIZONTAL_RULE'
                },
            }
        })

    def test_block_element_in_paragraph(self):
        converter = ContentstateConverter(features=['hr'])
        result = json.loads(converter.from_database_format(
            '''

before
after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {
                '0': {
                    'data': {},
                    'mutability': 'IMMUTABLE', 'type': 'HORIZONTAL_RULE'
                }
            }
        })

    def test_br_element_in_paragraph(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

before
after

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before\nafter',
                 'type': 'unstyled'}
            ],
        })

    def test_br_element_between_paragraphs(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

before

after

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
        })

    def test_block_element_in_empty_paragraph(self):
        converter = ContentstateConverter(features=['hr'])
        result = json.loads(converter.from_database_format(
            '''

            '''
        ))
        # ignoring the paragraph completely would probably be better,
        # but we'll settle for an empty preceding paragraph and not crashing as the next best thing...
        # (and if it's the first/last block we actually do want a spacer paragraph anyhow)
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {
                    'data': {},
                    'mutability': 'IMMUTABLE', 'type': 'HORIZONTAL_RULE'
                }
            }
        })

    def test_html_entities(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

Arthur "two sheds" Jackson <the third> & his wife

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Arthur "two sheds" Jackson <the third> & his wife', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_collapse_targeted_whitespace_characters(self):
        # We expect all targeted whitespace characters (one or more consecutively)
        # to be replaced by a single space. (\xa0 is a non-breaking whitespace)
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

Multiple whitespaces:     should  be reduced

Multiple non-breaking whitespace characters:  \xa0\xa0\xa0  should be preserved

            '''
        ))
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Multiple whitespaces: should be reduced', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Multiple non-breaking whitespace characters: \xa0\xa0\xa0 should be preserved', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_extra_end_tag_before(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

Before

            '''
        ))
        # The leading
 tag should be ignored instead of blowing up with a
        # pop from empty list error
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Before', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_extra_end_tag_after(self):
        converter = ContentstateConverter(features=[])
        result = json.loads(converter.from_database_format(
            '''

After

            '''
        ))
        # The tailing
 tag should be ignored instead of blowing up with a
        # pop from empty list error
        self.assertContentStateEqual(result, {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'After', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
            ]
        })

    def test_p_with_class(self):
        # Test support for custom conversion rules which require correct treatment of
        # CSS precedence in HTMLRuleset. Here,
 should match the
        # 'p[class="intro"]' rule rather than 'p' and thus become an 'intro-paragraph' block
        converter = ContentstateConverter(features=['intro'])
        result = json.loads(converter.from_database_format(
            '''

before

after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'intro-paragraph'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {}
        })

    def test_image_inside_paragraph(self):
        # In Draftail's data model, images are block-level elements and therefore
        # split up preceding / following text into their own paragraphs
        converter = ContentstateConverter(features=['image'])
        result = json.loads(converter.from_database_format(
            '''

before <embed embedtype="image" alt="an image" id="1" format="left" /> after

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'}
            ],
            'entityMap': {
                '0': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                }
            }
        })

    def test_image_inside_style(self):
        # https://github.com/wagtail/wagtail/issues/4602 - ensure that an <embed> inside
        # an inline style is handled. This is not valid in Draftail as images are block-level,
        # but should be handled without errors, splitting the image into its own block
        converter = ContentstateConverter(features=['image', 'italic'])
        result = json.loads(converter.from_database_format(
            '''

before <embed embedtype="image" alt="an image" id="1" format="left" /> after

<embed embedtype="image" alt="an image" id="1" format="left" />

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [{'offset': 0, 'length': 6, 'style': 'ITALIC'}], 'entityRanges': [], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [{'offset': 0, 'length': 5, 'style': 'ITALIC'}], 'entityRanges': [], 'depth': 0, 'text': 'after', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [{'offset': 0, 'length': 0, 'style': 'ITALIC'}], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [{'offset': 0, 'length': 0, 'style': 'ITALIC'}], 'entityRanges': [], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
                '1': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
            }
        })

    def test_image_inside_link(self):
        # https://github.com/wagtail/wagtail/issues/4602 - ensure that an <embed> inside
        # a link is handled. This is not valid in Draftail as images are block-level,
        # but should be handled without errors, splitting the image into its own block
        converter = ContentstateConverter(features=['image', 'link'])
        result = json.loads(converter.from_database_format(
            '''

before <embed embedtype="image" alt="an image" id="1" format="left" /> after

<embed embedtype="image" alt="an image" id="1" format="left" />

            '''
        ))
        self.assertContentStateEqual(result, {
            'blocks': [
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 6}], 'depth': 0, 'text': 'before', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 1, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 0, 'offset': 0, 'length': 5}], 'depth': 0, 'text': 'after', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 2, 'offset': 0, 'length': 0}], 'depth': 0, 'text': '', 'type': 'unstyled'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 3, 'offset': 0, 'length': 1}], 'depth': 0, 'text': ' ', 'type': 'atomic'},
                {'key': '00000', 'inlineStyleRanges': [], 'entityRanges': [{'key': 2, 'offset': 0, 'length': 0}], 'depth': 0, 'text': '', 'type': 'unstyled'},
            ],
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'https://wagtail.org'}},
                '1': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
                '2': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'https://wagtail.org'}},
                '3': {
                    'data': {'format': 'left', 'alt': 'an image', 'id': '1', 'src': '/media/not-found'},
                    'mutability': 'IMMUTABLE', 'type': 'IMAGE'
                },
            }
        })

class TestContentStateToHtml(TestCase):
    def test_external_link(self):
        converter = ContentstateConverter(features=['link'])
        contentstate_json = json.dumps({
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': 'http://wagtail.org'}}
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

        result = converter.to_database_format(contentstate_json)
        self.assertEqual(result, '
an external link
')

    def test_local_link(self):
        converter = ContentstateConverter(features=['link'])
        contentstate_json = json.dumps({
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': '/some/local/path/'}}
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

        result = converter.to_database_format(contentstate_json)
        self.assertEqual(result, '
an external link
')

    def test_reject_javascript_link(self):
        converter = ContentstateConverter(features=['link'])
        contentstate_json = json.dumps({
            'entityMap': {
                '0': {'mutability': 'MUTABLE', 'type': 'LINK', 'data': {'url': "javascript:alert('oh no')"}}
            },
            'blocks': [
                {
                    'inlineStyleRanges': [], 'text': 'an external link', 'depth': 0, 'type': 'unstyled', 'key': '00000',
                    'entityRanges': [{'offset': 3, 'length': 8, 'key': 0}]
                },
            ]
        })

        result = converter.to_database_format(contentstate_json)
        self.assertEqual(result, '
an external link
')

    def test_paragraphs_retain_keys(self):
        converter = ContentstateConverter(features=[])
        contentState = json.dumps({
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Goodbye world!', 'depth': 0, 'type': 'unstyled', 'key': '00001', 'entityRanges': []},
            ]
        })
        result = converter.to_database_format(contentState)
        self.assertHTMLEqual(result, '''

Hello world!

Goodbye world!

            ''')

    def test_wrapped_block_retains_key(self):
        # Test a block which uses a wrapper correctly receives the key defined on the inner element
        converter = ContentstateConverter(features=['h1', 'ol', 'bold', 'italic'])
        result = converter.to_database_format(json.dumps({
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'The rules of Fight Club', 'depth': 0, 'type': 'header-one', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'ordered-list-item', 'key': '00001', 'entityRanges': []},
                {
                    'inlineStyleRanges': [],
                    'text': 'You do not talk about Fight Club.', 'depth': 0, 'type': 'ordered-list-item', 'key': '00002', 'entityRanges': []
                },
            ]
        }))
        self.assertHTMLEqual(result, '''

The rules of Fight Club

You do not talk about Fight Club.

You do not talk about Fight Club.

        ''')

    def test_wrap_block_function(self):
        # Draft JS exporter's block_map config can also contain a function to handle a particular block
        # Test that persist_key_for_block still works with such a function, making the resultant conversion
        # keep the same block key between html and contentstate
        exporter_config = {
            'block_map': {
                'unstyled': persist_key_for_block(lambda props: DOM.create_element('p', {}, props['children'])),
            },
            'style_map': {},
            'entity_decorators': {},
            'composite_decorators': [],
            'engine': DOM.STRING,
        }
        contentState = {
            'entityMap': {},
            'blocks': [
                {'inlineStyleRanges': [], 'text': 'Hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []},
                {'inlineStyleRanges': [], 'text': 'Goodbye world!', 'depth': 0, 'type': 'unstyled', 'key': '00001', 'entityRanges': []},
            ]
        }
        result = HTMLExporter(exporter_config).render(contentState)
        self.assertHTMLEqual(result, '''

Hello world!

Goodbye world!

            ''')

    def test_style_fallback(self):
        # Test a block which uses an invalid inline style, and will be removed
        converter = ContentstateConverter(features=[])

        with self.assertLogs(level='WARNING') as log_output:
            result = converter.to_database_format(json.dumps({
                'entityMap': {},
                'blocks': [
                    {
                        'inlineStyleRanges': [{'offset': 0, 'length': 12, 'style': 'UNDERLINE'}],
                        'text': 'Hello world!', 'depth': 0, 'type': 'unstyled', 'key': '00000', 'entityRanges': []
                    },
                ]
            }))

        self.assertHTMLEqual(result, '''

                Hello world!

        ''')
        self.assertIn(
            'Missing config for "UNDERLINE". Deleting style.',
            log_output.output[0]
        )


text:
/*
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 */
#ifndef COMMONCRYPTO_H
#define COMMONCRYPTO_H

#include "buffer.h"

int CommonCryptoMD5   (BufferT* in,BufferT* digest,bool useCommon);
int CommonCryptoSHA1  (BufferT* in,BufferT* digest,bool useCommon);
int CommonCryptoSHA256(BufferT* in,BufferT* digest,bool useCommon);
int CommonCryptoSHA512(BufferT* in,BufferT* digest,bool useCommon);

int CommonCryptoAES128Encrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoAES128Decrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoCASTEncrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoCASTDecrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoTwofishEncrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoTwofishDecrypt(BufferT* in,BufferT* key,BufferT* iv,BufferT* out,bool useCommon);
int CommonCryptoRandomData(BufferT* data);
int CommonCryptoDeriveKey(BufferT* pwd,BufferT* salt,BufferT* key,unsigned int iter,bool useCommon);
#endif
/*====================================================END-OF-FILE============================================*/

redpajama_set_name: RedPajamaGithub


text:
var templates = (function(){

	var compiled = {};

	_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

	$("script[type=template]").each(function(){
		var tmpl = $(this);
		compiled[tmpl.attr("data-name")] = _.template(tmpl.html());
	});

	var parse = function(template,data) {
		return compiled[template](data);
	}

	return {
		parse:parse,
		group:_.curry(parse)
	}

})();

var vec2nav = (function(){

	var $word = $("#word");
	var $wordlist = $("#wordlist");
	var $phraselist = $("#phraselist");

	var display = function(type,word,data) {
		if (!(data.d && data.d.results && data.d.results.length)) return;
		var $group = $(templates.parse("word-list",{word:word}));
		$("#"+type).append($group);
		$group.children(".list").append(data.d.results.map(templates.group(type)));
	};

	var lookup = function(resource){
		var last = "";
		var method = _.curry(display)(resource);
		return function(word) {
			if(word && word !== last) {
				last = word;
				$.get("/"+resource+"/"+word).done(method(word));
			}
		}
	}

	var timeout = function(delay,callback) {
		var id;
		return function() {
			var self = this;
			var args = Array.prototype.slice.call(arguments);
			clearTimeout(id);
			id = setTimeout(function(){
				callback.apply(self,args);
			},delay);
		}
	}

	var lookupWord   = lookup("words");
	var lookupPhrase = lookup("phrases");

	$word.on("keyup",timeout(500,function(e){
		lookupWord($word.val());
		lookupPhrase($word.val());
	}));

	$("#lists").on("click",".word",function(e){
		var word = $(this).attr("data-value");
		$word.val(word);
		lookupWord(word);
		lookupPhrase(word);
	});

	return {
		lookupWord:lookupWord
	};

})();


text:
using System;

namespace Azure.ResourceManager.SecurityInsights.Models
{
    /// <summary> Represents MTP (Microsoft Threat Protection) requirements check request. </summary>
    public partial class MtpCheckRequirements : DataConnectorsCheckRequirements
    {
        /// <summary> Initializes a new instance of MtpCheckRequirements. </summary>
        public MtpCheckRequirements()
        {
            Kind = DataConnectorKind.MicrosoftThreatProtection;
        }

        /// <summary> The tenant id to connect to, and get the data from. </summary>
        public Guid? TenantId { get; set; }
    }
}


text:
#ifndef UTILS_LENNARDJONESCALCULATORSETTINGS_H
#define UTILS_LENNARDJONESCALCULATORSETTINGS_H

#include <Utils/IO/FilesystemHelpers.h>
#include <Utils/Settings.h>
#include <Utils/UniversalSettings/SettingsNames.h>

namespace Scine {
namespace Utils {
namespace SettingsNames {
static constexpr const char* lennardJonesSigma = "lj_sigma";
static constexpr const char* lennardJonesEpsilon = "lj_epsilon";
static constexpr const char* lennardJonesCutoff = "lj_cutoff";
} // namespace SettingsNames

/**
 * @class LennardJonesCalculatorSettings LennardJonesCalculatorSettings.h
 * @brief Settings for Lennard-Jones calculations.
 */
class LennardJonesCalculatorSettings : public Scine::Utils::Settings {
 public:
  /**
   * @brief Populates the Lennard-Jones settings
   */
  void populateSettings(UniversalSettings::DescriptorCollection& settings);

  /**
   * @brief Constructor that populates the LennardJonesCalculatorSettings.
   */
  LennardJonesCalculatorSettings() : Settings("LennardJonesCalculatorSettings") {
    populateSettings(_fields);
    resetToDefaults();
  };
};

inline void LennardJonesCalculatorSettings::populateSettings(UniversalSettings::DescriptorCollection& settings) {
  UniversalSettings::DoubleDescriptor convergence_threshold("Energy convergence limit.");
  convergence_threshold.setDefaultValue(1e-12);
  settings.push_back(SettingsNames::selfConsistenceCriterion, convergence_threshold);

  Utils::UniversalSettings::DoubleDescriptor lennardJonesSigma(
      "The sigma parameter for the Lennard-Jones potential in bohr.");
  lennardJonesSigma.setMinimum(0.);
  lennardJonesSigma.setDefaultValue(6.4); // reasonable for Ar
  settings.push_back(Scine::Utils::SettingsNames::lennardJonesSigma, std::move(lennardJonesSigma));

  Utils::UniversalSettings::DoubleDescriptor lennardJonesEpsilon(
      "The depth epsilon of the Lennard-Jones potential in K.");
  lennardJonesEpsilon.setMinimum(0.);
  lennardJonesEpsilon.setDefaultValue(120); // reasonable for Ar
  settings.push_back(Scine::Utils::SettingsNames::lennardJonesEpsilon, std::move(lennardJonesEpsilon));

  Utils::UniversalSettings::DoubleDescriptor lennardJonesCutoff(
      "The cutoff radius for the Lennard-Jones potential in bohr.");
  lennardJonesCutoff.setMinimum(0.);
  lennardJonesCutoff.setDefaultValue(16.);
  settings.push_back(Scine::Utils::SettingsNames::lennardJonesCutoff, std::move(lennardJonesCutoff));

  Utils::UniversalSettings::StringDescriptor lennardJonesPBCs(
      "The periodic boundary conditions. Empty if not applied.");
  lennardJonesPBCs.setDefaultValue("");
  settings.push_back(Scine::Utils::SettingsNames::periodicBoundaries, std::move(lennardJonesPBCs));
}

} // namespace Utils
} // namespace Scine

#endif // UTILS_LENNARDJONESCALCULATORSETTINGS_H


text:
<?php

namespace ShnfuCarver\Component\Dispatcher\Response\Unit;

/**
 * Cookie collection class
 *
 * @package    ShnfuCarver
 * @subpackage Component\Dispatcher\Response\Unit
 * @copyright  2012 Shnfu
 * @author     Zhao Xianghu <xianghuzhao@gmail.com>
 * @license    http://carver.shnfu.com/license.txt    New BSD License
 */
class CookieCollection
{
    /**
     * The cookie
     *
     * @var array
     */
    private $_cookie = array();

    /**
     * construct
     *
     * @param  array $cookie
     * @return void
     */
    public function __construct(array $cookie = array())
    {
        $this->_cookie = $cookie;
    }

    /**
     * Add cookie
     *
     * @param  \ShnfuCarver\Component\Dispatcher\Response\Unit\Cookie $cookie
     * @return void
     */
    public function add(Cookie $cookie)
    {
        $cookieName = str_replace('-', '_', strtolower($cookie->getName()));

        $this->_cookie[$cookieName] = $cookie;
    }

    /**
     * Exist cookie
     *
     * @param  string $cookieName
     * @return bool
     */
    public function exist($cookieName)
    {
        $cookieName = str_replace('-', '_', strtolower($cookie->getName()));
        return isset($this->_cookie[$cookieName]);
    }

    /**
     * Get cookie with the name
     *
     * @param  string $cookieName
     * @return \ShnfuCarver\Component\Dispatcher\Response\Unit\Cookie
     */
    public function get($cookieName)
    {
        $cookieName = str_replace('-', '_', strtolower($cookie->getName()));
        if (!isset($this->_cookie[$cookieName]))
        {
            return null;
        }

        return $this->_cookie[$cookieName];
    }

    /**
     * Get all cookies
     *
     * @return array
     */
    public function getAll()
    {
        return $this->_cookie;
    }
}

?>


text:
package com.foilen.smalltools.tools;

public class SystemTools {

    /**
     * Get the property, the environment or null value.
     *
     * @param key
     *            the key
     * @return the value
     */
    public static String getPropertyOrEnvironment(String key) {
        return getPropertyOrEnvironment(key, null);
    }

    /**
     * Get the property, the environment or the default value.
     *
     * @param key
     *            the key
     * @param defaultValue
     *            the default value
     * @return the value
     */
    public static String getPropertyOrEnvironment(String key, String defaultValue) {
        String value = System.getProperty(key);
        if (value != null) {
            return value;
        }

        value = System.getenv(key);
        if (value != null) {
            return value;
        }

        return defaultValue;
    }

    /**
     * Sets a system property if not already defined.
     *
     * @param key
     *            the property's key
     * @param value
     *            the property's value
     */
    public static void setPropertyIfNotSet(String key, String value) {
        String currentValue = System.getProperty(key);
        if (currentValue == null) {
            System.setProperty(key, value);
        }
    }

    private SystemTools() {
    }

}


text:
#include "caffe2/mpi/mpi_ops.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/operators/operator_fallback_gpu.h"

namespace caffe2 {

// Here is a bunch of MPI macro definitions that allow us to see if the MPI
// version supports CUDA aware MPI functions or not.

#if OPEN_MPI
#define CAFFE2_OMPI_VERSION \
  OMPI_MAJOR_VERSION * 10000 + OMPI_MINOR_VERSION * 100 + OMPI_RELEASE_VERSION
#if CAFFE2_OMPI_VERSION >= 20000
// OpenMPI 2.x now supports compile time check whether CUDA is supported.
#include "mpi-ext.h" /* Needed for CUDA-aware check */
#if MPIX_CUDA_AWARE_SUPPORT
#define CAFFE2_HAS_CUDA_MPI_BASICS 1
#define CAFFE2_HAS_CUDA_MPI_ALLREDUCE 1
#endif // MPIX_CUDA_AWARE_SUPPORT
#else // CAFFE2_OMPI_VERSION >= 2000
// In the case of OpenMPI 1.x, we don't have compile-time flags to
// figure out if CUDA is supported; as a result, we will assume that
// the user has built OpenMPI with CUDA support.
// CUDA-aware MPIBroadcast is introduced after OpenMPI 1.7.
#if CAFFE2_OMPI_VERSION >= 10700
#define CAFFE2_HAS_CUDA_MPI_BASICS 1
#else // CAFFE2_OMPI_VERSION >= 10700
#define CAFFE2_HAS_CUDA_MPI_BASICS 0
#endif // CAFFE2_OMPI_VERSION >= 10700
// CUDA-aware MPIAllreduce is introduced after OpenMPI 1.8.5.
#if CAFFE2_OMPI_VERSION >= 10805
#define CAFFE2_HAS_CUDA_MPI_ALLREDUCE 1
#else // CAFFE2_OMPI_VERSION >= 10805
#define CAFFE2_HAS_CUDA_MPI_ALLREDUCE 0
#endif // CAFFE2_OMPI_VERSION >= 10805
#endif // CAFFE2_OMPI_VERSION >= 2000
#else // !OPEN_MPI
// We have not really tested against other MPI environments, so let's go for a
// safe path and basically say we don't have cuda-aware functions.
#define CAFFE2_HAS_CUDA_MPI_BASICS 0
#define CAFFE2_HAS_CUDA_MPI_ALLREDUCE 0
#endif // OPEN_MPI

// We allow a macro to force using fallback functions.
#ifdef CAFFE2_FORCE_FALLBACK_CUDA_MPI
#undef CAFFE2_HAS_CUDA_MPI_BASICS
#undef CAFFE2_HAS_CUDA_MPI_ALLREDUCE
#define CAFFE2_HAS_CUDA_MPI_BASICS 0
#define CAFFE2_HAS_CUDA_MPI_ALLREDUCE 0
#endif // CAFFE2_FORCE_FALLBACK_CUDA_MPI

namespace {

REGISTER_CUDA_OPERATOR(
    MPICreateCommonWorld,
    MPICreateCommonWorldOp<CUDAContext>);
#if CAFFE2_HAS_CUDA_MPI_BASICS
REGISTER_CUDA_OPERATOR(MPIBroadcast, MPIBroadcastOp<CUDAContext>);
REGISTER_CUDA_OPERATOR(MPIReduce, MPIReduceOp<float, CUDAContext>);
REGISTER_CUDA_OPERATOR(MPIAllgather, MPIAllgatherOp<float, CUDAContext>);
REGISTER_CUDA_OPERATOR(MPISendTensor, MPISendTensorOp<CUDAContext>);
REGISTER_CUDA_OPERATOR(MPIReceiveTensor, MPIReceiveTensorOp<CUDAContext>);
#else
REGISTER_CUDA_OPERATOR(MPIBroadcast, GPUFallbackOp<MPIBroadcastOp<CPUContext>>);
REGISTER_CUDA_OPERATOR(
    MPIReduce,
    GPUFallbackOp<MPIReduceOp<float, CPUContext>>);
REGISTER_CUDA_OPERATOR(
    MPIAllgather,
    GPUFallbackOp<MPIAllgatherOp<float, CPUContext>>);
REGISTER_CUDA_OPERATOR(
    MPISendTensor,
    GPUFallbackOp<MPISendTensorOp<CPUContext>>);
REGISTER_CUDA_OPERATOR(
    MPIReceiveTensor,
    GPUFallbackOp<MPIReceiveTensorOp<CPUContext>, SkipIndices<1, 2>>);
#endif

#if CAFFE2_HAS_CUDA_MPI_ALLREDUCE
REGISTER_CUDA_OPERATOR(MPIAllreduce, MPIAllreduceOp<float, CUDAContext>);
#else
REGISTER_CUDA_OPERATOR(
    MPIAllreduce,
    GPUFallbackOp<MPIAllreduceOp<float, CPUContext>>);
#endif
}  // namespace

}  // namespace caffe2


text:
@extends('layouts.application')

@section('title'){{ getTitle('الحجز '. $extra->name) }}@endsection

@section('content')
	{{ $extra->name }}
    {!! form_start($form) !!}
    {!! form_row($form->name) !!}
    {!! form_row($form->artwork) !!}
    {!! form_row($form->description) !!}
    {!! form_row($form->space_info) !!}

session->prototype()) }}">

            {{-- remove icon --}}

            {{-- clone icon --}}

                  Collapsible Group Item #1 (template panel)

                                {!! form_row($form->session) !!}

    <button class="btn btn-primary btn-add-panel">  أضف جلسه</button>
    {!! form_until($form, 'apply'); !!}

        {!! form_until($form, 'apply_agreement'); !!}

    {!! form_end($form, true); !!}

@endsection

 <button class="pull-left" style="background: none; border: none;" type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
نسخ الجلسة

            فترة التكرار
            <select id="duplocation-period" name="duplocation-period" style="width: 100%;">
                <option value="every-day">كل يوم</option>
                <option value="every-week">كل اسبوع</option>
                <option value="every-month">كل شهر</option>
            </select>

            عدد مرات التكرار
            <input class="form-control" id="duplocation-number" value="1" name="duplocation-number" type="number">

        <input type="hidden" name="number" value="">

 <button class="duplicate-action btn-primary btn">نسخ</button>

 <button class="pull-left" style="background: none; border: none;" type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
قواعد إستخدام المساحة


text:
@interface DiscussListViewController ()<UITableViewDataSource, UITableViewDelegate>
//UI
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) DiscussListHeaderView *headerView;
//Data
@property (nonatomic, strong) NSArray *discussListTopDatas;
@property (nonatomic, strong) NSArray *discussListDatas;
@property (nonatomic, assign) NSInteger pageIndex;
@end

@implementation DiscussListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initParams];
    [self addTableView];
    [self loadData];
}

- (void)initParams
{
    _pageIndex = 1;
}

- (void)addTableView
{
    [self.view addSubview:self.tableView];
}

- (void)loadData
{
    [self loadDiscussListData];
}

- (void)loadDiscussListData
{
    NSDictionary *params = @{@"version":@"163",@"module":@"forumdisplay",@"fid":_fid?_fid:@"",@"tpp":@"15",@"charset":@"utf-8",@"page":@(_pageIndex).stringValue};
    [[HttpRequest sharedInstance] GET:DiscussListURL parameters:params success:^(id response) {
        NSLog(@"list-succ : %@", response);
        DiscussListModel *discussListModel = [DiscussListModel modelWithJSON:response[@"Variables"]];
        [self dealWithDiscussList:discussListModel.forum_threadlist];

        [self loadDiscussImageData];
    } failure:^(NSError *error) {
        NSLog(@"list-fail : %@", error);
    }];
}

- (void)loadDiscussImageData
{
    NSString *urlString = [NSString stringWithFormat:@"%@/%@", DiscussListImgURL, _fid];
    [[HttpRequest sharedInstance] GET:urlString parameters:nil success:^(id response) {
        NSLog(@"img-suc : %@", response);
        DiscussImageModel *discussImageModel = [DiscussImageModel modelWithJSON:response[@"info"]];
        [self dealWithDiscussHeaderViewWithDiscussImageModel:discussImageModel];
        [_tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"img-Err : %@", error);
    }];
}

- (void)dealWithDiscussHeaderViewWithDiscussImageModel:(DiscussImageModel *)imageModel
{

    self.headerView.imageModel = imageModel;
    self.tableView.tableHeaderView = self.headerView;
}

- (void)dealWithDiscussList:(NSArray *)discussList
{
    NSMutableArray *discussListTops = [NSMutableArray array];
    NSMutableArray *discussLists = [NSMutableArray array];

    for (ForumThread *forum in discussList) {
        if (forum.displayorder == 1) {
            [discussListTops addObject:forum];
        }else {
            [discussLists addObject:forum];
        }
    }
    _discussListDatas = [discussLists copy];
    _discussListTopDatas = [discussListTops copy];
}

#pragma mark - tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return _discussListTopDatas.count;
            break;
        case 1:
            return _discussListDatas.count;
            break;

        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            ForumThread *forumThread = _discussListTopDatas[indexPath.row];
            DiscussListTopCell *cell = [DiscussListTopCell cellWithTableView:tableView];
            cell.forumThread = forumThread;
            return cell;
        }
            break;
        case 1:
        {
            ForumThread *forumThread = _discussListDatas[indexPath.row];
            DiscussListCell *cell = [DiscussListCell cellWithTableView:tableView];
            cell.forumThread = forumThread;
            return cell;
        }
            break;
        default:
            return nil;
            break;
    }
}

#pragma mark - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            ForumThread *forumThread = _discussListTopDatas[indexPath.row];
            return [_tableView cellHeightForIndexPath:indexPath model:forumThread keyPath:@"forumThread" cellClass:[DiscussListTopCell class] contentViewWidth:_tableView.width];
        }
            break;
        case 1:
        {
            ForumThread *forumThread = _discussListDatas[indexPath.row];
            return [_tableView cellHeightForIndexPath:indexPath model:forumThread keyPath:@"forumThread" cellClass:[DiscussListCell class] contentViewWidth:_tableView.width];
        }
            break;
        default:
            return CGFLOAT_MIN;
            break;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumThread *forumThread = indexPath.section == 0 ? _discussListTopDatas[indexPath.row] : _discussListDatas[indexPath.row];
    DiscussDetailViewController *detailViewController = [[DiscussDetailViewController alloc] init];
    detailViewController.tid = forumThread.tid;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

#pragma mark - Getter / Setter
- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.dataSource = self;
        _tableView = tableView;
    }
    return _tableView;
}

- (DiscussListHeaderView *)headerView
{
    if (!_headerView) {
        DiscussListHeaderView *headerView = [[DiscussListHeaderView alloc] init];
        headerView.width = self.tableView.width;
        headerView.height = 150;
        _headerView = headerView;
    }
    return _headerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
#ifndef _EASYMESH_POINTS_MESH_H_
#define _EASYMESH_POINTS_MESH_H_

#include "Mesh.h"

#include <easyshape.h>

namespace emesh
{

class PointsMeshShape;

class PointsMesh : public Mesh, public eshape::EditedPolyShape, public s2::PolylineShape
{
public:
	PointsMesh();
	PointsMesh(const ee::SymPtr& base);

	/**
	 *  @interface
	 *    Mesh
	 */
	virtual void Load(const Json::Value& value) override;
	virtual void Store(Json::Value& value) const override;
//	virtual void Update() override;
	virtual void Refresh() override;
	virtual void TraverseMesh(ee::RefVisitor<ee::Shape>& visitor) const override;
	virtual bool RemoveMesh(const ee::ShapePtr& mesh) override;
	virtual bool InsertMesh(const ee::ShapePtr& mesh) override;
//	virtual bool ClearMesh() override;
	virtual void Reset() override;
	virtual void Clear() override;

	/**
	 *  @interface
	 *    Shape
	 */
	virtual const char* GetShapeDesc() const override { return "edited_poly"; }
	virtual void Translate(const sm::vec2& offset) override {}
	virtual ee::PropertySetting* CreatePropertySetting(ee::EditPanelImpl* stage) override { return NULL; }
// 	virtual void LoadFromFile(const Json::Value& value, const std::string& dir) override;
// 	virtual void StoreToFile(Json::Value& value, const std::string& dir) const override;

	/**
	 *  @interface
	 *    eshape::EditedPolyShape
	 */
	virtual void AddVertex(int index, const sm::vec2& pos) override;
	virtual void RemoveVertex(const sm::vec2& pos) override;
	virtual void ChangeVertex(const sm::vec2& from, const sm::vec2& to) override;
	virtual void SetVertices(const CU_VEC<sm::vec2>& vertices) override;
	virtual const CU_VEC<sm::vec2>& GetVertices() const override { return m_vertices; }
	virtual bool IsClosed() const override { return m_closed; }
	virtual int PointQueryVertex(const sm::vec2& p) const override;
	virtual void RectQueryVertices(const sm::rect& r, std::vector<int>& vertices) const override;

	int  QueryInnerPos(const sm::vec2& pos) const;
	bool InsertInnerPos(const sm::vec2& pos);
	bool RemoveInnerPos(const sm::vec2& pos);
	bool MoveInnerPos(int idx, const sm::vec2& pos);

	void GetInnerPoints(CU_VEC<sm::vec2>& points) const;

private:
	void UpdateMeshFromShape();

}; // PointsMesh

}

#endif // _EASYMESH_POINTS_MESH_H_


text:
package org.semanticweb.elk.owl.parsing;

import junit.framework.TestCase;

import org.semanticweb.elk.owl.implementation.ElkObjectFactoryImpl;
import org.semanticweb.elk.owl.interfaces.ElkClassExpression;
import org.semanticweb.elk.owl.interfaces.ElkObjectFactory;
import org.semanticweb.elk.owl.iris.ElkFullIri;
import org.semanticweb.elk.owl.managers.ElkEntityRecycler;

public class SyntaxTest extends TestCase {
	final ElkObjectFactory objectFactory = new ElkObjectFactoryImpl(new ElkEntityRecycler());

	public SyntaxTest(String testName) {
		super(testName);
	}

	public void testFactory() {
		ElkClassExpression heart = objectFactory.getClass(new ElkFullIri("Heart"));
		ElkClassExpression organ = objectFactory.getClass(new ElkFullIri("Organ"));
		ElkClassExpression heart2 = objectFactory.getClass(new ElkFullIri("Heart"));

		assertSame("heart == heart2", heart, heart2);
		assertNotSame("heart != organ", organ);

	}
}


text:
package com.adaptris.core.socket;

import com.adaptris.core.ConfiguredProduceDestination;
import com.adaptris.core.ProducerCase;
import com.adaptris.core.StandaloneProducer;

/**
 * @author lchan
 * @author $Author: lchan $
 */
public class TestSocketProducer extends ProducerCase {

  /**
   * Key in unit-test.properties that defines where example goes unless overriden {@link #setBaseDir(String)}.
   *
   */
  public static final String BASE_DIR_KEY = "SocketProducerExamples.baseDir";

  public TestSocketProducer(String name) {
    super(name);
    if (PROPERTIES.getProperty(BASE_DIR_KEY) != null) {
      setBaseDir(PROPERTIES.getProperty(BASE_DIR_KEY));
    }
  }

  @Override
  protected Object retrieveObjectForSampleConfig() {
    TcpProduceConnection tcp = new TcpProduceConnection();
    SocketProducer producer = new SocketProducer();
    producer.setDestination(new ConfiguredProduceDestination("tcp://localhost:9099"));
    producer
        .setProtocolImplementation("my.implementation.of.com.adaptris.core."
            + "socket.Protocol");
    return new StandaloneProducer(tcp, producer);
  }

  @Override
  public String getExampleCommentHeader(Object o) {
    return super.getExampleCommentHeader(o) + "\n<!--" + "\n-->";
  }
}


text:
using Badger.Redis.Types;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Badger.Redis.IO
{
    internal interface IWriter : IDisposable
    {
        Task WriteAsync(IRedisType value, CancellationToken cancellationToken);
    }
}


text: ALTER TABLE usuario MODIFY nome VARCHAR(150) NOT NULL;


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2016 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt

/**
 * UriBuilder a class which facilitates building a URI with a colleciton
 * of parameters in a query string.
 *
 * @author jis@mit.edu (Jeffrey I. Schiller)
 */

package com.google.appinventor.server.util;

import java.net.URLEncoder;

public class UriBuilder {
  private StringBuilder sb = new StringBuilder();
  private boolean first = true;

  public UriBuilder(String baseUri) {
    sb.append(baseUri);
  }

  public UriBuilder add(String key, String value) {
    // If value is null, we don't add it
    if (value == null) {
      return this;
    }
    if (first) {
      sb.append("?");
      first = false;
    } else {
      sb.append("&");
    }
    sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(value));
    return this;
  }

  public String build() {
    return new String(sb);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Drag and Drop</title>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

Drag and Drop

This JavaScript tree menu has extended drag-and-drop functionality
	(within one tree, between trees, between frames). Drop-as-sibling behavior makes
	it easy to reorder nodes in a tree view.
You can easily edit the tree by dragging nodes within one tree or between trees or even to another object.

	Drag-and-Drop works in each tree and between trees too.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<wicket:extend>

							<fieldset>
								<legend>Document</legend>

Open

Prev.

Next

							</fieldset>

							<fieldset>
								<legend>Page</legend>

First

Prev.

											<form wicket:id="gotoPageTextFieldForm">
												<input type="number" wicket:id="gotoPageText"
													style="width: 4em; text-align: right;" title="press Enter" />
											</form>

											Go to

Next

Last

							</fieldset>

							<fieldset>
								<legend>Help</legend>

							</fieldset>

							<fieldset>
								<legend>Workflow</legend>

							</fieldset>

	</wicket:extend>


text:
package util

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"log"
	"reflect"
	"sort"
	"strings"
)

const (
	DefaultSecretKey = "OTE3MTZhMjQ0OWFlYTAxNTQ5Njk2MDJi"
)

type SignError struct {
	Code int
	Msg  string
}

func (this SignError) Error() string {
	return this.Msg
}

func Sign(input, key string) string {
	keyForSign := []byte(key)
	h := hmac.New(sha1.New, keyForSign)
	h.Write([]byte(input))
	//	return base64.StdEncoding.EncodeToString(h.Sum(nil))
	return fmt.Sprintf("%x", h.Sum(nil))
}

// 将Map格式化成待签名的字符串,
// 注意此方法会滤掉map中value为空的所有键值对
func formatForSign(data map[string]interface{}) string {
	if data == nil {
		panic("invalid arguments")
	}
	var validKeys []string
	for k := range data {
		switch value := data[k].(type) {
		case string:
			if value != "" {
				validKeys = append(validKeys, k)
			}
		case []interface{}:
			if value != nil && len(value) > 0 {
				validKeys = append(validKeys, k)
			}
		case interface{}:
			validKeys = append(validKeys, k)
		default:
			log.Printf("Unknown type [%v], will not sign this value!\n", reflect.TypeOf(data[k]))
		}

	}

	sort.Strings(validKeys)

	var kv []string
	for _, k := range validKeys {
		switch value := data[k].(type) {
		case string:
			kv = append(kv, fmt.Sprintf("%s=%s", k, value))
		case []interface{}:
			vs := fmt.Sprintf("%v", value)
			kv = append(kv, fmt.Sprintf("%s=%s", k, strings.Replace(vs, " ", ",", -1)))
		case interface{}:
			kv = append(kv, fmt.Sprintf("%s=%v", k, value))
		}

	}
	dataForSign := strings.Join(kv, "&")
	return dataForSign
}

// 获取签名串,不包含其他任何东西,仅仅是签名字符串本身
func GetSignStr(data map[string]interface{}, key string) (string, error) {
	if data == nil || key == "" {
		log.Println("args could not be nil!!!")
		return "", SignError{Code: -1, Msg: "Arguments Error"}
	}
	dataForSign := formatForSign(data)
	log.Printf("data for sign: %s\n", dataForSign)
	return Sign(dataForSign, key), nil
}

// 构造已签名的请求字符串,
// 形式如: key1=val1&key2=val2&sign=signvalue
// 主要用于GET请求
func BuildSignedStr(data map[string]interface{}, key string) (string, error) {
	if data == nil || key == "" {
		log.Println("args could not be nil!!!")
		return "", SignError{Code: -1, Msg: "Arguments Error"}
	}
	dataForSign := formatForSign(data)
	log.Printf("data for sign: %s\n", dataForSign)
	sn := Sign(dataForSign, key)
	return dataForSign + "&sign=" + sn, nil
}

// 构造已签名的Json格式的字符串,主要用于POST请求的Body
func BuildSignedJsonStr(data map[string]interface{}, key string) (string, error) {
	if data == nil || key == "" {
		log.Println("args could not be nil!!!")
		return "", SignError{Code: -1, Msg: "Arguments Error"}
	}
	dataForSign := formatForSign(data)
	log.Printf("data for sign: %s\n", dataForSign)
	data["sign"] = Sign(dataForSign, key)
	js, jsErr := json.Marshal(data)
	if jsErr != nil {
		log.Println("format map to Json error")
		return "", SignError{Code: -1, Msg: "Error format request to Json"}
	}
	return string(js), nil
}

// 签名校验,验证通过返回true,否则返回false
func SignVerify(data map[string]interface{}, secret string, sign string) bool {
	if data == nil || sign == "" {
		log.Println("args could not be nil!!!")
		return false
	}
	if data["sign"] != "" {
		// map中存在sign字段,需要将它移除
		delete(data, "sign")
	}
	signStr, _ := GetSignStr(data, secret)
	log.Printf("verify result: orginSign=%s, correctSign=%s\n", sign, signStr)
	return signStr == sign
}

// 签名校验,原始签名串需要作为Json值放入到jsonStr参数中。
// 验证通过返回true,否则返回false
func SignVerify2(jsonStr string, secret string) bool {
	maps := make(map[string]interface{})
	br := bytes.NewReader([]byte(jsonStr))
	jd := json.NewDecoder(br)
	jd.UseNumber()
	err := jd.Decode(&maps)
	if err != nil {
		log.Printf("args is not a json!\n", jsonStr)
		return false
	}

	if originSign := maps["sign"]; originSign == nil {
		log.Println("sign segment not found or is empty")
		return false
	} else {
		return SignVerify(maps, secret, originSign.(string))
	}
}


text:
package com.amazonaws.services.ec2.model.transform;

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

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Import Instance Request Marshaller
 */
public class ImportInstanceRequestMarshaller implements Marshaller<Request<ImportInstanceRequest>, ImportInstanceRequest> {

    public Request<ImportInstanceRequest> marshall(ImportInstanceRequest importInstanceRequest) {

        if (importInstanceRequest == null) {
            throw new AmazonClientException("Invalid argument passed to marshall(...)");
        }

        Request<ImportInstanceRequest> request = new DefaultRequest<ImportInstanceRequest>(importInstanceRequest, "AmazonEC2");
        request.addParameter("Action", "ImportInstance");
        request.addParameter("Version", "2015-10-01");

        if (importInstanceRequest.getDescription() != null) {
            request.addParameter("Description", StringUtils.fromString(importInstanceRequest.getDescription()));
        }
        ImportInstanceLaunchSpecification importInstanceLaunchSpecificationLaunchSpecification = importInstanceRequest.getLaunchSpecification();
        if (importInstanceLaunchSpecificationLaunchSpecification != null) {
            if (importInstanceLaunchSpecificationLaunchSpecification.getArchitecture() != null) {
                request.addParameter("LaunchSpecification.Architecture", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getArchitecture()));
            }

            java.util.List<String> groupNamesList = importInstanceLaunchSpecificationLaunchSpecification.getGroupNames();
            int groupNamesListIndex = 1;

            for (String groupNamesListValue : groupNamesList) {
                if (groupNamesListValue != null) {
                    request.addParameter("LaunchSpecification.GroupName." + groupNamesListIndex, StringUtils.fromString(groupNamesListValue));
                }

                groupNamesListIndex++;
            }

            java.util.List<String> groupIdsList = importInstanceLaunchSpecificationLaunchSpecification.getGroupIds();
            int groupIdsListIndex = 1;

            for (String groupIdsListValue : groupIdsList) {
                if (groupIdsListValue != null) {
                    request.addParameter("LaunchSpecification.GroupId." + groupIdsListIndex, StringUtils.fromString(groupIdsListValue));
                }

                groupIdsListIndex++;
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.getAdditionalInfo() != null) {
                request.addParameter("LaunchSpecification.AdditionalInfo", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getAdditionalInfo()));
            }
            UserData userDataUserData = importInstanceLaunchSpecificationLaunchSpecification.getUserData();
            if (userDataUserData != null) {
                if (userDataUserData.getData() != null) {
                    request.addParameter("LaunchSpecification.UserData.Data", StringUtils.fromString(userDataUserData.getData()));
                }
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.getInstanceType() != null) {
                request.addParameter("LaunchSpecification.InstanceType", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getInstanceType()));
            }
            Placement placementPlacement = importInstanceLaunchSpecificationLaunchSpecification.getPlacement();
            if (placementPlacement != null) {
                if (placementPlacement.getAvailabilityZone() != null) {
                    request.addParameter("LaunchSpecification.Placement.AvailabilityZone", StringUtils.fromString(placementPlacement.getAvailabilityZone()));
                }
                if (placementPlacement.getGroupName() != null) {
                    request.addParameter("LaunchSpecification.Placement.GroupName", StringUtils.fromString(placementPlacement.getGroupName()));
                }
                if (placementPlacement.getTenancy() != null) {
                    request.addParameter("LaunchSpecification.Placement.Tenancy", StringUtils.fromString(placementPlacement.getTenancy()));
                }
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.isMonitoring() != null) {
                request.addParameter("LaunchSpecification.Monitoring.Enabled", StringUtils.fromBoolean(importInstanceLaunchSpecificationLaunchSpecification.isMonitoring()));
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.getSubnetId() != null) {
                request.addParameter("LaunchSpecification.SubnetId", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getSubnetId()));
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.getInstanceInitiatedShutdownBehavior() != null) {
                request.addParameter("LaunchSpecification.InstanceInitiatedShutdownBehavior", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getInstanceInitiatedShutdownBehavior()));
            }
            if (importInstanceLaunchSpecificationLaunchSpecification.getPrivateIpAddress() != null) {
                request.addParameter("LaunchSpecification.PrivateIpAddress", StringUtils.fromString(importInstanceLaunchSpecificationLaunchSpecification.getPrivateIpAddress()));
            }
        }

        java.util.List<DiskImage> diskImagesList = importInstanceRequest.getDiskImages();
        int diskImagesListIndex = 1;

        for (DiskImage diskImagesListValue : diskImagesList) {
            DiskImage diskImageMember = diskImagesListValue;
            if (diskImageMember != null) {
                DiskImageDetail diskImageDetailImage = diskImageMember.getImage();
                if (diskImageDetailImage != null) {
                    if (diskImageDetailImage.getFormat() != null) {
                        request.addParameter("DiskImage." + diskImagesListIndex + ".Image.Format", StringUtils.fromString(diskImageDetailImage.getFormat()));
                    }
                    if (diskImageDetailImage.getBytes() != null) {
                        request.addParameter("DiskImage." + diskImagesListIndex + ".Image.Bytes", StringUtils.fromLong(diskImageDetailImage.getBytes()));
                    }
                    if (diskImageDetailImage.getImportManifestUrl() != null) {
                        request.addParameter("DiskImage." + diskImagesListIndex + ".Image.ImportManifestUrl", StringUtils.fromString(diskImageDetailImage.getImportManifestUrl()));
                    }
                }
                if (diskImageMember.getDescription() != null) {
                    request.addParameter("DiskImage." + diskImagesListIndex + ".Description", StringUtils.fromString(diskImageMember.getDescription()));
                }
                VolumeDetail volumeDetailVolume = diskImageMember.getVolume();
                if (volumeDetailVolume != null) {
                    if (volumeDetailVolume.getSize() != null) {
                        request.addParameter("DiskImage." + diskImagesListIndex + ".Volume.Size", StringUtils.fromLong(volumeDetailVolume.getSize()));
                    }
                }
            }

            diskImagesListIndex++;
        }
        if (importInstanceRequest.getPlatform() != null) {
            request.addParameter("Platform", StringUtils.fromString(importInstanceRequest.getPlatform()));
        }

        return request;
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UnitEqualityHelper.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Sundew.Quantities.Representations.Expressions;

/// <summary>
/// Helper class for <see cref="IUnit" />.
/// </summary>
public static class UnitEqualityHelper
{
    /// <summary>
    /// Checks if the LHS and the RHS base units are equal.
    /// </summary>
    /// <param name="lhs">The LHS <see cref="IUnit"/>.</param>
    /// <param name="rhs">The RHS <see cref="IUnit"/>.</param>
    /// <returns>
    ///     <c>true</c>, if the base unit are the equal.
    /// </returns>
    public static bool AreBaseUnitsEqual(IUnit lhs, IUnit rhs)
    {
        return lhs.BaseUnit.Equals(rhs.BaseUnit);
    }

    /// <summary>
    /// Checks if the LHS and the RHS are equal.
    /// </summary>
    /// <param name="lhs">The LHS <see cref="IUnit"/>.</param>
    /// <param name="rhs">The RHS <see cref="object"/>.</param>
    /// <returns>
    /// A value indication whether the lhs and the rhs are equal.
    /// </returns>
    public static bool AreUnitsEqual(IUnit lhs, object rhs)
    {
        return AreUnitsEqual(lhs, rhs as IUnit);
    }

    /// <summary>
    /// Checks if the lhs and the rhs are equal.
    /// </summary>
    /// <param name="lhs">The LHS <see cref="IUnit"/>.</param>
    /// <param name="rhs">The RHS <see cref="IUnit"/>.</param>
    /// <returns>
    /// A value indication whether the lhs and the rhs are equal.
    /// </returns>
    public static bool AreUnitsEqual(IUnit lhs, IUnit rhs)
    {
        if (rhs == null || lhs == null)
        {
            return false;
        }

        if (!lhs.PrefixFactor.Equals(rhs.PrefixFactor))
        {
            return false;
        }

        if (!IsNotationEqual(lhs, rhs))
        {
            return false;
        }

        return true;
    }

    /// <summary>
    /// Returns a hash code for this instance.
    /// </summary>
    /// <param name="unit">The quantity unit.</param>
    /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
    public static int GetHashCode(IUnit unit)
    {
        return unit.PrefixFactor.GetHashCode() ^ unit.Notation.GetHashCode();
    }

    internal static bool IsNotationEqual(IUnit lhs, IUnit rhs)
    {
        return lhs.GetNotationWithoutPrefix().Equals(rhs.GetNotationWithoutPrefix());
    }
}


text:
package org.apache.hadoop.yarn.service.component;

import com.google.common.base.Preconditions;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.event.AbstractEvent;
import org.apache.hadoop.yarn.service.component.instance.ComponentInstance;

public class ComponentEvent extends AbstractEvent<ComponentEventType> {
  private long desired;
  private final String name;
  private final ComponentEventType type;
  private Container container;
  private ComponentInstance instance;
  private String instanceName;
  private ContainerStatus status;
  private ContainerId containerId;
  private org.apache.hadoop.yarn.service.api.records.Component targetSpec;
  private String upgradeVersion;

  public ContainerId getContainerId() {
    return containerId;
  }

  public ComponentEvent setContainerId(ContainerId containerId) {
    this.containerId = containerId;
    return this;
  }

  public ComponentEvent(String name, ComponentEventType type) {
    super(type);
    this.name = name;
    this.type = type;
  }

  public String getName() {
    return name;
  }

  public ComponentEventType getType() {
    return type;
  }

  public long getDesired() {
    return desired;
  }

  public ComponentEvent setDesired(long desired) {
    this.desired = desired;
    return this;
  }

  public Container getContainer() {
    return container;
  }

  public ComponentEvent setContainer(Container container) {
    this.container = container;
    return this;
  }

  public ComponentInstance getInstance() {
    return instance;
  }

  public ComponentEvent setInstance(ComponentInstance instance) {
    this.instance = instance;
    return this;
  }

  public String getInstanceName() {
    return instanceName;
  }

  public ComponentEvent setInstanceName(String instanceName) {
    this.instanceName = instanceName;
    return this;
  }

  public ContainerStatus getStatus() {
    return status;
  }

  public ComponentEvent setStatus(ContainerStatus status) {
    this.status = status;
    return this;
  }

  public org.apache.hadoop.yarn.service.api.records.Component getTargetSpec() {
    return targetSpec;
  }

  public ComponentEvent setTargetSpec(
      org.apache.hadoop.yarn.service.api.records.Component targetSpec) {
    this.targetSpec = Preconditions.checkNotNull(targetSpec);
    return this;
  }

  public String getUpgradeVersion() {
    return upgradeVersion;
  }

  public ComponentEvent setUpgradeVersion(String upgradeVersion) {
    this.upgradeVersion = upgradeVersion;
    return this;
  }
}


text:
namespace DevLab.JmesPath
{
    public interface IJmesPathGenerator
    {
        bool IsProjection();

        void OnExpression();

        void OnIdentifier(string name);
        void OnLiteralString(string literal);
        void OnRawString(string value);

        void OnAndExpression();
        void OnNotExpression();
        void OnOrExpression();

        void OnComparisonEqual();
        void OnComparisonGreater();
        void OnComparisonGreaterOrEqual();
        void OnComparisonLesser();
        void OnComparisonLesserOrEqual();
        void OnComparisonNotEqual();

        void OnArithmeticUnaryPlus();
        void OnArithmeticUnaryMinus();
        void OnArithmeticAddition();
        void OnArithmeticSubtraction();
        void OnArithmeticMultiplication();
        void OnArithmeticDivision();
        void OnArithmeticModulo();
        void OnArithmeticIntegerDivision();

        void OnCurrentNode();

        void OnSubExpression();

        void OnFilterProjection();
        void OnFlattenProjection();
        void OnHashWildcardProjection();
        void OnListWildcardProjection();

        void OnIndex(int index);
        void OnIndexExpression();
        void OnSliceExpression(int? start, int? stop, int? step);

        void PushMultiSelectHash();
        void AddMultiSelectHashExpression();
        void PopMultiSelectHash();

        void PushMultiSelectList();
        void AddMultiSelectListExpression();
        void PopMultiSelectList();

        void PushFunction();
        void AddFunctionArg();
        void PopFunction(string name);
        void OnExpressionType();

        void OnPipeExpression();
    }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

class Version20120716214711_create_TaskTypeClass extends AbstractMigration {

    private $statements = [
        'mysql' => [
            'up' => [
                "CREATE TABLE TaskTypeClass (
                    id INT AUTO_INCREMENT NOT NULL,
                    name VARCHAR(255) NOT NULL,
                    description LONGTEXT DEFAULT NULL,
                    UNIQUE INDEX UNIQ_F92FE5F25E237E06 (name),
                    PRIMARY KEY(id))
                    DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"
            ],
            'down' => [
                "DROP TABLE TaskTypeClass"
            ]
        ],
        'sqlite' => [
            'up' => [
                "CREATE TABLE TaskTypeClass (
                    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                    name VARCHAR(255) NOT NULL,
                    description LONGTEXT DEFAULT NULL)",
                "CREATE UNIQUE INDEX UNIQ_F92FE5F25E237E06 ON TaskTypeClass (name)"
            ],
            'down' => [
                "DROP TABLE TaskTypeClass"
            ]
        ]
    ];

    public function up(Schema $schema)
    {
        foreach ($this->statements[$this->connection->getDatabasePlatform()->getName()]['up'] as $statement) {
            $this->addSql($statement);
        }
    }

    public function down(Schema $schema)
    {
        foreach ($this->statements[$this->connection->getDatabasePlatform()->getName()]['down'] as $statement) {
            $this->addSql($statement);
        }
    }

}