#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the compressed stream file entry implementation."""

import unittest

from dfvfs.lib import definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import context
from dfvfs.vfs import compressed_stream_file_entry
from dfvfs.vfs import compressed_stream_file_system

from tests import test_lib as shared_test_lib

class CompressedStreamFileEntryTest(shared_test_lib.BaseTestCase):
  """Tests the compressed stream file entry."""

  def setUp(self):
    """Sets up the needed objects used throughout the test."""
    self._resolver_context = context.Context()
    test_path = self._GetTestFilePath(['syslog.bz2'])
    self._SkipIfPathNotExists(test_path)

    test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
        definitions.TYPE_INDICATOR_OS, location=test_path)
    self._compressed_stream_path_spec = path_spec_factory.Factory.NewPathSpec(
        definitions.TYPE_INDICATOR_COMPRESSED_STREAM,
        compression_method=definitions.COMPRESSION_METHOD_BZIP2,
        parent=test_os_path_spec)

    self._file_system = (
        compressed_stream_file_system.CompressedStreamFileSystem(
            self._resolver_context, self._compressed_stream_path_spec))
    self._file_system.Open()

  def tearDown(self):
    """Cleans up the needed objects used throughout the test."""
    self._resolver_context.Empty()

  def testInitialize(self):
    """Test the __init__ function."""
    file_entry = compressed_stream_file_entry.CompressedStreamFileEntry(
        self._resolver_context, self._file_system,
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

  def testSize(self):
    """Test the size property."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)

    self.assertIsNotNone(file_entry)
    self.assertEqual(file_entry.size, 1247)

  def testGetFileEntryByPathSpec(self):
    """Test the get a file entry by path specification functionality."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

  def testGetParentFileEntry(self):
    """Tests the GetParentFileEntry function."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

    parent_file_entry = file_entry.GetParentFileEntry()
    self.assertIsNone(parent_file_entry)

  def testIsFunctions(self):
    """Test the Is? functions."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

    self.assertTrue(file_entry.IsRoot())
    self.assertTrue(file_entry.IsVirtual())
    self.assertTrue(file_entry.IsAllocated())

    self.assertFalse(file_entry.IsDevice())
    self.assertFalse(file_entry.IsDirectory())
    self.assertTrue(file_entry.IsFile())
    self.assertFalse(file_entry.IsLink())
    self.assertFalse(file_entry.IsPipe())
    self.assertFalse(file_entry.IsSocket())

  def testSubFileEntries(self):
    """Test the sub file entries iteration functionality."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

    self.assertEqual(file_entry.number_of_sub_file_entries, 0)

    expected_sub_file_entry_names = []

    sub_file_entry_names = []
    for sub_file_entry in file_entry.sub_file_entries:
      sub_file_entry_names.append(sub_file_entry.name)

    self.assertEqual(
        len(sub_file_entry_names), len(expected_sub_file_entry_names))
    self.assertEqual(
        sorted(sub_file_entry_names), expected_sub_file_entry_names)

  def testDataStreams(self):
    """Test the data streams functionality."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

    self.assertEqual(file_entry.number_of_data_streams, 1)

    data_stream_names = []
    for data_stream in file_entry.data_streams:
      data_stream_names.append(data_stream.name)

    self.assertEqual(data_stream_names, [''])

  def testGetDataStream(self):
    """Tests the GetDataStream function."""
    file_entry = self._file_system.GetFileEntryByPathSpec(
        self._compressed_stream_path_spec)
    self.assertIsNotNone(file_entry)

    data_stream_name = ''
    data_stream = file_entry.GetDataStream(data_stream_name)
    self.assertIsNotNone(data_stream)
    self.assertEqual(data_stream.name, data_stream_name)

    data_stream = file_entry.GetDataStream('bogus')
    self.assertIsNone(data_stream)

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


import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint

pp = pprint.PrettyPrinter()

scope =['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('SheetsDatabase-d61611f5391b.json', scopes=scope)
client = gspread.authorize(credentials)

sheet = client.open('Rakuten').sheet1

all_records = sheet.get_all_records()
pp.pprint(all_records)

# single_row = sheet.cell(2,1).value
# pp.pprint(single_row)

# name = sheet.find("James")
# print("James can be found at Row:%s Column:%s" %(name.row, name.col))

# sheet.update_cell(2,2,'Java')
# single_row = sheet.row_values(2)
# pp.pprint(single_row)

# new_row = ["Here","is","a","new","row"]
# index = 2
# sheet.insert_row(new_row, index)

# sheet.delete_row(2)

# print(sheet.row_count)


"""
Wrapper functon of blueqat

"""

from blueqat import opt
import numpy as np

def auto_bit_search_by_blueqat(mat, shots=100):
    """
    search ideal binary by blueqat

    Parameters
    ----------------------------
    mat: np array
        qubo matrix
    shots: int
        number of shots for annealing
    Returns
    ---------------
    ideal_bit: np array of 01010101..
        best binary found by blueqat
    min_energy: np
        its energy
    """

    an = opt.opt()
    an.qubo = -mat

    result = an.sa(shots=shots, sampler="fast")

    en = [i[-1] for i in an.E]
    min_energy = min(en)
    ideal_bit = result[np.where(en == min_energy)[0][0]]

    return ideal_bit, min_energy


from jazzr.tools import latex, transcription
from jazzr.midi import representation
from jazzr.annotation import Annotation
import math

class Symbol(object):

    # Types
    ONSET = 0
    TIE = 1
    SYMB = 2
    SONG = 3

    #Beats
    DOWN = 0
    UP = 1

    def __init__(self, features, length=None, children=None, depth=0, type=SYMB, beats=[], onsets=[], divisions=[], perf_beats=[], perf_on=None):
        self.depth = depth
        self.type = type
        self.children = children
        self.length = length
        self.features = features
        self.beats = beats
        self.onsets = onsets
        self.prior = 1.0
        self.likelihood = None
        self.divisions = divisions
        self.perf_beats = perf_beats
        self.perf_on = perf_on

    @staticmethod
    def fill(onsets, division):
        beats = [None for x in range(division)]
        for pos, onset in onsets:
            if int(pos) == pos and pos < division:
                beats[int(pos)] = onset
        if len(onsets) <= 1:
            return beats

        for (p1, t1), (p2, t2) in zip(onsets[:-1], onsets[1:]):
            if p2 - p1 == 0:
                length = 0
            else:
                length = (t2 - t1)/float(p2 - p1)
            for i in range(0, int(p2)):
                if beats[i] == None:
                    beats[i] = t1 + (i - p1) * length
        if division > int(p2):
            for i in range(int(p2), division):
                if beats[i] == None:
                    beats[i] = t1 + (i - p1) * length
        return beats

    @staticmethod
    def fromSymbols(Symbols, corpus=False):
        # beats should be filled with actual onsets, and filled with onsets estimated from those
        # as soon as two onsets are defined, upper symbols only add their own onsets
        division = len(Symbols)
        positions = []
        onsets = [None for x in range(division)]
        complexpositions = []

        previous = None
        next = None

        perf_complexpositions = []
        perf_positions = []
        perf_on = None

        if corpus:
            if len(Symbols) == 3 and Symbols[0].isTie() and Symbols[1].isTie():
                if Symbols[2].annotation.type(Symbols[2].index) == Annotation.SWUNG and not Symbols[2].annotation.position(Symbols[2].index) - int(Symbols[2].annotation.position(Symbols[2].index)) == 0:
                    positions.append((0, int(Symbols[2].on)))
        #      perf_positions.append((0, Symbols[2].annotation.perf_onset(Symbols[2].index) - 2/3.0 * 60000000/float(Symbols[2].annotation.bpm)))

        for S, pos in zip(Symbols, range(0, division)):
            if S.isOnset():
                positions.append((pos, S.on))
                onsets[pos] = S
                if previous == None:
                    previous = S.previous
                next = S.next
                if corpus:
                    perf_positions.append((pos, S.annotation.perf_onset(S.index)))

            elif S.isSymbol():
                (complexpos, (p, onset, n)) = S.features
                next = n
                if previous == None:
                    previous = p

                if S.beats[0] != None:
                    positions.append((pos, S.beats[0]))
                    if S.onsets[0] != None:
                        onsets[pos] = S.onsets[0]
                else:
                    complexpositions.append((pos + complexpos, onset))
                if S.beats[1] != None and S.beats[0] != None:
                    positions.append((pos+1, S.beats[0] + len(S.children) * (S.beats[1] - S.beats[0])))

                if corpus:
                    perf_complexpos, perf_on = S.perf_on
                    if S.perf_beats[0] != None:
                        perf_positions.append((pos, S.perf_beats[0]))
                    else:
                        perf_complexpositions.append((pos + perf_complexpos, perf_on))
                    if S.perf_beats[1] != None and S.perf_beats[0] != None:
                        perf_positions.append((pos+1, S.perf_beats[0] + len(S.children) * (S.perf_beats[1] - S.perf_beats[0])))

        length = None
        if len(positions) <= 1:
            positions += complexpositions
        position, onset = positions[0]
        features = (position/float(division), (previous, onset, next))

        positions = sorted(positions, key=lambda x:x[0])
        beats = Symbol.fill(positions, division)
        if len(positions) >= 2:
            length = division * (beats[1] - beats[0])

        perf_beats = None
        if corpus:
            if len(perf_positions) <= 1:
                perf_positions += perf_complexpositions
            position, on = perf_positions[0]
            perf_on = (position/float(division), on)
            perf_positions = sorted(perf_positions, key=lambda x:x[0])
            perf_beats = Symbol.fill(perf_positions, division)

        children = Symbols
        divisions = max([S.divisions for S in Symbols], key=lambda x: len(x))[:]
        divisions.append(len(Symbols))
        depth = max([S.depth for S in Symbols]) + 1
        R = Symbol(features, length=length, children=children, depth=depth, beats=beats, onsets=onsets, divisions=divisions, perf_beats=perf_beats, perf_on=perf_on)
        return R

    def downbeat(self):
        return self.beats[0]

    def hasDownbeat(self):
        return self.beats[0] != None

    def hasLength(self):
        return self.length != None

    def hasLikelihood(self):
        return self.likelihood != None

    def isOnset(self):
        return self.type == self.ONSET

    def isTie(self):
        return self.type == self.TIE

    def isSymbol(self):
        return self.type == self.SYMB

    def tree(self):
        types = ['on', 'tie', 'symb']
        if self.isTie() or self.isOnset():
            return types[self.type]
        return [child.tree() for child in self.children]

    def transcribe(self, barlevel=0):
        if self.isSymbol():
            return transcription.transcribe(self, barlevel=barlevel)
        else:
            return None

    def midi(self, barlevel=0):
        transcription.save_midi(self, barlevel=barlevel)
        return representation.MidiFile('transcription.mid')
        os.system('rm transcription.mid')

    def latex(self, showOnsets=False, showPerfOnsets=False, showRatios=False, showFeatures=False):
        return latex.latexify(self, showOnsets=showOnsets, showPerfOnsets=showPerfOnsets, showRatios=showRatios)

    def view(self, scale=False, showOnsets=False, showPerfOnsets=False, showRatios=False, showFeatures=False, quiet=True):
        """Generate a LaTeX tree using qtree.sty, convert to pdf with pdflatex and view using Evince. Remove the files afterwards."""
        latex.view_symbols([self], scale=scale, showOnsets=showOnsets, showPerfOnsets=showPerfOnsets, showRatios=showRatios, showFeatures=showFeatures, quiet=quiet)

    def score(self, barlevel=0, annotation=None, pitches=None):
        """Transcribe the symbol, save as MusicXML, convert to pdf using MuseScore and view using Evince. Remove the file afterwards."""
        transcription.view_pdf(self, barlevel=barlevel, annotation=annotation, pitches=pitches)

    def musescore(self, barlevel=0, annotation=None, pitches=None, filename='transcription'):
        transcription.musescore(self, barlevel=barlevel, annotation=annotation, pitches=pitches)

    def __str__(self):
        types = ['Onset', 'Tie', 'Symbol']
        info = ''
        if self.type == self.SYMB:
            return '[{0}:\tLength {1} Features {2} Depth {3}]'.format(types[self.type], self.length, self.features, self.depth)
        else:
            return '[{0}]'.format(types[self.type])

    def fromString():
        # To be implemented
        pass

class Onset(Symbol):

    def __init__(self, previous, on, next, annotation=None, index=None):
        self.previous = previous
        self.on = on
        self.next = next
        self.annotation = annotation
        self.index = index
        super(Onset, self).__init__([], type=Symbol.ONSET)

    def __str__(self):
        return '[{3}:\tOn {0}, Previous {1}, Next {2}]'.format(self.on, self.previous, self.next, super(Onset, self).__str__())

class Tie(Symbol):

    def __init__(self):
        super(Tie, self).__init__([], type=Symbol.TIE)


import unittest

from skimpy.element import *

class TestElement(unittest.TestCase):
    def test_getting_nonexistent_child_raises_keyerror(self):
        with self.assertRaises(KeyError):
            Element['bogus']

    def test_get_returns_copy_bound_to_parent(self):
        class A(Element):
            element = Element
        self.assertIsNot(A['element'], Element)
        self.assertIs(A['element'].parent, A)

    def test_get_on_instance_returns_instance_bound_to_parent_instance(self):
        class A(Element):
            element = Element
        a = A()
        self.assertTrue(isinstance(a['element'], Element))
        self.assertIs(a['element'].parent, a)

    def test_subsequent_instance_gets_return_same_instance(self):
        class A(Element):
            element = Element
        a = A()
        self.assertIs(a['element'], a['element'])

    def test_get_works_with_element_subclass(self):
        class MyElement(Element):
            pass
        class A(Element):
            element = MyElement
        self.assertIsNot(A['element'], MyElement)
        self.assertIs(A['element'].parent, A)

    def test_get_works_with_parent_subclass(self):
        class MyElement(Element):
            pass
        class A(Element):
            element = MyElement
        class B(A):
            pass
        self.assertIsNot(B['element'], MyElement)
        self.assertIs(B['element'].parent, B)

    def test_get_returns_correct_element_with_multiple_inheritance(self):
        class MyElement(Element):
            pass
        class A(Element):
            element = MyElement
        class B(Element):
            element = Element
        class C(A, B):
            pass
        self.assertTrue(issubclass(C['element'], MyElement))

    def test_get_works_with_parent_subclass_instance(self):
        class MyElement(Element):
            pass
        class A(Element):
            element = MyElement
        class B(A):
            pass
        b = B()
        self.assertTrue(isinstance(b['element'], MyElement))
        self.assertIs(b['element'].parent, b)

    def test_can_set_name_on_class(self):
        class MyElement(Element):
            name = 'a_name'
        self.assertEqual(MyElement.name, 'a_name')

    def test_can_set_name_on_instance(self):
        class MyElement(Element):
            pass
        el = MyElement()
        el.name = 'a_name'
        self.assertEqual(el.name, 'a_name')

    def test_path(self):
        class E1(Element):
            class E2(Element):
                class E3(Element):
                    pass
        self.assertEqual(E1['E2']['E3'].path, 'E2.E3')

    def test_path_works_when_supplanted(self):
        class E1(Element):
            class E2(Element):
                class E3(Element):
                    pass
        class E4(Element):
            pass
        E4['E3'] = E1['E2']['E3']
        self.assertEqual(E4['E3'].path, 'E3')

    def test_path_works_when_supplanted_on_instance(self):
        class E1(Element):
            class E2(Element):
                class E3(Element):
                    pass
        class E4(Element):
            pass
        e1 = E1()
        e4 = E4()
        e4['E3'] = e1['E2']['E3']
        self.assertIs(e4['E3'].parent, e4)
        self.assertEqual(e4['E3'].path, 'E3')

    def test_path_with_custom_names(self):
        class E1(Element):
            e2 = type('E2', (Element,), {'e3': Element})
        self.assertEqual(E1['e2']['e3'].path, 'e2.e3')

    def test_can_have_no_children(self):
        self.assertEqual(Element.keys(), [])

    def test_iter_yields_child_names(self):
        class E(Element):
            a = Element
            b = Element
            c = Element
        self.assertEqual(set(E), set('a b c'.split()))

    def test_can_iter_on_child(self):
        class E1(Element):
            class E2(Element):
                a = Element
                b = Element
                c = Element
        self.assertEqual(set(E1['E2']), set('a b c'.split()))

    def test_inherits_children_from_superclass(self):
        class E1(Element):
            a = type('E1a', (Element,), {})
        class E2(Element):
            a = type('E2a', (Element,), {})
        class E3(E1, E2):
            b = Element
        self.assertEqual(set(E3), set('a b'.split()))
        self.assertEqual(E3['a'].__name__, 'E1a')

    def test_iter_on_instance_yields_child_names(self):
        class E(Element):
            a = Element
            b = Element
            c = Element
        e = E()
        self.assertEqual(set(e), set('a b c'.split()))

    def test_subclass_can_have_init_args(self):
        class MyElement(Element):
            def __init__(self, arg1):
                pass
        self.assertTrue(isinstance(MyElement(1), MyElement))

    def test_convert_is_strict_by_default(self):
        class MyElement(Element):
            converter = int
        e = MyElement()
        e.raw_value = 'a'
        with self.assertRaises(ValueError):
            e.convert()
        self.assertEqual(e.value, None)

    def test_from_flat(self):
        class MyElement(Element):
            a = Element
            b = Element
            class c(Element):
                a = Element
                b = Element
                c = Element
        e = MyElement.from_flat({
            'a': 1,
            'b': 2,
            'c': 3,
            'c.a': 4,
            'c.b': 5,
        })
        self.assertEqual(e['a'].value, 1)
        self.assertEqual(e['b'].value, 2)
        self.assertEqual(e['c'].value, 3)
        self.assertEqual(e['c']['a'].value, 4)
        self.assertEqual(e['c']['b'].value, 5)
        self.assertEqual(e['c']['c'].value, None)

    def test_from_flat_with_root_name(self):
        class MyElement(Element):
            name = 'root'
            a = Element
            b = Element
            class c(Element):
                a = Element
                b = Element
                c = Element
        e = MyElement.from_flat({
            'root': 0,
            'root.a': 1,
            'root.b': 2,
            'root.c': 3,
            'root.c.a': 4,
            'root.c.b': 5,
        })
        self.assertEqual(e['a'].value, 1)
        self.assertEqual(e['b'].value, 2)
        self.assertEqual(e['c'].value, 3)
        self.assertEqual(e['c']['a'].value, 4)
        self.assertEqual(e['c']['b'].value, 5)
        self.assertEqual(e['c']['c'].value, None)

    def test_converts_data(self):
        class MyElement(Element):
            converter = int
        el = MyElement.from_flat({'': '1'})
        self.assertEqual(el.raw_value, '1')
        self.assertEqual(el.value, 1)

    def test_can_skip_conversion(self):
        class MyElement(Element):
            converter = int
        el = MyElement.from_flat({'': '1'}, convert=False)
        self.assertEqual(el.raw_value, '1')
        self.assertEqual(el.value, None)

    def test_notes_conversion_errors_by_default(self):
        class MyElement(Element):
            converter = int
        el = MyElement.from_flat({'': 'a'})
        self.assertEqual(el.raw_value, 'a')
        self.assertEqual(el.value, None)
        self.assertTrue(isinstance(el.conversion_error, ValueError))

    def test_raises_conversion_errors_when_strict(self):
        class MyElement(Element):
            converter = int
        with self.assertRaises(ValueError):
            el = MyElement.from_flat({'': 'a'}, strict=True)

    def test_flatten(self):
        class MyElement(Element):
            a = Element
            b = Element
            class c(Element):
                a = Element
                b = Element
                c = Element
        flat = {
            'a': 1,
            'b': 2,
            'c': 3,
            'c.a': 4,
            'c.b': 5,
        }
        e = MyElement.from_flat(flat)
        self.assertEqual(e.flatten(), flat)

    def test_flatten_with_root_name(self):
        class MyElement(Element):
            name = 'root'
            a = Element
            b = Element
            class c(Element):
                a = Element
                b = Element
                c = Element
        flat = {
            'root': 0,
            'root.a': 1,
            'root.b': 2,
            'root.c': 3,
            'root.c.a': 4,
            'root.c.b': 5,
        }
        e = MyElement.from_flat(flat)
        self.assertEqual(e.flatten(), flat)

    def test_can_include_empty_values_in_flatten(self):
        class MyElement(Element):
            a = Element
            b = Element
            class c(Element):
                a = Element
                b = Element
                c = Element
        flat = {
            'a': 1,
            'b': 2,
            'c': 3,
            'c.a': 4,
            'c.b': 5,
        }
        e = MyElement.from_flat(flat)
        flat[''] = None
        flat['c.c'] = None
        self.assertEqual(e.flatten(include_empty=True), flat)

    def test_flatten_adapts_by_default(self):
        class MyElement(Element):
            adapter = str
        e = MyElement()
        e.value = 1
        self.assertEqual(e.flatten(), {'': '1'})

    def test_can_skip_adapting(self):
        class MyElement(Element):
            adapter = str
        e = MyElement()
        e.value = 1
        self.assertEqual(e.flatten(adapt=False), {'': 1})

    def test_validate_with_no_validators(self):
        e = Element()
        self.assertTrue(e.is_valid())

    def test_can_be_invalid(self):
        calls = []
        def validator(e):
            calls.append(e)
        e = Element.with_attrs(validators=[validator])()
        self.assertFalse(e.is_valid())
        self.assertEqual(calls, [e])

    def test_validator_can_set_errors(self):
        def validator(e):
            e.validation_errors.append(u'Some error')
            return False
        e = Element.with_attrs(validators=[validator])()
        self.assertFalse(e.is_valid())
        self.assertEqual(e.validation_errors, [u'Some error'])

    def test_validator_exceptions_are_recorded_as_errors(self):
        error = TypeError()
        def validator(e):
            raise error
        e = Element.with_attrs(validators=[validator])()
        self.assertFalse(e.is_valid())
        self.assertEqual(e.validation_errors, [error])

    def test_can_be_valid(self):
        e = Element.with_attrs(validators=[lambda e: True])()
        self.assertTrue(e.is_valid())

    def test_multiple_validators_are_called_in_order(self):
        call_order = []
        def validator(order, value):
            def validator(e):
                call_order.append(order)
                return value
            return validator
        validators = [validator(i, i != 1) for i in xrange(3)]
        e = Element.with_attrs(validators=validators)()
        self.assertFalse(e.is_valid())
        self.assertEqual(call_order, range(2))

    def test_validation_is_recursive(self):
        calls = []
        def validator(e):
            calls.append(e)
            return True
        class MyElement(Element):
            validators = [validator]
            class a(Element):
                validators = [validator]
                class b(Element):
                    validators = [validator]
            class b(Element):
                validators = [validator]
        e = MyElement()
        self.assertTrue(e.is_valid())
        self.assertEqual(calls, [e['a']['b'], e['a'], e['b'], e])

    def test_invalid_child_doesnt_stop_recursion(self):
        calls = []
        def validator(value):
            def validator(e):
                calls.append(e)
                return value
            return validator
        class MyElement(Element):
            validators = [validator(True)]
            class a(Element):
                validators = [validator(False)]
                class b(Element):
                    validators = [validator(True)]
            class b(Element):
                validators = [validator(True)]
        e = MyElement()
        self.assertFalse(e.is_valid())
        self.assertEqual(calls, [e['a']['b'], e['a'], e['b'], e])

class TestListOf(unittest.TestCase):
    def test_items_have_correct_path(self):
        class MyElement(Element):
            L = List.of(Element)
        el = MyElement()
        el['L'].append(Element())
        self.assertEqual(el['L'][0].path, 'L.0')

    def test_getting_elements_binds_parent_to_instance(self):
        l = List.of(Element)()
        l.append(Element())
        self.assertIs(l[0].parent, l)

    def test_extract_sub_items(self):
        @List.of
        class MyElement(Element):
            name = 'list'
        flat = dict(('list.%d' % (i,), i) for i in xrange(3))
        flat['list'] = 3
        flats = list(MyElement()._extract_sub_items(flat))
        flats.sort()
        self.assertEqual(flats, [(i, 'list', i) for i in xrange(3)])

    def test_extract_flats(self):
        @List.of
        class MyElement(Element):
            name = 'list'
        flats = list(MyElement()._extract_flats(
            dict(('list.%d' % (i,), i) for i in xrange(3))))
        self.assertEqual(flats, [{'list': i} for i in xrange(3)])

    def test_extract_flats_with_structure(self):
        @List.of
        class MyElement(Element):
            name = 'list'
            a = Element
            b = Element
        flat = {
            'list.0.a': 0,
            'list.0.b': 1,
            'list.1.a': 2,
            'list.1.b': 3,
        }
        flats = list(MyElement()._extract_flats(flat))
        self.assertEqual(flats, [{'list.a': i, 'list.b': i + 1}
                                 for i in xrange(0, 4, 2)])

    def test_from_flat(self):
        class MyElement(Element):
            name = 'list'
        MyList = List.of(MyElement)
        flat = dict(('list.%d' % (i,), i) for i in xrange(3))
        flat['list'] = '1'
        l = MyList.from_flat(flat)
        self.assertTrue(all(isinstance(el, MyElement) for el in l))
        self.assertEqual([el.value for el in l], range(3))
        self.assertEqual(l.value, '1')

    def test_from_flat_with_converter(self):
        class MyElement(Element):
            name = 'list'
            converter = int
        MyList = List.of(MyElement)
        flat = dict(('list.%d' % (i,), i) for i in xrange(3))
        flat['list'] = '1'
        l = MyList.from_flat(flat)
        self.assertTrue(all(isinstance(el, MyElement) for el in l))
        self.assertEqual([el.value for el in l], range(3))
        self.assertEqual(l.value, '1')

    def test_from_flat_with_structure(self):
        class MyElement(Element):
            @List.of
            class l(Element):
                a = Element
                class b(Element):
                    a = Element
            b = Element
        el = MyElement.from_flat({
            'l': 1,
            'l.2.a': 2,
            'l.2.b': 3,
            'l.2.b.a': 4,
            'l.12.a': 5,
            'l.12.b': 6,
            'l.12.b.a': 7,
            'b': 8,
        })
        self.assertEqual(el['l'].value, 1)
        self.assertEqual(el['l'][0]['a'].value, 2)
        self.assertEqual(el['l'][0]['b'].value, 3)
        self.assertEqual(el['l'][0]['b']['a'].value, 4)
        self.assertEqual(el['l'][1]['a'].value, 5)
        self.assertEqual(el['l'][1]['b'].value, 6)
        self.assertEqual(el['l'][1]['b']['a'].value, 7)
        self.assertEqual(el['b'].value, 8)

    def test_flatten(self):
        class MyElement(Element):
            @List.of
            class l(Element):
                a = Element
                class b(Element):
                    a = Element
            b = Element
        flat = {
            'l': 1,
            'l.0.a': 2,
            'l.0.b': 3,
            'l.0.b.a': 4,
            'l.1.a': 5,
            'l.1.b': 6,
            'l.1.b.a': 7,
            'b': 8,
        }
        el = MyElement.from_flat(flat)
        self.assertEqual(el.flatten(), flat)

    def test_validation(self):
        calls = []
        def validator(e):
            calls.append(e)
            return True
        class MyElement(Element):
            validators = [validator]
            @List.of
            class a(Element):
                validators = [validator]
                class b(Element):
                    validators = [validator]
            a = a.with_attrs(validators=[validator])
        e = MyElement()
        e['a'].extend(e['a'].element_type() for _ in xrange(3))
        self.assertTrue(e.is_valid())
        self.assertEqual(calls, [
            e['a'][0]['b'],
            e['a'][0],
            e['a'][1]['b'],
            e['a'][1],
            e['a'][2]['b'],
            e['a'][2],
            e['a'],
            e
        ])

    def test_validation_fails_if_nested_item_fails(self):
        calls = []
        def validator(e):
            valid = (getattr(e, 'name', '') != 'failer')
            calls.append((e, valid))
            return valid
        class MyElement(Element):
            validators = [validator]
            @List.of
            class a(Element):
                validators = [validator]
                class failer(Element):
                    validators = [validator]
            a = a.with_attrs(validators=[validator])
        e = MyElement.from_flat({
            'a.0.failer': 'fail',
        })
        self.assertFalse(e.is_valid())
        self.assertEqual(calls, [
            (e['a'][0]['failer'], False),
            (e['a'][0], True),
            (e['a'], True),
            (e, True),
        ])

    def test_copy_has_same_list_items(self):
        class MyElement(Element):
            name = 'list'
        MyList = List.of(MyElement)
        flat = dict(('list.%d' % (i,), i) for i in xrange(3))
        flat['list'] = '1'
        src = MyList.from_flat(flat)
        l = src.copy()
        self.assertTrue(all(isinstance(el, MyElement) for el in l))
        self.assertEqual([el.value for el in l], range(3))
        self.assertEqual(l.value, '1')

class TestWithAttrs(unittest.TestCase):
    def test_calls_with_attrs_on_argument(self):
        class MyElement(Element):
            pass
        NewElement = with_attrs(MyElement, name='new name')
        self.assertEqual(NewElement.name, 'new name')

    def test_can_be_used_as_decorator(self):
        @with_attrs(name='new name')
        class MyElement(Element):
            pass
        self.assertEqual(MyElement.name, 'new name')

    def test_too_many_args_raises_typeerror(self):
        with self.assertRaises(TypeError) as assertion:
            with_attrs(1, 2)
        self.assertEqual(
            str(assertion.exception),
            'with_attrs() takes exactly 1 argument (2 given)'
        )

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


class SquareSumDifference:
    def sumOfSquares():
        ans = 0
        for i in range(1, 101):
            ans += i**2
        return ans

    def squareOfSums():
        ans = 0
        for i in range(1, 101):
            ans += i
        return ans**2

print(SquareSumDifference.squareOfSums()-SquareSumDifference.sumOfSquares())


"""
parameters는 명령어 뒤에 따라나오는 parameter의 개수를 나타냅니다
    * 0: 없음
    * -1: 1 이상
    * 1~: parameter 개수
"""

prefix = '$'
commands = {
    'bot_help': {
        'parameters': 0,
        'message': ['도움', 'ㄷㅇ', 'help'],
        'help': '명령어 목록과 사용법을 확인합니다'
    },
    'leader': {
        'parameters': 0,
        'message': ['분대장', 'ㅂㄷㅈ', 'leader'],
        'help': '오늘의 분대장 선택 (현재 online인 멤버 중에서 랜덤으로 선택합니다)'
    },
    'ack': {
        'parameters': 0,
        'message': ['ack'],
        'help': '봇의 연결 상태를 확인합니다. TCP 3 way handshake'
    },
    'history': {
        'parameters': 1,
        'message': ['전적', 'ㅈㅈ', 'ㅉ', 'history', 'hist'],
        'help': 'r6stats에 기록되어있는 전적 요약을 가져옵니다'
    },
    'random_ops': {
        'parameters': 0,
        'message': ['랜덤', 'ㄹㄷ', 'random', 'rand'],
        'help': '공격팀, 방어팀에서 랜덤하게 3개의 오퍼를 선택해서 보여줍니다'
    },
    'muzzle': {
        'parameters': 1,
        'message': ['머즐', 'ㅁㅈ', 'muzzle', 'muz'],
        'help': '총구 부착물 추천 참고: https://www.reddit.com/comments/9dk0pm'
    },
    'magical_conch': {
        'parameters': -1,
        'message': ['마법의소라고둥', '마법의소라고둥님', '소라', 'sora', 'conch', 'magical_conch', 'pick'],
        'help': '명령 뒤에 따라오는 공백으로 구분된 문자열 중 하나를 임의로 선택합니다'
    },
    'server_status': {
        'parameters': 0,
        'message': ['서버', '서버상태', '유비가또', '감자서버', 'server', 'serverstatus', 'status', 'potato'],
        'help': 'r6s 서버 상태 리포트 결과를 확인합니다 https://outage.report/rainbow-six'
    },
    'bot_status': {
        'parameters': 0,
        'message': ['봇', '봇상태', 'bot', 'status', 'stat'],
        'help': '봇 상태를 표시합니다'
    },
}