text:
#import "Bicycle.h"
#import <Foundation/NSString.h>

@implementation Bicycle

- (void)signalStop {
    NSLog(@"Bending left arm downwards");
}
- (void)signalLeftTurn {
    NSLog(@"Extending left arm outwards");
}
- (void)signalRightTurn {
    NSLog(@"Bending left arm upwards");
}
- (void)startPedaling {
    NSLog(@"Here we go!");
}
- (void)removeFrontWheel {
    NSLog(@"Front wheel is off."
          "Should probably replace that before pedaling...");
}
- (void)lockToStructure:(id)theStructure {
    NSLog(@"Locked to structure. Don't forget the combination!");
}

@end

redpajama_set_name: RedPajamaGithub


text:
from collections import OrderedDict
import unittest

import bald

class netcdfVarMin(object):
    def __init__(self, dim_tuple, shape_tuple):
        self.dimensions = dim_tuple
        self.shape = shape_tuple
        if len(self.dimensions) != len(self.shape):
            raise ValueError('dim_tuple and shape_tuple must be tuples'
                             ' of the same length')

class Test(unittest.TestCase):
    #def setup(self)
    def test_same_two(self):
        source_var = netcdfVarMin(('a', 'b'), (3, 5))
        target_var = netcdfVarMin(('a', 'b'), (3, 5))
        expected = OrderedDict((('a', 3), ('b', 5)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()), expected)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()), expected)

    def test_target_subset_last(self):
        source_var = netcdfVarMin(('a', 'b', 'c'), (3, 5, 7))
        target_var = netcdfVarMin(('b', 'c'), (5, 7))
        expected_source = OrderedDict((('a', 3), ('b', 5), ('c', 7)))
        expected_target = OrderedDict((('a', 1), ('b', 5), ('c', 7)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)

    def test_target_subset_first(self):
        source_var = netcdfVarMin(('a', 'b', 'c'), (3, 5, 7))
        target_var = netcdfVarMin(('a', 'b'), (3, 5))
        expected_source = OrderedDict((('a', 3), ('b', 5), ('c', 7)))
        expected_target = OrderedDict((('a', 3), ('b', 5), ('c', 1)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)

    def test_disjoint_misalign(self):
        source_var = netcdfVarMin(('a', 'b', 'c'), (3, 5, 7))
        target_var = netcdfVarMin(('b', 'c', 'd'), (5, 7, 9))
        expected_source = OrderedDict((('a', 3), ('b', 5), ('c', 7), ('d', 1)))
        expected_target = OrderedDict((('a', 1), ('b', 5), ('c', 7), ('d', 9)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)

    def test_disjoint_misalign_invert(self):
        source_var = netcdfVarMin(('b', 'c', 'd'), (5, 7, 9))
        target_var = netcdfVarMin(('a', 'b', 'c'), (3, 5, 7))
        expected_source = OrderedDict((('a', 1), ('b', 5), ('c', 7), ('d', 9)))
        expected_target = OrderedDict((('a', 3), ('b', 5), ('c', 7), ('d', 1)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)

    def test_disjoint_align_interleave(self):
        source_var = netcdfVarMin(('a', 'c', 'd', 'e', 'f'), (3, 7, 9, 11, 13))
        target_var = netcdfVarMin(('a', 'b', 'c', 'f'), (3, 5, 7, 13))
        expected_source = OrderedDict((('a', 3), ('b', 1), ('c', 7), ('d', 9),
                                       ('e', 11), ('f', 13)))
        expected_target = OrderedDict((('a', 3), ('b', 5), ('c', 7), ('d', 1),
                                       ('e', 1), ('f', 13)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)

    def test_disjoint_misalign_interleave(self):
        source_var = netcdfVarMin(('b', 'c', 'd', 'e', 'f'), (5, 7, 9, 11, 13))
        target_var = netcdfVarMin(('a', 'b', 'c', 'f'), (3, 5, 7, 13))
        expected_source = OrderedDict((('a', 1), ('b', 5), ('c', 7), ('d', 9),
                                       ('e', 11), ('f', 13)))
        expected_target = OrderedDict((('a', 3), ('b', 5), ('c', 7), ('d', 1),
                                       ('e', 1), ('f', 13)))
        result = bald.netcdf_shared_dimensions(source_var, target_var)
        with self.subTest():
            self.assertDictEqual(result.get('sourceReshape', dict()),
                                 expected_source)
        with self.subTest():
            self.assertDictEqual(result.get('targetReshape', dict()),
                                 expected_target)


text:
      Search
      <input type="text" class="form-control" placeholder="Find your Champion" aria-describedby="basic-addon1" ng-model="query">

            <champ-info champ="champion"></champ-info>


text:
"""
Copyright (c) 2013, Dave Mankoff
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Dave Mankoff nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAVE MANKOFF BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

from __future__ import unicode_literals
import unittest

import htmlmin
from htmlmin.decorator import htmlmin as htmlmindecorator
from htmlmin.middleware import HTMLMinMiddleware

from . import test_escape

MINIFY_FUNCTION_TEXTS = {
  'simple_text': (
    '  a  b',
    ' a b'
  ),
  'long_text': (
    '''When doing     test-driven development, or
    running automated builds that need testing before they are  deployed
\t\t for downloading or use, it's often useful to be able to run a project's
unit tests without actually deploying the project anywhere.\r\n\r\n\n\r\rThe
test command runs project's unit tests without actually deploying it, by
    temporarily putting the project's source on sys.path, after first running
     build_ext -i to ensure that any C extensions are built.

    ''',
    ("When doing test-driven development, or running automated "
      "builds that need testing before they are deployed for "
      "downloading or use, it's often useful to be able to run a "
      "project's unit tests without actually deploying the project "
      "anywhere. The test command runs project's unit tests without "
      "actually deploying it, by temporarily putting the project's "
      "source on sys.path, after first running build_ext -i to "
      "ensure that any C extensions are built. ")
  ),
  'simple_html': (
    ('    a b  '  #  is not closed
     '
   x
 <textarea>   Y  </textarea> '),
    ('   a b  '
     '
   x
 <textarea>   Y  </textarea> ')
  ),
  'with_doctype': (
    '\n\n<!DOCTYPE html>\n\n   X   Y   ',
    '<!DOCTYPE html>\n X Y '
  ),
}

FEATURES_TEXTS = {
  'remove_quotes': (
    '

  ',
    '

 ',
  ),
  'remove_quotes_keep_quote_trailing_slash_last': (
    '

',
    '

',  # NOTE the single space at the end, inserted to not make this a self-closing tag
  ),
  'remove_single_quotes': (
    '

 ',
    '

 ',
  ),
  'keep_nested_single_quotes': (
    '

 ',
    '

 ',
  ),
  'remove_tag_name_whitespace': (
    '
  <textarea  >   </ textarea  >  ',
    '
 <textarea>   </textarea> '
  ),
  'no_reduce_empty_attributes': (
    '',
    '',
  ),
  'no_reduce_empty_attributes_keep_quotes': (
    '',
    '',
  ),
  'reduce_empty_attributes': (
    '',
    '',
  ),
  'keep_boolean_attributes': (
    '<input id="x" disabled="disabled">',
    '<input id=x disabled=disabled>',
  ),
  'reduce_boolean_attributes': (
    '<input id="x" disabled="disabled">',
    '<input id=x disabled>',
  ),
  'remove_close_tags': (
    '

   x
 ',
    '

   x   ',
  ),
  'remove_comments': (
    ' this text should  have  comments removed',
    ' this text should have comments removed',
  ),
  'keep_comments': (
    ' this text should  have comments removed',
    ' this text should  have comments removed',
  ),
  'keep_conditional_comments': (
    'keep IE conditional styles ',
    'keep IE conditional styles ',
  ),
  'remove_nonconditional_comments': (
    'remove other [if] things ',
    'remove other [if] things ',
  ),
  'keep_optional_attribute_quotes': (
    '',
    '',
  ),
  'keep_pre_attribute': (
    'the pre should stay  ',
    'the pre should stay ',
  ),
  'custom_pre_attribute': (
    'the    X    Y  ',
    'the  X   Y  ',
  ),
  'keep_empty': (
    '
  A

  B
  ',
    '
 A

 B
 ',
  ),
  'remove_empty': (
    ('  \n
  A
\r'
     '
  B
\r\n
 C

D
 '),
    ('
 A
'
     '
 B

 C

D
 '),
  ),
  'remove_all_empty': (
    ('  \n
  A
\r'
     '
  B
\r\n
 C

D
 '),
    ('
 A
'
     '
 B

 C

D
'),
  ),
  'dont_minify_div': (
    '
   X
   ',
    '
   X
 ',
  ),
  'minify_pre': (
    '
   X
   ',
    '
 X
 ',
  ),
  'remove_head_spaces': (
    '  <title>   ☃X  Y  &  Z </title>  ',
    '<title>☃X Y & Z</title>',
  ),
  'dont_minify_scripts_or_styles': (
    '       ',
    '   ',
  ),
  'remove_close_from_tags': (
    (' <area/> <base/>
 <col/><command /><embed />
 '
     '   <input   /> <keygen/> <meta  /><param/><source/><track  /><wbr />'
     '  '),
    (' <area> <base>
 <col><command><embed>
 '
     ' <input> <keygen> <meta><param><source><track><wbr>'
     ' '),
  ),
  'remove_space_from_self_closed_tags': (
    '    <y />   <x    />',
    ' <y/> <x/>',
  ),
}

SELF_CLOSE_TEXTS = {
  'p_self_close': (
    '
  X
  Y  ',
    '
  X
 Y ',
  ),
  'li_self_close': (
    '

  X
  Y
  Z
   Q',
    '

  X
 Y
  Z
 Q',
  ),
  'dt_self_close': (
    '

  X
  Y
  Z

   Q',
    '

  X
 Y
  Z

 Q',
  ),
  'dd_self_close': (
    '

  X
  Y
  Z
   Q',
    '

  X
 Y
  Z
 Q',
  ),
  'optgroup_self_close': (
    ('   <select  a >  <optgroup pre>   <option>   X</option>   '
     '<optgroup>   <option>   Y</option> </optgroup> </select>   '),
    (' <select a> <optgroup>   <option>   X</option>   '
     '<optgroup> <option> Y</option> </optgroup> </select> '),
  ),
  'option_self_close': (
    ('   <select  a >  <option pre  >   X    '
     '<option> Y    </option></select>   '),
    (' <select a> <option>   X    '
     '<option> Y </option></select> '),
  ),
  'colgroup_self_close': (
    '
  <colgroup pre>
',
    '
 <colgroup>
',
  ),
  'tbody_self_close': (
    ('

   X
  \n'
     '\n

   Y
\n\n\n   '),
    ('

   X
  \n'
     '\n

 Y
 '),
  ),
  'thead_self_close': (
    ('

   X
  '
     '

   Y
 '),
    ('

   X
  '
     '

 Y
 '),
  ),
  'tfoot_self_close': (
    ('

   X
  '
     '

   Y
 '),
    ('

   X
  '
     '

 Y
 '),
  ),
  'tr_self_close': (
    ('

   X  	  '
     '
   Y   	 '),
    ('

   X  	  '
     '
 Y 	 '),
  ),
  'td_self_close': (
    '

   X       Y    ',
    '

  X       Y ',
  ),
  'th_self_close': (
    '

   X        Y    ',
    '

  X        Y ',
  ),
  'a_p_interaction': ( # the 'pre' functionality continues after the
    '
  X
   Y',
    '
  X
 Y',
  ),
}

SELF_OPENING_TEXTS = {
  'html_closed_no_open': (
    '  X  ',
    ' X '
  ),
  'head_closed_no_open': (
    '      X  ',
    '  X ' # TODO: we could theoretically kill that leading
                               # space. See HTMLMinParse.handle_endtag
  ),
  'body_closed_no_open': (
    '   X  ',
    ' X '
  ),
  'colgroup_self_open': (
    '
  </colgroup>
',
    '
 </colgroup>
',
  ),
  'tbody_self_open': (
    '

',
    '

',
  ),
  'p_closed_no_open': ( # this isn't valid html, but its worth accounting for
    '
   X

    Y

',
    '
   X

 Y

',
  ),
}

class HTMLMinTestMeta(type):
  def __new__(cls, name, bases, dct):
    def make_test(text):
      def inner_test(self):
        self.assertEqual(self.minify(text[0]), text[1])
      return inner_test

    for k, v in dct.get('__reference_texts__',{}).items():
      if 'test_'+k not in dct:
        dct['test_'+k] = make_test(v)
    return type.__new__(cls, str(name), bases, dct)

class HTMLMinTestCase(
  HTMLMinTestMeta('HTMLMinTestCase', (unittest.TestCase, ), {})):
  def setUp(self):
    self.minify = htmlmin.minify

class TestMinifyFunction(HTMLMinTestCase):
  __reference_texts__ = MINIFY_FUNCTION_TEXTS

  def test_basic_minification_quality(self):
    import codecs
    with codecs.open('htmlmin/tests/large_test.html', encoding='utf-8') as inpf:
      inp = inpf.read()
    out = self.minify(inp)
    self.assertEqual(len(inp) - len(out), 9579)

  def test_high_minification_quality(self):
    import codecs
    with codecs.open('htmlmin/tests/large_test.html', encoding='utf-8') as inpf:
      inp = inpf.read()
    out = self.minify(inp, remove_all_empty_space=True, remove_comments=True)
    self.assertEqual(len(inp) - len(out), 12693)

class TestMinifierObject(HTMLMinTestCase):
  __reference_texts__ = MINIFY_FUNCTION_TEXTS

  def setUp(self):
    HTMLMinTestCase.setUp(self)
    self.minifier = htmlmin.Minifier()
    self.minify = self.minifier.minify

  def test_reuse(self):
    text = self.__reference_texts__['simple_text']
    self.assertEqual(self.minify(text[0]), text[1])
    self.assertEqual(self.minify(text[0]), text[1])

  def test_buffered_input(self):
    text = self.__reference_texts__['long_text']
    self.minifier.input(text[0][:len(text[0]) // 2])
    self.minifier.input(text[0][len(text[0]) // 2:])
    self.assertEqual(self.minifier.finalize(), text[1])

class TestMinifyFeatures(HTMLMinTestCase):
  __reference_texts__ = FEATURES_TEXTS

  def test_remove_comments(self):
    text = self.__reference_texts__['remove_comments']
    self.assertEqual(htmlmin.minify(text[0], remove_comments=True), text[1])

  def test_no_reduce_empty_attributes(self):
    text = self.__reference_texts__['no_reduce_empty_attributes']
    self.assertEqual(htmlmin.minify(text[0], reduce_empty_attributes=False), text[1])

  def test_no_reduce_empty_attributes_keep_quotes(self):
    text = self.__reference_texts__['no_reduce_empty_attributes_keep_quotes']
    self.assertEqual(htmlmin.minify(text[0], reduce_empty_attributes=False, remove_optional_attribute_quotes=False), text[1])

  def test_reduce_empty_attributes(self):
    text = self.__reference_texts__['reduce_empty_attributes']
    self.assertEqual(htmlmin.minify(text[0], reduce_empty_attributes=True), text[1])

  def test_reduce_boolean_attributes(self):
    text = self.__reference_texts__['reduce_boolean_attributes']
    self.assertEqual(htmlmin.minify(text[0], reduce_boolean_attributes=True), text[1])

  def test_keep_comments(self):
    text = self.__reference_texts__['keep_comments']
    self.assertEqual(htmlmin.minify(text[0], remove_comments=True), text[1])

  def test_keep_conditional_comments(self):
    text = self.__reference_texts__['keep_conditional_comments']
    self.assertEqual(htmlmin.minify(text[0], remove_comments=True), text[1])

  def test_remove_nonconditional_comments(self):
    text = self.__reference_texts__['remove_nonconditional_comments']
    self.assertEqual(htmlmin.minify(text[0], remove_comments=True), text[1])

  def test_keep_optional_attribute_quotes(self):
    text = self.__reference_texts__['keep_optional_attribute_quotes']
    self.assertEqual(htmlmin.minify(text[0], remove_optional_attribute_quotes=False), text[1])

  def test_keep_pre_attribute(self):
    text = self.__reference_texts__['keep_pre_attribute']
    self.assertEqual(htmlmin.minify(text[0], keep_pre=True), text[1])

  def test_custom_pre_attribute(self):
    text = self.__reference_texts__['custom_pre_attribute']
    self.assertEqual(htmlmin.minify(text[0], pre_attr='custom'), text[1])

  def test_keep_empty(self):
    text = self.__reference_texts__['keep_empty']
    self.assertEqual(htmlmin.minify(text[0]), text[1])

  def test_remove_empty(self):
    text = self.__reference_texts__['remove_empty']
    self.assertEqual(htmlmin.minify(text[0], remove_empty_space=True), text[1])

  def test_remove_all_empty(self):
    text = self.__reference_texts__['remove_all_empty']
    self.assertEqual(htmlmin.minify(text[0], remove_all_empty_space=True),
                     text[1])

  def test_dont_minify_div(self):
    text = self.__reference_texts__['dont_minify_div']
    self.assertEqual(htmlmin.minify(text[0], pre_tags=('div',)), text[1])

  def test_minify_pre(self):
    text = self.__reference_texts__['minify_pre']
    self.assertEqual(htmlmin.minify(text[0], pre_tags=('div',)), text[1])

  def test_remove_head_spaces(self):
    text = self.__reference_texts__['remove_head_spaces']
    self.assertEqual(htmlmin.minify(text[0]), text[1])

  def test_dont_minify_scripts_or_styles(self):
    text = self.__reference_texts__['dont_minify_scripts_or_styles']
    self.assertEqual(htmlmin.minify(text[0], pre_tags=[]), text[1])

class TestSelfClosingTags(HTMLMinTestCase):
  __reference_texts__ = SELF_CLOSE_TEXTS

class TestSelfOpeningTags(HTMLMinTestCase):
  __reference_texts__ = SELF_OPENING_TEXTS

class TestDecorator(HTMLMinTestCase):
  def test_direct_decorator(self):
    @htmlmindecorator
    def directly_decorated():
      return '   X   Y   '

    self.assertEqual(' X Y ', directly_decorated())

  def test_options_decorator(self):
    @htmlmindecorator(remove_comments=True)
    def directly_decorated():
      return '   X   Y   '

    self.assertEqual(' X Y ', directly_decorated())

class TestMiddleware(HTMLMinTestCase):
  def setUp(self):
    HTMLMinTestCase.setUp(self)
    def wsgi_app(environ, start_response):
      start_response(environ['status'], environ['headers'])
      yield environ['content']

    self.wsgi_app = wsgi_app

  def call_app(self, app, status, headers, content):
    response_status = []  # these need to be mutable so that they can be changed
    response_headers = [] # within our inner function.
    def start_response(status, headers, exc_info=None):
      response_status.append(status)
      response_headers.append(headers)
    response_body = ''.join(app({'status': status,
                                 'content': content,
                                 'headers': headers},
                                start_response))
    return response_status[0], response_headers[0], response_body

  def test_middlware(self):
    app = HTMLMinMiddleware(self.wsgi_app)
    status, headers, body = self.call_app(
      app, '200 OK', (('Content-Type', 'text/html'),),
      '    X    Y   ')
    self.assertEqual(body, ' X Y ')

  def test_middlware_minifier_options(self):
    app = HTMLMinMiddleware(self.wsgi_app, remove_comments=True)
    status, headers, body = self.call_app(
      app, '200 OK', (('Content-Type', 'text/html'),),
      '    X    Y   ')
    self.assertEqual(body, ' X Y ')

  def test_middlware_off_by_default(self):
    app = HTMLMinMiddleware(self.wsgi_app, by_default=False)
    status, headers, body = self.call_app(
      app, '200 OK', (('Content-Type', 'text/html'),),
      '    X    Y   ')
    self.assertEqual(body, '    X    Y   ')

  def test_middlware_on_by_header(self):
    app = HTMLMinMiddleware(self.wsgi_app, by_default=False)
    status, headers, body = self.call_app(
      app, '200 OK', (
        ('Content-Type', 'text/html'),
        ('X-HTML-Min-Enable', 'True'),
        ),
      '    X    Y   ')
    self.assertEqual(body, ' X Y ')

  def test_middlware_off_by_header(self):
    app = HTMLMinMiddleware(self.wsgi_app)
    status, headers, body = self.call_app(
      app, '200 OK', (
        ('Content-Type', 'text/html'),
        ('X-HTML-Min-Enable', 'False'),
        ),
      '    X    Y   ')
    self.assertEqual(body, '    X    Y   ')

  def test_middlware_remove_header(self):
    app = HTMLMinMiddleware(self.wsgi_app)
    status, headers, body = self.call_app(
      app, '200 OK', (
        ('Content-Type', 'text/html'),
        ('X-HTML-Min-Enable', 'False'),
        ),
      '    X    Y   ')
    self.assertFalse(any((h == 'X-HTML-Min-Enable' for h, v in headers)))

  def test_middlware_keep_header(self):
    app = HTMLMinMiddleware(self.wsgi_app, keep_header=True)
    status, headers, body = self.call_app(
      app, '200 OK', [
        ('Content-Type', 'text/html'),
        ('X-HTML-Min-Enable', 'False'),
        ],
      '    X    Y   ')
    self.assertTrue(any((h == 'X-HTML-Min-Enable' for h, v in headers)))

def suite():
    minify_function_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestMinifyFunction)
    minifier_object_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestMinifierObject)
    minify_features_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestMinifyFeatures)
    self_closing_tags_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestSelfClosingTags)
    self_opening_tags_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestSelfOpeningTags)
    decorator_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestDecorator)
    middleware_suite = unittest.TestLoader().\
        loadTestsFromTestCase(TestMiddleware)
    return unittest.TestSuite([
        minify_function_suite,
        minifier_object_suite,
        minify_features_suite,
        self_closing_tags_suite,
        self_opening_tags_suite,
        decorator_suite,
        middleware_suite,
        test_escape.suite(),
        ])

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


text:
/* tslint:disable max-line-length */
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';
import { HttpHeaders, HttpResponse } from '@angular/common/http';

import { BlockchainTestModule } from '../../../test.module';
import { ResourceBlockChainInfoComponent } from '../../../../../../main/webapp/app/entities/resource/resource-block-chain-info.component';
import { ResourceBlockChainInfoService } from '../../../../../../main/webapp/app/entities/resource/resource-block-chain-info.service';
import { ResourceBlockChainInfo } from '../../../../../../main/webapp/app/entities/resource/resource-block-chain-info.model';

describe('Component Tests', () => {

    describe('ResourceBlockChainInfo Management Component', () => {
        let comp: ResourceBlockChainInfoComponent;
        let fixture: ComponentFixture<ResourceBlockChainInfoComponent>;
        let service: ResourceBlockChainInfoService;

        beforeEach(async(() => {
            TestBed.configureTestingModule({
                imports: [BlockchainTestModule],
                declarations: [ResourceBlockChainInfoComponent],
                providers: [
                    ResourceBlockChainInfoService
                ]
            })
            .overrideTemplate(ResourceBlockChainInfoComponent, '')
            .compileComponents();
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(ResourceBlockChainInfoComponent);
            comp = fixture.componentInstance;
            service = fixture.debugElement.injector.get(ResourceBlockChainInfoService);
        });

        describe('OnInit', () => {
            it('Should call load all on init', () => {
                // GIVEN
                const headers = new HttpHeaders().append('link', 'link;link');
                spyOn(service, 'query').and.returnValue(Observable.of(new HttpResponse({
                    body: [new ResourceBlockChainInfo(123)],
                    headers
                })));

                // WHEN
                comp.ngOnInit();

                // THEN
                expect(service.query).toHaveBeenCalled();
                expect(comp.resources[0]).toEqual(jasmine.objectContaining({id: 123}));
            });
        });
    });

});


text:
<!doctype html>

<meta charset="utf-8">
<title>Journal &#35 8 – Jeremy Smith</title>
<meta name="description" content="">
<meta name="keywords" content="">

<meta property="og:locale" content="en_US">
<meta property="og:title" content="Journal &#35 8 – Jeremy Smith">
<meta property="og:description" content="Today has been an incredibly successful and productive day. Act One is complete. At least for now. It runs around 10 ...">
<meta property="og:url" content="http://localhost:4000/the-azule-journals/journal-8">
<meta property="og:site_name" content="Jeremy Smith">

<meta property="og:image" content="journal-8-feature.png">

<link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Jeremy Smith Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Crimson+Text:400,400italic,700,700italic" rel='stylesheet' type='text/css' />
<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://localhost:4000/assets/css/entypo.css" media="all">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="http://localhost:4000/assets/css/i.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://localhost:4000/images/jeremy-header-image.png">

        <hgroup>

Jeremy Smith

        </hgroup>
        ☰

              Writings

Biography

Works

Reach Out

          <hgroup>

Journal &#35 8

Jun 12, 2016

          </hgroup>

Today has been an incredibly successful and productive day. Act One is complete. At least for now. It runs around 10 minutes long. I will begin on Act Two tomorrow. It is a little shorter, and I am hoping to have it done in around 3 days. That will give me a little over a week to finish the third and final act and revise the entire product.

After finishing I ran into town to send out some band arrangements and sound files (and to grab another burger. They are starting to recognize me at the restaurant). I had driven all the way down into Hot Springs… and then I noticed I had forgotten my wallet. I have driven up and down the mountain twice today, and although I still go well under the speed limit I am really starting to get used to that drive.

The new person arrived while I was in town. After I got back we spent around an hour or so exploring the house and talking. It is nice to have someone my age around. Tomorrow we are going to section hike some of the Appalachian Trail, and later this week we are going to make the trek to Asheville. I had hoped I was going to be able to make it to Asheville while I was here. I have never been, but everyone has always told me I would love it there.

Today marks a full week since my arrival at Azule. I have loved every second. Only 12 days left. I am not looking forward to that last trip down the mountain, but I don't have to think about that just yet.

              « Journal &#35 7

              Journal &#35 9 »

Read The Azule Journals

              Journal &#35 1
              Jun 05, 2016

Reach Out

Contact Me

©2017 Jeremy Smith. Website design by Dillon Wastrack


text:
import importlib
import glob
import json
import os
import re
import copy
import itertools
import time
import inspect
import codecs
from shutil import copyfile
from jinja2 import Environment, StrictUndefined, FileSystemLoader
from distutils.version import StrictVersion
from datetime import datetime
import tempfile
import textwrap

from spec import Type, Availability, Constant, Parameter, Method, Define, Class

# Generate global dictionaries and sets of everything with their methods and definitions
# only once per process execution for efficiency

_core_files = []
_desk_files = []
_ps_files = []
_uxo_files = []

_core_files = glob.glob(os.path.join(os.path.dirname(__file__), '../spec/core/*.py'))
_desk_files = glob.glob(os.path.join(os.path.dirname(__file__), '../spec/desk/*.py'))
_ps_files = glob.glob(os.path.join(os.path.dirname(__file__), '../spec/ps/*.py'))
_uxo_files = glob.glob(os.path.join(os.path.dirname(__file__), '../spec/uxo/*.py'))

with open(os.path.join(os.path.dirname(__file__), '../version.json')) as fp:
    _version = json.load(fp)

_classes = {}
_class_method_groups = {}
_class_defines = {}
_class_verbatim_defines = {}
_branches = set()
_branches_default = {'core', 'desk'}

for file in itertools.chain(_core_files, _desk_files, _ps_files, _uxo_files):
    parts = file.replace('/', '.').replace('\\', '.').split('.')
    parts.pop()
    gx_cl = parts.pop()
    branch = parts.pop()
    mod = importlib.import_module('spec.{}.{}'.format(branch, gx_cl), __package__)

    _classes[gx_cl] = mod.gx_class
    _classes[gx_cl].branch = branch

    defines = mod.gx_defines if hasattr(mod, 'gx_defines') else []
    _class_defines[gx_cl] = defines

    # verbatim_defines is only used in PS(class ANGLO,CSLIB,DIMPLOT) and UXO(class USACE)
    verbatim_defines = mod.gx_verbatim_defines if hasattr(mod, 'gx_verbatim_defines') else ''
    if verbatim_defines:
        _class_verbatim_defines[gx_cl] = verbatim_defines

    groups = mod.gx_methods if hasattr(mod, 'gx_methods') else {}

    _class_method_groups[gx_cl] = groups
    _branches.add(branch)

def do_comment(s, prefix='// ', comment_first_line=False, extra_spaces=0):
    if extra_spaces > 0:
        prefix += u' ' * extra_spaces
    rv = (u'\n' + prefix).join(s.splitlines())
    if comment_first_line:
        rv = prefix + rv
    return rv

def _opt_derive(instance, derive_type):
    return derive_type(instance) if derive_type else copy.deepcopy(instance)

class CodeGeneratorBase:
    # This class provide a set of dicts from an API spec that is perfectly suited for
    # code generation. The circular references from children to parents are intentional
    # and allows resolution of any pertinent information where only the child object is
    # available.
    def _doc_sanitize_def(self, match):
        return r'<define>{}</define>'.format(match)

    def doc_sanitize(self, s):
        s = self.re_class.sub(r'\1', s)
        s = self.re_def.sub(lambda m: self._doc_sanitize_def(m.group(1)), s)
        s = self.re_func.sub(r'\1', s)
        s = self.re_const.sub(lambda m: self._doc_sanitize_def(m.group(1)), s)
        s = textwrap.dedent(s).strip()
        return s.replace('``', '')

    def _parse_references(self, branch_ref, namespace_ref):
        if (branch_ref == ""):
            return {}
        else:
            references = {}
            branch_list = branch_ref.split(';')
            namespace_list = namespace_ref.split(';')
            for i, branch in enumerate(branch_list):
                if i < len(namespace_list):
                    references[branch] = namespace_list[i]
                else:
                    references[branch] = ""
            return references

    def __init__(self, *, constant_type=None, define_type=None, parameter_type=None,
                 method_type=None, class_type=None, no_obsolete=True, template_dirs = [],
                 branch_in="", branch_ref="", namespace_in="", namespace_ref="",
                 line_statement_prefix='###'):

        self.current_version = StrictVersion("{}{}".format(_version['version'], _version['pre-release']))
        self.classes = {}
        self.branches = set()
        self.classes_in = {}
        self.classes_ref = {}
        self.methods = {}
        self.constants = {}
        self.constants_namespace_ref = {}
        self.definitions = {}
        self.handlenames = {}
        self.generation_time = datetime.now()

        loader = FileSystemLoader(template_dirs) if len(template_dirs) else None
        self.j2env = Environment(loader=loader, line_statement_prefix=line_statement_prefix)
        self.j2env.filters['comment'] = do_comment
        self.j2env.filters['doc_sanitize'] = self.doc_sanitize
        self.j2env.undefined = StrictUndefined

        # Some regular expressions to sanitize documentation
        self.re_class = re.compile(':class:`(.*?)`')
        self.re_def = re.compile(':def:`(.*?)`')
        self.re_func = re.compile(':func:`(.*?)`')
        self.re_const = re.compile(':const:`(.*?)`')

        # Load classes from all branches if not specified by user
        references = self._parse_references(branch_ref, namespace_ref)
        if branch_in:
            self.branches.add(branch_in)
        if references:
            self.branches.update(references.keys())
        if not self.branches:
            self.branches = _branches_default

        class_to_load = {c_name:c for c_name,c in _classes.items() if c.branch in self.branches}
        for c_name, c in class_to_load.items():
            cl = _opt_derive(c, class_type)
            cl.generator = self
            cl.defines = {}
            cl.method_groups = {}

            # handlenames
            if cl.handle_name is not None:
                self.handlenames[cl.handle_name] = c_name

            # verbatim_defines
            if c_name in _class_verbatim_defines:
                cl.verbatim_defines = _class_verbatim_defines[c_name]

            # definitions
            for d in _class_defines[c_name]:
                define = _opt_derive(d, define_type)
                define.parent = cl
                define.generator = self

                # constants within definition
                gen_constants = []
                for const in define.constants:
                    gen_const = _opt_derive(const, constant_type)
                    gen_const.parent = define
                    gen_const.generator = self
                    gen_constants.append(gen_const)
                    self.constants[gen_const.name] = gen_const
                    if cl.branch in references:
                        self.constants_namespace_ref[gen_const.name] = references[cl.branch]
                define.constants = gen_constants
                define.validate()
                cl.defines[d.name] = define
                self.definitions[d.name] = define

            cl.is_static = True
            cl.has_methods = False
            default_destr_name = 'Destroy_{}'.format(cl.name)
            default_destrex_name = 'DestroyEx_{}'.format(cl.name)

            # method groups
            for g_k, g in _class_method_groups[c_name].items():
                # methods within each group
                methods = []
                for m in g:
                    if not no_obsolete or not m.is_obsolete:
                        method = _opt_derive(m, method_type)
                        method.parent = cl
                        method.generator = self

                        # parameters within method
                        parameters = []
                        for p in m.parameters:
                            parameter = _opt_derive(p, parameter_type)
                            parameter.parent = method
                            parameter.generator = self
                            parameters.append(parameter)
                        method.parameters = parameters
                        method.add_extra_properties(cl)
                        if not method.is_static:
                            cl.is_static = False

                        method.is_destroy_method = method.name == default_destr_name or method.name == default_destrex_name

                        if cl.name == 'BF':
                            # We only use the DestroyEx in BF
                            if method.name == default_destrex_name:
                                cl.default_destroy_method = default_destrex_name
                        elif method.name == default_destr_name:
                            if method.is_app:
                                cl.default_destroy_method = 'App_{}'.format(default_destr_name)
                            else:
                                cl.default_destroy_method = default_destr_name

                        cl.has_methods = True
                        methods.append(method)
                        cl.methods[method.name] = method
                        self.methods[method.name] = method
                if len(methods) > 0:
                    cl.method_groups[g_k] = methods
            cl.validate()
            self.classes[c_name] = cl
            if cl.branch == branch_in:
                self.classes_in[c_name] = cl
            if cl.branch in references:
                self.classes_ref[c_name] = cl

    def is_class(self, type):
        return type in self.classes or type in self.handlenames

    def get_class(self, type):
        if type in self.classes:
            return self.classes[type]
        elif type in self.handlenames:
            return self.handlenames[type]
        else:
            return None

    def resolve_enum_type_from_description(self, type, description):
        if description and (type == Type.INT32_T or type == Type.BOOL):
            defines = re.findall("<define>(.+?)</define>", description)
            if len(defines) == 1:
                if not defines[0] in self.definitions:
                    raise Exception('Unknown definition indicated for parameter or return value: ' + defines[0])
                return defines[0]
        return type

    def parse_template(self, source, globals=None, template_class=None):
        return self.j2env.from_string(source, globals=globals, template_class=template_class)

    def get_template(self, name, parent=None, globals=None):
        return self.j2env.get_template(name, parent=parent, globals=globals)

    def get_description(self, content):
        if content:
            return self.parse_template("{{ doc | doc_sanitize }}").render(doc=content)
        else:
            return ''

    def normalize_line_endings(self, contents):
        return contents.replace('\r\n', '~~---NL~~---').replace('\n', '~~---NL~~---').replace('~~---NL~~---', '\n')

    def refresh_file_contents(self, file_name, contents):
        cur_contents = None
        if os.path.exists(file_name):
            with open(file_name, 'r', newline='', encoding='utf8') as f:
                cur_contents = self.normalize_line_endings(f.read())
        if contents != cur_contents:
            if not 'templates/' in file_name:
                print('Updating {}'.format(file_name))
            with open(file_name, 'w', encoding='utf8') as f:
                f.write(self.normalize_line_endings(contents))

    def regen_with_template(self, output_dir, file_name, **kwargs):
        out_file = os.path.join(output_dir, file_name)
        template = self.get_template(file_name)
        self.refresh_file_contents(out_file, template.render(**kwargs))

    _prevent_delete_set = {
        'ALL',
        'PREDEF_ALL',
        'PRECOMP_ALL',
        'VERSION',
        '__INIT__'
        }
    def delete_gen_files_with_no_class(self, output_dir, extension):
        existing_files = glob.glob(os.path.join(output_dir, '*.{}'.format(extension)))
        for file in existing_files:
            file_part = os.path.split(file)[1].split('.')[0].upper();
            if file_part not in _classes and file_part not in self._prevent_delete_set:
                print('Deleting {}'.format(file))
                os.remove(file)

    def regen_with_editable_blocks(self, template_gen_dir, template_prefix, extension, input_file, output_file, **kwargs):
        empty_template = '{}/{}_empty.{}'.format(template_gen_dir, template_prefix, extension)
        empty_template_path = os.path.join(os.path.dirname(__file__), '..', empty_template)
        cur_gen_template = '{}/{}_cur.gen.{}'.format(template_gen_dir, template_prefix, extension)
        cur_gen_template_path = os.path.join(os.path.dirname(__file__), '..', cur_gen_template)
        generated_template_name = '{}_generated.{}'.format(template_prefix, extension)
        generated_gen_template = '{}/{}_generated.gen.{}'.format(template_gen_dir, template_prefix, extension)
        generated_gen_template_path = os.path.join(os.path.dirname(__file__), '..', generated_gen_template)
        if not os.path.exists(input_file):
            copyfile(empty_template_path, cur_gen_template_path)
        else:
            copyfile(input_file, cur_gen_template_path)

        # Ensure file time change to ensure jinja reloads it even if the previous source had exactly the same modified
        # time. This occasionally happens on fast systems with git checkouts where sources are not generated in-place
        time.sleep(0.001)
        os.utime(cur_gen_template_path, None)

        gen_template = self.get_template(generated_template_name)
        self.refresh_file_contents(generated_gen_template_path, gen_template.render(**kwargs))

        final_template = self.get_template(os.path.split(generated_gen_template)[1])
        self.refresh_file_contents(output_file, final_template.render(**kwargs))


text:
<!DOCTYPE html>

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

  <title>Shoe Tying 101 | Mommy Knows Best</title>
  <meta name="author" content="Jennifer Elam">
  <meta name="description" content="Jennifer Elam's online blog about being a mother, her observations of daily life, and her interactions with the products that are supposed to make it all better.">
  <meta property="og:title" content="Shoe Tying 101 | Mommy Knows Best">
  <meta property="og:url" content="http://www.mommyknowsbest.co/2016/02/20/shoe-tying-101/">
  <meta property="og:site_name" content="Mommy Knows Best">
  <meta property="og:description" content="Jennifer Elam's online blog about being a mother, her observations of daily life, and her interactions with the products that are supposed to make it all better.">
  <meta property="og:image" content="https://jaythanelam.github.io/mommy-knows-best/assets/images/tying-shoes.jpg">
  <meta property="og:type" content="blog">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:description" content="Jennifer Elam's online blog about being a mother, her observations of daily life, and her interactions with the products that are supposed to make it all better.">
  <meta name="twitter:title" content="Shoe Tying 101 | Mommy Knows Best">
  <meta name="twitter:url" content="http://www.mommyknowsbest.co/2016/02/20/shoe-tying-101/">
  <meta name="twitter:site" content="Mommy Knows Best">
  <meta name="twitter:creator" content="@">
  <meta name="twitter:domain" content="http://www.mommyknowsbest.co">
  <meta property="twitter:image" content="https://jaythanelam.github.io/mommy-knows-best/assets/images/tying-shoes.jpg">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata|Lora|Space+Mono:700">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css">
  <link rel="stylesheet" href="/assets/css/main.css">

  <link rel="alternate" type="application/rss+xml" title="Mommy Knows Best" href="http://www.mommyknowsbest.co/feed.xml">
  <link rel="canonical" href="http://www.mommyknowsbest.co/2016/02/20/shoe-tying-101/">

      Back to Posts

      <time datetime="2016-02-20T00:00:00-05:00" itemprop="datePublished">Feb 20, 2016</time>

Shoe Tying 101

          Posted in Family, Teaching Tools

Resources and opportunity mamas! That is really what it comes down to when you have kiddos. Let's be honest, it's hard to find great teaching tools, a fun environment and not gasp at the sticker shock… That's why I had to share this shoe tying class offered by Nordstrom (yep the fancy store that gives away balloons!) They offer a class once a month for kiddos to learn to bunny year with the best of 'em. Not only did we learn to tie (something I've been trying to teach my 7 year old for MONTHS!) but we walked away with a little "I DID IT!" certificate, a goody bag packed with cute kiddo yummies and a discount on kids shoes! all completely free! It was fantastic! WE skipped out of there with HUGE smiles - Me not believing how great it all turned out and Ima with a renewed confidence, sucking a lollipop and holding her balloon wearing her just laced sneakers!

Definitely gets the mommyknowsbest seal of approval!

Happy Weekend!
Jen@mommyknowsbest.co

My online blog about being a mother, my observations of daily life, and my interactions with the products that are supposed to make it all better.

        Read Next

I'm gellin'


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

namespace PingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new PingClient(!args.Contains("-nowait"));
            client.Init().Wait();

            Console.ReadLine();

            client.Stop().Wait();
        }
    }
}


text:
cask 'macvim-kaoriya' do
  if MacOS.version <= :lion
    version '7.4:20130911'
    sha256 'd9fc6e38de1852e4ef79e9ea78afa60e606bf45066cff031e349d65748cbfbce'
  else
    version '8.0:20170125'
    sha256 'd220d1f386e2221fa1d2c55d8e9edb204d5c72e7536f01568a50a3b6d423718b'
  end

  url "https://github.com/splhack/macvim-kaoriya/releases/download/#{version.after_colon}/MacVim-KaoriYa-#{version.after_colon}.dmg"
  appcast 'https://github.com/splhack/macvim-kaoriya/releases.atom',
          checkpoint: '62b952d4c12beaa1596e0f326090efd764db9022efc7e82a2e9295a3adfc30c7'
  name 'MacVim KaoriYa'
  homepage 'https://github.com/splhack/macvim-kaoriya'

  depends_on macos: '>= :lion'

  app 'MacVim.app'

  mvim = "#{appdir}/MacVim.app/Contents/MacOS/mvim"
  executables = %w[macvim-askpass mvim mvimdiff mview mvimex gvim gvimdiff gview gvimex]
  executables += %w[vi vim vimdiff view vimex] if ARGV.include? '--override-system-vim'
  executables.each { |e| binary mvim, target: e }

  postflight do
    system 'ruby',
           '-i.bak',
           '-pe',
           %q[sub %r[`dirname "\$0"`(?=(?:/\.\.){3})], '$(cd $(dirname $(readlink $0 || echo $0));pwd)'],
           staged_path.join(mvim)
  end

  zap delete: [
                '~/Library/Preferences/org.vim.MacVim.LSSharedFileList.plist',
                '~/Library/Preferences/org.vim.MacVim.plist',
              ]

  caveats do
    files_in_usr_local
    <<-EOS.undent
      Note that homebrew also provides a compiled macvim Formula that links its
      binary to /usr/local/bin/mvim. And the Cask MacVim also does. It's not
      recommended to install both the Cask MacVim KaoriYa and the Cask MacVim
      and the Formula of MacVim.

      This cask installs symlinks in /usr/local/bin that target to the binary
      MacVim.app/Contents/MacOS/mvim. Below is the list.
        macvim-askpass / mvim / mvimdiff / mview / mvimex /
        gvim / gvimdiff / gview / gvimex

      With --override-system-vim option, you can have more symlinks to use
      macvim-kaoriya instead of the system vim.
        vi / vim / vimdiff / view / vimex
    EOS
  end
end


text:
enum {
    kTagLabel1,
    kTagLabel2,
    kTagLabel3,
    kTagLabel4,

    kTagColor1,
    kTagColor2,
    kTagColor3,
};

static int fontIdx = 0;

static std::string fontList[] =
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    // custom ttf files are defined in Test-info.plist
    "American Typewriter",
    "Marker Felt",
    "A Damn Mess",
    "Abberancy",
    "Abduction",
    "Paint Boy",
    "Schwarzwald Regular",
    "Scissor Cuts",
#else
    "fonts/A Damn Mess.ttf",
    "fonts/Abberancy.ttf",
    "fonts/Abduction.ttf",
    "fonts/Paint Boy.ttf",
    "fonts/Schwarzwald Regular.ttf",
    "fonts/Scissor Cuts.ttf",
#endif
};

static int fontCount = sizeof(fontList) / sizeof(*fontList);

static int vAlignIdx = 0;
static CCVerticalTextAlignment verticalAlignment[] =
{
    kCCVerticalTextAlignmentTop,
    kCCVerticalTextAlignmentCenter,
    kCCVerticalTextAlignmentBottom,
};
static int vAlignCount = sizeof(verticalAlignment) / sizeof(*verticalAlignment);

static const char* nextAction(void)
{
    fontIdx++;
    if(fontIdx >= fontCount) {
        fontIdx = 0;
        vAlignIdx = (vAlignIdx + 1) % vAlignCount;
    }
    return fontList[fontIdx].c_str();
}

static const char* backAction(void)
{
    fontIdx--;
    if( fontIdx < 0 ) {
        fontIdx = fontCount - 1;
        vAlignIdx--;
        if(vAlignIdx < 0)
            vAlignIdx = vAlignCount - 1;
    }

    return fontList[fontIdx].c_str();
}

static const char* restartAction(void)
{
    return fontList[fontIdx].c_str();
}

FontTest::FontTest()
{
    CCMenuItemImage *item1 = CCMenuItemImage::create(s_pPathB1, s_pPathB2, this, menu_selector(FontTest::backCallback));
    CCMenuItemImage *item2 = CCMenuItemImage::create(s_pPathR1, s_pPathR2, this, menu_selector(FontTest::restartCallback));
    CCMenuItemImage *item3 = CCMenuItemImage::create(s_pPathF1, s_pPathF2, this, menu_selector(FontTest::nextCallback));

    CCMenu *menu = CCMenu::create(item1, item2, item3, NULL);
    menu->setPosition(CCPointZero);
    item1->setPosition(ccp(VisibleRect::center().x - item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));
    item2->setPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y+item2->getContentSize().height/2));
    item3->setPosition(ccp(VisibleRect::center().x + item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));
    addChild(menu, 1);

    showFont(restartAction());
}

void FontTest::showFont(const char *pFont)
{
    CCSize s = CCDirector::sharedDirector()->getWinSize();

    CCSize blockSize = CCSizeMake(s.width/3, 200);
    float fontSize = 26;

    removeChildByTag(kTagLabel1, true);
    removeChildByTag(kTagLabel2, true);
    removeChildByTag(kTagLabel3, true);
    removeChildByTag(kTagLabel4, true);
    removeChildByTag(kTagColor1, true);
    removeChildByTag(kTagColor2, true);
    removeChildByTag(kTagColor3, true);

    CCLabelTTF *top = CCLabelTTF::create(pFont, pFont, 24);
    CCLabelTTF *left = CCLabelTTF::create("alignment left", pFont, fontSize,
                                          blockSize, kCCTextAlignmentLeft, verticalAlignment[vAlignIdx]);
    CCLabelTTF *center = CCLabelTTF::create("alignment center", pFont, fontSize,
                                            blockSize, kCCTextAlignmentCenter, verticalAlignment[vAlignIdx]);
    CCLabelTTF *right = CCLabelTTF::create("alignment right", pFont, fontSize,
                                           blockSize, kCCTextAlignmentRight, verticalAlignment[vAlignIdx]);

    CCLayerColor *leftColor = CCLayerColor::create(ccc4(100, 100, 100, 255), blockSize.width, blockSize.height);
    CCLayerColor *centerColor = CCLayerColor::create(ccc4(200, 100, 100, 255), blockSize.width, blockSize.height);
    CCLayerColor *rightColor = CCLayerColor::create(ccc4(100, 100, 200, 255), blockSize.width, blockSize.height);

    leftColor->ignoreAnchorPointForPosition(false);
    centerColor->ignoreAnchorPointForPosition(false);
    rightColor->ignoreAnchorPointForPosition(false);

    top->setAnchorPoint(ccp(0.5, 1));
    left->setAnchorPoint(ccp(0,0.5));
    leftColor->setAnchorPoint(ccp(0,0.5));
    center->setAnchorPoint(ccp(0,0.5));
    centerColor->setAnchorPoint(ccp(0,0.5));
    right->setAnchorPoint(ccp(0,0.5));
    rightColor->setAnchorPoint(ccp(0,0.5));

    top->setPosition(ccp(s.width/2,s.height-20));
    left->setPosition(ccp(0,s.height/2));
    leftColor->setPosition(left->getPosition());
    center->setPosition(ccp(blockSize.width, s.height/2));
    centerColor->setPosition(center->getPosition());
    right->setPosition(ccp(blockSize.width*2, s.height/2));
    rightColor->setPosition(right->getPosition());

    this->addChild(leftColor, -1, kTagColor1);
    this->addChild(left, 0, kTagLabel1);
    this->addChild(rightColor, -1, kTagColor2);
    this->addChild(right, 0, kTagLabel2);
    this->addChild(centerColor, -1, kTagColor3);
    this->addChild(center, 0, kTagLabel3);
    this->addChild(top, 0, kTagLabel4);
}

void FontTest::backCallback(CCObject* pSender)
{
    showFont(backAction());
}

void FontTest::nextCallback(CCObject* pSender)
{
    showFont(nextAction());
}

std::string FontTest::title()
{
    return "Font test";
}

void FontTest::restartCallback(CCObject* pSender)
{
    showFont(restartAction());
}

///---------------------------------------
//
// DirectorTestScene
//
///---------------------------------------
void FontTestScene::runThisTest()
{
    CCLayer* pLayer = FontTest::create();
    addChild(pLayer);

    CCDirector::sharedDirector()->replaceScene(this);
}


text:
get_latest_release() {
	curl --silent "https://api.github.com/repos/$1/releases/latest" | grep -Po '"tag_name": "\K.*?(?=")'
}

wget https://raw.githubusercontent.com/AquaQAnalytics/TorQ/master/installtorqapp.sh

torq_latest=`get_latest_release "AquaQAnalytics/TorQ"`

if [[  $torq_latest == *?.?.? ]] || [[  $torq_latest == *?.??.?? ]] || [[  $torq_latest == *?.?.?? ]] || [[  $torq_latest == *?.??.? ]];
then
        echo "============================================================="
	echo "Latest TorQ release"
	echo $torq_latest
	echo "Getting the latest TorQ .tar.gz file"
	echo "============================================================="

else
	echo "the tag for Torq release: "
        echo $torq_latest
        echo "Is not in the right format, exiting script."
	exit 1
fi

wget --content-disposition https://github.com/AquaQAnalytics/TorQ/archive/$torq_latest.tar.gz

echo $torq_latest

if [ "${torq_latest%%v*}" ]
then
  echo "tag doesn't start with v"
else
  torq_latest=${torq_latest#?}
fi

echo $torq_latest

torq_fsp_latest=`get_latest_release "AquaQAnalytics/TorQ-Finance-Starter-Pack"`

echo "============================================================="
echo "Latest TorQ-FSP release"
echo $torq_fsp_latest
echo "Getting the latest TorQ-FSP .tar.gz file"
echo "============================================================="

if [[  $torq_fsp_latest == *?.?.? ]] || [[  $torq_fsp_latest == *?.??.?? ]] || [[  $torq_fsp_latest == *?.??.? ]] || [[  $torq_fsp_latest == *?.?.?? ]];
then
	echo "============================================================="
	echo "Latest TorQ-FSP release"
	echo $torq_fsp_latest
	echo "Getting the latest TorQ-FSP .tar.gz file"
	echo "============================================================="

else
        echo "the tag for Torq release: "
        echo $torq_fsp_latest
        echo "Is not in the right format, exiting script."
	exit 1
fi

wget --content-disposition https://github.com/AquaQAnalytics/TorQ-Finance-Starter-Pack/archive/$torq_fsp_latest.tar.gz

echo $torq_fsp_latest

if [ "${torq_fsp_latest%%v*}" ]
then
  echo "tag doesn't start with v"
else
  torq_fsp_latest=${torq_fsp_latest#?}
fi

echo $torq_fsp_latest

echo "Files downloaded. Executing install script"

bash installtorqapp.sh --torq TorQ-$torq_latest.tar.gz --releasedir deploy --data datatemp --installfile TorQ-Finance-Starter-Pack-$torq_fsp_latest.tar.gz


text:
Slack bot to save links: Meteor
-----

A meteor web application using iron:router.

## Pre-requests
 - Install [meteor](https://www.meteor.com/install) ```curl https://install.meteor.com/ | sh```
 - Add token from webhook-integration to ```settings.json```

### Run localy:
In CLI: ```meteor```

### Deploy
```
meteor deploy save-a-link-bot.meteor.com --settings settings.json
```


text:
package schema.override;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.traversers.override.DOMOverrideImpl;
import org.apache.xerces.impl.xs.traversers.override.OverrideTransformationManager;
import org.apache.xerces.util.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @version $Id$
 */
public class OverrideHandlerTest extends BaseOverrideTest {

    Hashtable fId2DocMap ;
    OverrideTransformationManager fOverrideHandler;
    LinkedList fDependencyList ;
    String fDirectedGraph;

    public static void main(String args[]) {
        junit.textui.TestRunner.run(OverrideHandlerTest.class);
    }

    public OverrideHandlerTest(){
        fId2DocMap = createId2DocMapScenario_1();

    }

    protected void setUp(){
        fDependencyList = new LinkedList();
        fDirectedGraph = "";
        XSHandlerDelegate schemaHandler = new XSHandlerDelegate(Constants.SCHEMA_VERSION_1_1, null);
        fOverrideHandler = new OverrideTransformationManager(schemaHandler, new DOMOverrideImpl(schemaHandler));
    }

    public void testHasGlobalDecerations(){
        String[] testSchemas = {"schemaA.xsd","schemaA_1.xsd"};
        OverrideTransformationManager overrideHandler = new OverrideTransformationManager(null, null);

        Document dom1 = parseXmlDom(getResourceURL(testSchemas[0]));
        assertFalse(overrideHandler.hasGlobalDecl(dom1.getDocumentElement()));

        dom1 = parseXmlDom(getResourceURL(testSchemas[1]));
        assertTrue(overrideHandler.hasGlobalDecl(dom1.getDocumentElement()));

    }

    public void testHasCompositionalDecerations(){
        String[] testSchemas = {"schemaA.xsd","schemaA_1.xsd","schemaA_2.xsd"};
        OverrideTransformationManager overrideHandler = new OverrideTransformationManager(null, null);

        Document dom1 = parseXmlDom(getResourceURL(testSchemas[0]));
        assertTrue(overrideHandler.hasCompositionalDecl(dom1.getDocumentElement()));

        dom1 = parseXmlDom(getResourceURL(testSchemas[1]));
        assertTrue(overrideHandler.hasCompositionalDecl(dom1.getDocumentElement()));

        dom1 = parseXmlDom(getResourceURL(testSchemas[2]));
        assertFalse(overrideHandler.hasCompositionalDecl(dom1.getDocumentElement()));

    }

    public void testDependencyNoSchemaRepeats(){
        TestNode root = createDependancyMap1();
        String id = "A.xsd";
        Element domSchemaRoot = (Element) fId2DocMap.get(id);
        fDirectedGraph = id;
        fOverrideHandler.checkSchemaRoot(id, null,domSchemaRoot);
        performDependencyChecking(root,domSchemaRoot);
        System.out.println(fDirectedGraph);

    }

    public void testDependencySchemaRepeats(){
        fId2DocMap = createId2DocMapScenario_2();
        TestNode root = createDependancyMap2();
        String id = "A.xsd";
        Element domSchemaRoot = (Element) fId2DocMap.get(id);
        fDirectedGraph = id;
        fOverrideHandler.checkSchemaRoot(id, null,domSchemaRoot);
        performDependencyChecking(root,domSchemaRoot);
        System.out.println(fDirectedGraph);

    }

    public void testDependencySchemaRepeats_Collision(){
        fId2DocMap = createId2DocMapScenario_3();
        TestNode root = createDependancyMap3();
        String id = "A.xsd";
        Element domSchemaRoot = (Element) fId2DocMap.get(id);
        fDirectedGraph = id;
        fOverrideHandler.checkSchemaRoot(id, null,domSchemaRoot);
        performDependencyChecking(root,domSchemaRoot);
        System.out.println(fDirectedGraph);

    }

    public void testDependencySchemaRepeats_Cycles(){
        fId2DocMap = createId2DocMapScenario_4();
        TestNode root = createDependancyMap4();
        String id = "A.xsd";
        Element domSchemaRoot = (Element) fId2DocMap.get(id);
        fDirectedGraph = id;
        fOverrideHandler.checkSchemaRoot(id, null,domSchemaRoot);
        performDependencyChecking(root,domSchemaRoot);
        System.out.println(fDirectedGraph);

    }

    public void testDependencySchemaRepeats_Collision_2(){
        fId2DocMap = createId2DocMapScenario_5();
        TestNode root = createDependancyMap5();
        String id = "A.xsd";
        Element domSchemaRoot = (Element) fId2DocMap.get(id);
        fDirectedGraph = id;
        fOverrideHandler.checkSchemaRoot(id, null,domSchemaRoot);
        performDependencyChecking(root,domSchemaRoot);
        System.out.println(fDirectedGraph);

    }
    //"A inc B inc C";
    public TestNode createDependancyMap1(){
        TestNode parent = new TestNode();
        parent.expectedState = OverrideTransformationManager.STATE_INCLUDE;

        TestNode child = new TestNode();
        child.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        parent.addChildNode(child);

        TestNode desc = new TestNode();
        desc.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        child.addChildNode(desc);

        fillDependencyList(parent);
        return parent;
    }

    public TestNode createDependancyMap2(){
        TestNode parent = new TestNode();
        parent.expectedState = OverrideTransformationManager.STATE_INCLUDE;

        TestNode child = new TestNode();
        child.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        parent.addChildNode(child);

        TestNode desc = new TestNode();
        desc.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        child.addChildNode(desc);

        TestNode desc2 = new TestNode();
        desc2.expectedState = OverrideTransformationManager.STATE_DUPLICATE;
        desc.addChildNode(desc2);

        fillDependencyList(parent);
        return parent;
    }

    public TestNode createDependancyMap3(){
        TestNode parent = new TestNode();
        parent.expectedState = OverrideTransformationManager.STATE_INCLUDE;

        TestNode child = new TestNode();
        child.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        parent.addChildNode(child);

        TestNode desc = new TestNode();
        desc.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        child.addChildNode(desc);

        TestNode desc2 = new TestNode();
        desc2.expectedState = OverrideTransformationManager.STATE_COLLISION;
        desc.addChildNode(desc2);

        fillDependencyList(parent);
        return parent;
    }

    public TestNode createDependancyMap4(){
        //A
        TestNode parent = new TestNode();
        parent.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        //-->B
        TestNode child = new TestNode();
        child.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        parent.addChildNode(child);
        //-->C
        TestNode desc = new TestNode();
        desc.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        child.addChildNode(desc);
        //-->A'
        TestNode desc2 = new TestNode();
        desc2.expectedState = OverrideTransformationManager.STATE_CONTINUE;
        desc.addChildNode(desc2);
        //-->B'
        TestNode desc3 = new TestNode();
        desc3.expectedState = OverrideTransformationManager.STATE_CONTINUE;
        desc2.addChildNode(desc3);
        //-->C'
        TestNode desc4 = new TestNode();
        desc4.expectedState = OverrideTransformationManager.STATE_DUPLICATE;
        desc3.addChildNode(desc4);

        fillDependencyList(parent);
        return parent;
    }

    public TestNode createDependancyMap5(){
        //A
        TestNode parent = new TestNode();
        parent.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        //-->B
        TestNode child = new TestNode();
        child.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        parent.addChildNode(child);
        //-->C
        TestNode desc = new TestNode();
        desc.expectedState = OverrideTransformationManager.STATE_INCLUDE;
        child.addChildNode(desc);
        //-->A'
        TestNode desc2 = new TestNode();
        desc2.expectedState = OverrideTransformationManager.STATE_CONTINUE;
        desc.addChildNode(desc2);
        //-->B'
        TestNode desc3 = new TestNode();
        desc3.expectedState = OverrideTransformationManager.STATE_COLLISION;
        desc2.addChildNode(desc3);

        fillDependencyList(parent);
        return parent;
    }

    private void fillDependencyList(TestNode parent){
        if(parent!=null){
            fDependencyList.add(parent);
            Iterator children = parent.getChildren();

            while(children.hasNext()){
                fillDependencyList((TestNode)children.next());
            }
        }
    }

    public void print(int state){
        if(state == OverrideTransformationManager.STATE_DUPLICATE){
            System.out.println("CYCLE");
        }
        else if(state == OverrideTransformationManager.STATE_CONTINUE){
            System.out.println("CONTINUE");
        }
        else if(state == OverrideTransformationManager.STATE_COLLISION){
            System.out.println("COLLISION");
        }
        else{
            System.out.println("INCLUDE");
        }
    }

    public void performDependencyChecking(TestNode tNode,Element root){
        assertEquals(tNode.expectedState, fOverrideHandler.getCurrentState());
        print(tNode.expectedState);
        fDependencyList.removeFirst();
        if(root == null){
            return;
        }

        for (Element child = DOMUtil.getFirstChildElement(root);
        child != null;
        child = DOMUtil.getNextSiblingElement(child)){

            String localName = getLocalName(child);

            if (localName.equals(SchemaSymbols.ELT_ANNOTATION)){
                continue;
            }
            else if(localName.equals(SchemaSymbols.ELT_INCLUDE)){
                String id = DOMUtil.getAttrValue(child, SchemaSymbols.ATT_SCHEMALOCATION);
                System.out.println("<include> id : " + id);
                Element domNode = (Element) fId2DocMap.get(id);
                Element target = (Element) fOverrideHandler.transform(id, null, domNode);
                fDirectedGraph+= "--inc-->" + id;
                performDependencyChecking((TestNode)fDependencyList.getFirst(), target);
                if(fOverrideHandler.getCurrentState() == OverrideTransformationManager.STATE_DUPLICATE ||
                            fOverrideHandler.getCurrentState() == OverrideTransformationManager.STATE_COLLISION)
                   fDirectedGraph+= "\n";
            }
            else if(localName.equals(SchemaSymbols.ELT_REDEFINE)){

            }
            else if(localName.equals(SchemaSymbols.ELT_OVERRIDE)){
                String id = DOMUtil.getAttrValue(child, SchemaSymbols.ATT_SCHEMALOCATION);
                System.out.println("<override> id : " + id);
                Element domNode = (Element) fId2DocMap.get(id);
                Element overridden = (Element)fOverrideHandler.transform(id, child, domNode);
                fDirectedGraph+= "--ov-->" + id;
                performDependencyChecking((TestNode)fDependencyList.getFirst(), overridden);
                if(fOverrideHandler.getCurrentState() == OverrideTransformationManager.STATE_DUPLICATE ||
                            fOverrideHandler.getCurrentState() == OverrideTransformationManager.STATE_COLLISION)
                   fDirectedGraph+= "\n";
            }
        }
    }

    public Hashtable createId2DocMapScenario_1(){
        Hashtable map = new Hashtable();
        map.put("A.xsd",parseXmlDom(getResourceURL("scenario_1/A.xsd")).getDocumentElement());
        map.put("B.xsd",parseXmlDom(getResourceURL("scenario_1/B.xsd")).getDocumentElement());
        map.put("C.xsd",parseXmlDom(getResourceURL("scenario_1/C.xsd")).getDocumentElement());

        return map;
    }

    public Hashtable createId2DocMapScenario_2(){
        Hashtable map = new Hashtable();
        map.put("A.xsd",parseXmlDom(getResourceURL("scenario_2/A.xsd")).getDocumentElement());
        map.put("B.xsd",parseXmlDom(getResourceURL("scenario_2/B.xsd")).getDocumentElement());
        map.put("C.xsd",parseXmlDom(getResourceURL("scenario_2/C.xsd")).getDocumentElement());

        return map;
    }

    public Hashtable createId2DocMapScenario_3(){
        Hashtable map = new Hashtable();
        map.put("A.xsd",parseXmlDom(getResourceURL("scenario_3/A.xsd")).getDocumentElement());
        map.put("B.xsd",parseXmlDom(getResourceURL("scenario_3/B.xsd")).getDocumentElement());
        map.put("C.xsd",parseXmlDom(getResourceURL("scenario_3/C.xsd")).getDocumentElement());

        return map;
    }

    public Hashtable createId2DocMapScenario_4(){
        Hashtable map = new Hashtable();
        map.put("A.xsd",parseXmlDom(getResourceURL("scenario_4/A.xsd")).getDocumentElement());
        map.put("B.xsd",parseXmlDom(getResourceURL("scenario_4/B.xsd")).getDocumentElement());
        map.put("C.xsd",parseXmlDom(getResourceURL("scenario_4/C.xsd")).getDocumentElement());

        return map;
    }

    public Hashtable createId2DocMapScenario_5(){
        Hashtable map = new Hashtable();
        map.put("A.xsd",parseXmlDom(getResourceURL("scenario_5/A.xsd")).getDocumentElement());
        map.put("B.xsd",parseXmlDom(getResourceURL("scenario_5/B.xsd")).getDocumentElement());
        map.put("C.xsd",parseXmlDom(getResourceURL("scenario_5/C.xsd")).getDocumentElement());

        return map;
    }

    static class TestNode{
        ArrayList children = new ArrayList();
        int expectedState;

        public TestNode(){
        }

        public void addChildNode(TestNode child){
            children.add(child);
        }

        public Iterator getChildren(){
            return this.children.iterator();
        }

    }
}


text:
import React from 'react';
import styles from './Footer.scss';

const Footer = ({ title }: {title: String}) =>
  <footer className={styles.root} >
    <span>{title}</span>
  </footer>;

export default Footer;


text:
{% assign paginator_min = paginator.page | minus: 4 %}
{% assign paginator_max = paginator.page | plus: 4 %}
{% assign paginator_max_pre = paginator.page | plus: 3 %}

{% if paginator_min < 0 %}
    {% assign paginator_min_abs = paginator_min | abs %}
    {% assign paginator_max = paginator_max | plus: paginator_min_abs %}
{% elsif paginator_max_pre > paginator.total_pages %}
    {% assign paginator_max_shift = paginator_max_pre | minus: paginator.total_pages %}
    {% assign paginator_min = paginator_min | minus: paginator_max_shift %}
{% endif %}

    {% for page in (1..paginator.total_pages) %}
      {% if page > paginator_min and page < paginator_max %}
        {% if paginator.page == page %}

{{ page }}

        {% elsif page == 1 %}

{{ page }}

        {% else %}

{{ page }}

        {% endif %}
      {% endif %}
    {% endfor %}

  Showing {{ paginator.posts.size }} results of {{ site.posts.size }} — Page {{ paginator.page }} of {{ paginator.total_pages }}


text:
"""Interface to the SmartTub API."""

import asyncio
from datetime import timedelta
import logging

from aiohttp import client_exceptions
import async_timeout
from smarttub import APIError, LoginFailed, SmartTub
from smarttub.api import Account

from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DOMAIN, POLLING_TIMEOUT, SCAN_INTERVAL
from .helpers import get_spa_name

_LOGGER = logging.getLogger(__name__)

class SmartTubController:
    """Interface between Home Assistant and the SmartTub API."""

    def __init__(self, hass):
        """Initialize an interface to SmartTub."""
        self._hass = hass
        self._account = None
        self.spas = set()
        self._spa_devices = {}

        self.coordinator = None

    async def async_setup_entry(self, entry):
        """Perform initial setup.

        Authenticate, query static state, set up polling, and otherwise make
        ready for normal operations .
        """

        try:
            self._account = await self.login(
                entry.data[CONF_EMAIL], entry.data[CONF_PASSWORD]
            )
        except LoginFailed:
            # credentials were changed or invalidated, we need new ones

            return False
        except (
            asyncio.TimeoutError,
            client_exceptions.ClientOSError,
            client_exceptions.ServerDisconnectedError,
            client_exceptions.ContentTypeError,
        ) as err:
            raise ConfigEntryNotReady from err

        self.spas = await self._account.get_spas()

        self.coordinator = DataUpdateCoordinator(
            self._hass,
            _LOGGER,
            name=DOMAIN,
            update_method=self.async_update_data,
            update_interval=timedelta(seconds=SCAN_INTERVAL),
        )

        await self.coordinator.async_refresh()

        await self.async_register_devices(entry)

        return True

    async def async_update_data(self):
        """Query the API and return the new state."""

        data = {}
        try:
            async with async_timeout.timeout(POLLING_TIMEOUT):
                for spa in self.spas:
                    data[spa.id] = await self._get_spa_data(spa)
        except APIError as err:
            raise UpdateFailed(err) from err

        return data

    async def _get_spa_data(self, spa):
        status, pumps, lights = await asyncio.gather(
            spa.get_status(),
            spa.get_pumps(),
            spa.get_lights(),
        )
        return {
            "status": status,
            "pumps": {pump.id: pump for pump in pumps},
            "lights": {light.zone: light for light in lights},
        }

    async def async_register_devices(self, entry):
        """Register devices with the device registry for all spas."""
        device_registry = await dr.async_get_registry(self._hass)
        for spa in self.spas:
            device = device_registry.async_get_or_create(
                config_entry_id=entry.entry_id,
                identifiers={(DOMAIN, spa.id)},
                manufacturer=spa.brand,
                name=get_spa_name(spa),
                model=spa.model,
            )
            self._spa_devices[spa.id] = device

    async def login(self, email, password) -> Account:
        """Retrieve the account corresponding to the specified email and password.

        Returns None if the credentials are invalid.
        """

        api = SmartTub(async_get_clientsession(self._hass))

        await api.login(email, password)
        return await api.get_account()


text:
class X {

  @interface MyAnnotation {
    int value();
  }

  @MyAnnotation(value = {"blah"}<caret>)
  void foo() {}
}


text:
/*
 * XML Type:  RelationshipXRefType
 * Namespace: http://lmp.nci.nih.gov/mim/mimVisLevel1
 * Java type: gov.nih.nci.lmp.mim.mimVisLevel1.RelationshipXRefType
 *
 * Automatically generated - do not modify.
 */
package gov.nih.nci.lmp.mim.mimVisLevel1.impl;
/**
 * An XML RelationshipXRefType(@http://lmp.nci.nih.gov/mim/mimVisLevel1).
 *
 * This is a complex type.
 */
public class RelationshipXRefTypeImpl extends gov.nih.nci.lmp.mim.mimVisLevel1.impl.XRefTypeImpl implements gov.nih.nci.lmp.mim.mimVisLevel1.RelationshipXRefType
{
    private static final long serialVersionUID = 1L;

    public RelationshipXRefTypeImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType);
    }

    private static final javax.xml.namespace.QName TYPE$0 =
        new javax.xml.namespace.QName("", "type");

    /**
     * Gets the "type" attribute
     */
    public java.lang.String getType()
    {
        synchronized (monitor())
        {
            check_orphaned();
            org.apache.xmlbeans.SimpleValue target = null;
            target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(TYPE$0);
            if (target == null)
            {
                return null;
            }
            return target.getStringValue();
        }
    }

    /**
     * Gets (as xml) the "type" attribute
     */
    public org.apache.xmlbeans.XmlString xgetType()
    {
        synchronized (monitor())
        {
            check_orphaned();
            org.apache.xmlbeans.XmlString target = null;
            target = (org.apache.xmlbeans.XmlString)get_store().find_attribute_user(TYPE$0);
            return target;
        }
    }

    /**
     * Sets the "type" attribute
     */
    public void setType(java.lang.String type)
    {
        synchronized (monitor())
        {
            check_orphaned();
            org.apache.xmlbeans.SimpleValue target = null;
            target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(TYPE$0);
            if (target == null)
            {
                target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(TYPE$0);
            }
            target.setStringValue(type);
        }
    }

    /**
     * Sets (as xml) the "type" attribute
     */
    public void xsetType(org.apache.xmlbeans.XmlString type)
    {
        synchronized (monitor())
        {
            check_orphaned();
            org.apache.xmlbeans.XmlString target = null;
            target = (org.apache.xmlbeans.XmlString)get_store().find_attribute_user(TYPE$0);
            if (target == null)
            {
                target = (org.apache.xmlbeans.XmlString)get_store().add_attribute_user(TYPE$0);
            }
            target.set(type);
        }
    }
}


text:
using testing::AssertionResult;

namespace Envoy {
namespace {

const char FirstClusterName[] = "cluster_1";
const char SecondClusterName[] = "cluster_2";
// Index in fake_upstreams_
const int FirstUpstreamIndex = 2;
const int SecondUpstreamIndex = 3;

const std::string& config() {
  CONSTRUCT_ON_FIRST_USE(std::string, fmt::format(R"EOF(
admin:
  access_log:
  - name: envoy.access_loggers.file
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog
      path: "{}"
  address:
    socket_address:
      address: 127.0.0.1
      port_value: 0
dynamic_resources:
  cds_config:
    resource_api_version: V3
    api_config_source:
      api_type: GRPC
      transport_api_version: V3
      grpc_services:
        envoy_grpc:
          cluster_name: my_cds_cluster
      set_node_on_first_message_only: true
static_resources:
  clusters:
  - name: my_cds_cluster
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config:
          http2_protocol_options: {{}}
    load_assignment:
      cluster_name: my_cds_cluster
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 0
  - name: aggregate_cluster
    connect_timeout: 0.25s
    lb_policy: CLUSTER_PROVIDED
    cluster_type:
      name: envoy.clusters.aggregate
      typed_config:
        "@type": type.googleapis.com/envoy.extensions.clusters.aggregate.v3.ClusterConfig
        clusters:
        - cluster_1
        - cluster_2
  listeners:
  - name: http
    address:
      socket_address:
        address: 127.0.0.1
        port_value: 0
    filter_chains:
      filters:
        name: http
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: config_test
          http_filters:
            name: envoy.filters.http.router
          codec_type: HTTP1
          route_config:
            name: route_config_0
            validate_clusters: false
            virtual_hosts:
              name: integration
              routes:
              - route:
                  cluster: cluster_1
                match:
                  prefix: "/cluster1"
              - route:
                  cluster: cluster_2
                match:
                  prefix: "/cluster2"
              - route:
                  cluster: aggregate_cluster
                  retry_policy:
                    retry_priority:
                      name: envoy.retry_priorities.previous_priorities
                      typed_config:
                        "@type": type.googleapis.com/envoy.extensions.retry.priority.previous_priorities.v3.PreviousPrioritiesConfig
                        update_frequency: 1
                match:
                  prefix: "/aggregatecluster"
              domains: "*"
)EOF",
                                                  Platform::null_device_path));
}

class AggregateIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>,
                                 public HttpIntegrationTest {
public:
  AggregateIntegrationTest() : HttpIntegrationTest(Http::CodecType::HTTP1, GetParam(), config()) {
    use_lds_ = false;
  }

  void TearDown() override { cleanUpXdsConnection(); }

  void initialize() override {
    use_lds_ = false;
    setUpstreamCount(2);                         // the CDS cluster
    setUpstreamProtocol(Http::CodecType::HTTP2); // CDS uses gRPC uses HTTP2.

    defer_listener_finalization_ = true;
    HttpIntegrationTest::initialize();

    addFakeUpstream(Http::CodecType::HTTP2);
    addFakeUpstream(Http::CodecType::HTTP2);
    cluster1_ = ConfigHelper::buildStaticCluster(
        FirstClusterName, fake_upstreams_[FirstUpstreamIndex]->localAddress()->ip()->port(),
        Network::Test::getLoopbackAddressString(GetParam()));
    cluster2_ = ConfigHelper::buildStaticCluster(
        SecondClusterName, fake_upstreams_[SecondUpstreamIndex]->localAddress()->ip()->port(),
        Network::Test::getLoopbackAddressString(GetParam()));

    // Let Envoy establish its connection to the CDS server.
    acceptXdsConnection();

    // Do the initial compareDiscoveryRequest / sendDiscoveryResponse for cluster_1.
    EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "", {}, {}, {}, true));
    sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(Config::TypeUrl::get().Cluster,
                                                               {cluster1_}, {cluster1_}, {}, "55");

    test_server_->waitForGaugeGe("cluster_manager.active_clusters", 3);

    // Wait for our statically specified listener to become ready, and register its port in the
    // test framework's downstream listener port map.
    test_server_->waitUntilListenersReady();
    registerTestServerPorts({"http"});
  }

  void acceptXdsConnection() {
    AssertionResult result = // xds_connection_ is filled with the new FakeHttpConnection.
        fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, xds_connection_);
    RELEASE_ASSERT(result, result.message());
    result = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);
    RELEASE_ASSERT(result, result.message());
    xds_stream_->startGrpcStream();
  }

  envoy::config::cluster::v3::Cluster cluster1_;
  envoy::config::cluster::v3::Cluster cluster2_;
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AggregateIntegrationTest,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()));

TEST_P(AggregateIntegrationTest, ClusterUpDownUp) {
  // Calls our initialize(), which includes establishing a listener, route, and cluster.
  testRouterHeaderOnlyRequestAndResponse(nullptr, FirstUpstreamIndex, "/aggregatecluster");

  // Tell Envoy that cluster_1 is gone.
  EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "55", {}, {}, {}));
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(Config::TypeUrl::get().Cluster, {}, {},
                                                             {FirstClusterName}, "42");
  // We can continue the test once we're sure that Envoy's ClusterManager has made use of
  // the DiscoveryResponse that says cluster_1 is gone.
  test_server_->waitForCounterGe("cluster_manager.cluster_removed", 1);

  // Now that cluster_1 is gone, the listener (with its routing to cluster_1) should 503.
  BufferingStreamDecoderPtr response =
      IntegrationUtil::makeSingleRequest(lookupPort("http"), "GET", "/aggregatecluster", "",
                                         downstream_protocol_, version_, "foo.com");
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("503", response->headers().getStatusValue());

  cleanupUpstreamAndDownstream();
  ASSERT_TRUE(codec_client_->waitForDisconnect());

  // Tell Envoy that cluster_1 is back.
  EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "42", {}, {}, {}));
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(Config::TypeUrl::get().Cluster,
                                                             {cluster1_}, {cluster1_}, {}, "413");

  test_server_->waitForGaugeGe("cluster_manager.active_clusters", 3);
  testRouterHeaderOnlyRequestAndResponse(nullptr, FirstUpstreamIndex, "/aggregatecluster");

  cleanupUpstreamAndDownstream();
}

// Tests adding a cluster, adding another, then removing the first.
TEST_P(AggregateIntegrationTest, TwoClusters) {
  // Calls our initialize(), which includes establishing a listener, route, and cluster.
  testRouterHeaderOnlyRequestAndResponse(nullptr, FirstUpstreamIndex, "/aggregatecluster");

  cleanupUpstreamAndDownstream();
  ASSERT_TRUE(codec_client_->waitForDisconnect());

  // Tell Envoy that cluster_2 is here.
  EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "55", {}, {}, {}));
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(
      Config::TypeUrl::get().Cluster, {cluster1_, cluster2_}, {cluster2_}, {}, "42");
  // The '4' includes the fake CDS server and aggregate cluster.
  test_server_->waitForGaugeGe("cluster_manager.active_clusters", 4);

  // A request for aggregate cluster should be fine.
  testRouterHeaderOnlyRequestAndResponse(nullptr, FirstUpstreamIndex, "/aggregatecluster");
  cleanupUpstreamAndDownstream();
  ASSERT_TRUE(codec_client_->waitForDisconnect());

  // Tell Envoy that cluster_1 is gone.
  EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "42", {}, {}, {}));
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(
      Config::TypeUrl::get().Cluster, {cluster2_}, {}, {FirstClusterName}, "43");
  // We can continue the test once we're sure that Envoy's ClusterManager has made use of
  // the DiscoveryResponse that says cluster_1 is gone.
  test_server_->waitForCounterGe("cluster_manager.cluster_removed", 1);

  testRouterHeaderOnlyRequestAndResponse(nullptr, SecondUpstreamIndex, "/aggregatecluster");
  cleanupUpstreamAndDownstream();
  ASSERT_TRUE(codec_client_->waitForDisconnect());

  // Tell Envoy that cluster_1 is back.
  EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "43", {}, {}, {}));
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(
      Config::TypeUrl::get().Cluster, {cluster1_, cluster2_}, {cluster1_}, {}, "413");

  test_server_->waitForGaugeGe("cluster_manager.active_clusters", 4);
  testRouterHeaderOnlyRequestAndResponse(nullptr, FirstUpstreamIndex, "/aggregatecluster");

  cleanupUpstreamAndDownstream();
}

// Test that the PreviousPriorities retry predicate works as expected. It is configured
// in this test to exclude a priority after a single failure, so the first failure
// on cluster_1 results in the retry going to cluster_2.
TEST_P(AggregateIntegrationTest, PreviousPrioritiesRetryPredicate) {
  initialize();

  // Tell Envoy that cluster_2 is here.
  sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(
      Config::TypeUrl::get().Cluster, {cluster1_, cluster2_}, {cluster2_}, {}, "42");
  // The '4' includes the fake CDS server and aggregate cluster.
  test_server_->waitForGaugeGe("cluster_manager.active_clusters", 4);

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{{":method", "GET"},
                                     {":path", "/aggregatecluster"},
                                     {":scheme", "http"},
                                     {":authority", "host"},
                                     {"x-forwarded-for", "10.0.0.1"},
                                     {"x-envoy-retry-on", "5xx"}},
      1024);
  waitForNextUpstreamRequest(FirstUpstreamIndex);
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);

  ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
  ASSERT_TRUE(fake_upstream_connection_->close());
  ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
  fake_upstream_connection_.reset();

  waitForNextUpstreamRequest(SecondUpstreamIndex);
  upstream_request_->encodeHeaders(default_response_headers_, true);

  ASSERT_TRUE(response->waitForEndStream());
  EXPECT_TRUE(upstream_request_->complete());

  EXPECT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
  cleanupUpstreamAndDownstream();
}

} // namespace
} // namespace Envoy


text:
> Monitorar as mudanças de estado de energia.

Você só pode usá-lo no processo principal. Você não deve usar este módulo até que o evento `ready` do modulo `app` seja emitido.

Por exemplo:

```javascript
app.on('ready', () => {
  require('electron').powerMonitor.on('suspend', () => {
    console.log('O sistema está indo dormir');
  });
});
```

## Eventos

O módulo `power-monitor` emite os seguintes eventos:

### Evento: 'suspend'

Emitido quando o sistema está a suspender.

### Evento: 'resume'

Emitido quando o sistema está a retomar.

### Evento: 'on-ac' _Windows_

Emitido quando o sistema muda para energia AC.

### Evento: 'on-battery' _Windows_

Emitido quando o sistema muda para a energia da bateria.