import fixturesUtils
import mayaUtils
import ufeUtils
import usdUtils
import testUtils

import mayaUsd.lib as mayaUsdLib

from pxr import UsdGeom

from maya import cmds
from maya import standalone
from maya.internal.ufeSupport import ufeCmdWrapper as ufeCmd

import ufe

import os
import unittest

class TestObserver(ufe.Observer):
    def __init__(self):
        super(TestObserver, self).__init__()
        self._addedNotifications = 0
        self._removedNotifications = 0
        self._valueChangedNotifications = 0
        self._connectionChangedNotifications = 0
        self._unknownNotifications = 0

    def __call__(self, notification):
        if isinstance(notification, ufe.AttributeAdded):
            self._addedNotifications += 1
        elif isinstance(notification, ufe.AttributeRemoved):
            self._removedNotifications += 1
        elif isinstance(notification, ufe.AttributeValueChanged):
            self._valueChangedNotifications += 1
        elif isinstance(notification, ufe.AttributeConnectionChanged):
            self._connectionChangedNotifications += 1
        else:
            self._unknownNotifications += 1

    def assertNotificationCount(self, test, **counters):
        test.assertEqual(self._addedNotifications, counters.get("numAdded", 0))
        test.assertEqual(self._removedNotifications, counters.get("numRemoved", 0))
        test.assertEqual(self._valueChangedNotifications, counters.get("numValue", 0))
        test.assertEqual(self._connectionChangedNotifications, counters.get("numConnection", 0))
        test.assertEqual(self._unknownNotifications, 0)

class AttributesTestCase(unittest.TestCase):
    '''Verify the Attributes UFE interface, for multiple runtimes.
    '''

    pluginsLoaded = False

    @classmethod
    def setUpClass(cls):
        fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False)

        if not cls.pluginsLoaded:
            cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded()

    @classmethod
    def tearDownClass(cls):
        standalone.uninitialize()

    def setUp(self):
        ''' Called initially to set up the maya test environment '''
        self.assertTrue(self.pluginsLoaded)

        cmds.file(new=True, force=True)

        # Open top_layer.ma scene in testSamples
        mayaUtils.openTopLayerScene()

    def testAttributes(self):
        '''Engine method to run attributes test.'''

        # Get a UFE scene item for one of the balls in the scene.
        ball35Path = ufe.Path([
            mayaUtils.createUfePathSegment("|transform1|proxyShape1"),
            usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")])
        ball35Item = ufe.Hierarchy.createItem(ball35Path)

        # Then create the attributes interface for that item.
        ball35Attrs = ufe.Attributes.attributes(ball35Item)
        self.assertIsNotNone(ball35Attrs)

        # Test that we get the same scene item back.
        self.assertEqual(ball35Item, ball35Attrs.sceneItem())

        # Verify that ball35 contains the visibility attribute.
        self.assertTrue(ball35Attrs.hasAttribute(UsdGeom.Tokens.visibility))

        # Verify the attribute type of 'visibility' which we know is a enum token.
        self.assertEqual(ball35Attrs.attributeType(UsdGeom.Tokens.visibility), ufe.Attribute.kEnumString)

        # Get all the attribute names for this item.
        ball35AttrNames = ball35Attrs.attributeNames

        # Visibility should be in this list.
        self.assertIn(UsdGeom.Tokens.visibility, ball35AttrNames)

    @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 4, 'Test for UFE v4 or later')
    def testAddRemoveAttribute(self):
        '''Test adding and removing custom attributes'''

        ball35Path = ufe.Path([
            mayaUtils.createUfePathSegment("|transform1|proxyShape1"),
            usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")])
        ball35Item = ufe.Hierarchy.createItem(ball35Path)

        # Then create the attributes interface for that item.
        ball35Attrs = ufe.Attributes.attributes(ball35Item)
        self.assertIsNotNone(ball35Attrs)

        ballObserver = TestObserver()
        ball35Attrs.addObserver(ball35Item, ballObserver)
        ballObserver.assertNotificationCount(self, numAdded = 0, numRemoved = 0)

        cmd = ball35Attrs.addAttributeCmd("MyAttribute", ufe.Attribute.kString)
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)
        ballObserver.assertNotificationCount(self, numAdded = 1, numRemoved = 0)

        self.assertIsNotNone(cmd.attribute)
        self.assertIn("MyAttribute", ball35Attrs.attributeNames)
        attr = ball35Attrs.attribute("MyAttribute")
        self.assertEqual(repr(attr),"ufe.AttributeString(<|transform1|proxyShape1,/Room_set/Props/Ball_35.MyAttribute>)")

        cmds.undo()
        ballObserver.assertNotificationCount(self, numAdded = 1, numRemoved = 1)

        self.assertNotIn("MyAttribute", ball35Attrs.attributeNames)
        with self.assertRaisesRegex(KeyError, "Attribute 'MyAttribute' does not exist") as cm:
            with mayaUsdLib.DiagnosticBatchContext(1000) as bc:
                attr = ball35Attrs.attribute("MyAttribute")

        cmds.redo()
        ballObserver.assertNotificationCount(self, numAdded = 2, numRemoved = 1)

        self.assertIn("MyAttribute", ball35Attrs.attributeNames)
        attr = ball35Attrs.attribute("MyAttribute")

        cmd = ball35Attrs.removeAttributeCmd("MyAttribute")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)
        ballObserver.assertNotificationCount(self, numAdded = 2, numRemoved = 2)

        self.assertNotIn("MyAttribute", ball35Attrs.attributeNames)
        with self.assertRaisesRegex(KeyError, "Attribute 'MyAttribute' does not exist") as cm:
            with mayaUsdLib.DiagnosticBatchContext(1000) as bc:
                attr = ball35Attrs.attribute("MyAttribute")
        with self.assertRaisesRegex(ValueError, "Requested attribute with empty name") as cm:
            with mayaUsdLib.DiagnosticBatchContext(1000) as bc:
                attr = ball35Attrs.attribute("")

        cmds.undo()
        ballObserver.assertNotificationCount(self, numAdded = 3, numRemoved = 2)

        self.assertIn("MyAttribute", ball35Attrs.attributeNames)
        attr = ball35Attrs.attribute("MyAttribute")

        cmds.redo()
        ballObserver.assertNotificationCount(self, numAdded = 3, numRemoved = 3)

        self.assertNotIn("MyAttribute", ball35Attrs.attributeNames)
        with self.assertRaisesRegex(KeyError, "Attribute 'MyAttribute' does not exist") as cm:
            with mayaUsdLib.DiagnosticBatchContext(1000) as bc:
                attr = ball35Attrs.attribute("MyAttribute")

    @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 4, 'Test requires remove attribute and its connections feature only available on Ufe v4 or later')
    def testRemoveCompoundAttribute(self):
        '''Test removing compound attributes'''

        # Load a scene with a compound.

        testFile = testUtils.getTestScene("MaterialX", "MayaSurfaces.usda")
        shapeNode,shapeStage = mayaUtils.createProxyFromFile(testFile)

        # Compounds scene item.
        ufeCompound1Item = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG")
        self.assertIsNotNone(ufeCompound1Item)
        ufeCompound2Item = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/NodeGraph1")
        self.assertIsNotNone(ufeCompound2Item)

        # Then create the attributes interface for that item.
        compound1Attrs = ufe.Attributes.attributes(ufeCompound1Item)
        self.assertIsNotNone(compound1Attrs)
        compound2Attrs = ufe.Attributes.attributes(ufeCompound2Item)
        self.assertIsNotNone(compound2Attrs)

        # 1. Remove an output compound attribute.

        # 1.1 Remove an output compound attribute connected to prim and child prim.

        cmd = compound1Attrs.removeAttributeCmd("outputs:baseColor")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("outputs:baseColor", compound1Attrs.attributeNames)

        # Test we removed the connections.
        ufeItemStandardSurface2 = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/standardSurface2")
        self.assertIsNotNone(ufeItemStandardSurface2)
        ufeItemMayaSwizzle = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG/MayaSwizzle_file2_rgb")
        self.assertIsNotNone(ufeItemMayaSwizzle)

        connectionHandler = ufe.RunTimeMgr.instance().connectionHandler(ufeItemStandardSurface2.runTimeId())
        self.assertIsNotNone(connectionHandler)

        connections = connectionHandler.sourceConnections(ufeItemStandardSurface2)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 0)

        connections = connectionHandler.sourceConnections(ufeItemMayaSwizzle)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 1)

        # Test we removed the properties.
        mayaSwizzlePrim = usdUtils.getPrimFromSceneItem(ufeItemMayaSwizzle)
        self.assertIsNotNone(mayaSwizzlePrim)
        self.assertFalse(mayaSwizzlePrim.HasProperty('outputs:out'))
        standardSurface2Prim = usdUtils.getPrimFromSceneItem(ufeItemStandardSurface2)
        self.assertIsNotNone(standardSurface2Prim)
        self.assertFalse(standardSurface2Prim.HasProperty('inputs:base_color'))

        # 1.2 Remove an output compound attribute connected to parent prim.

        cmd = compound2Attrs.removeAttributeCmd("outputs:out")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("outputs:out", compound2Attrs.attributeNames)

        # Test we removed the connections.
        ufeItemParent = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG")
        self.assertIsNotNone(ufeItemParent)
        ufeItemSurface = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/NodeGraph1/surface1")
        self.assertIsNotNone(ufeItemSurface)

        connections = connectionHandler.sourceConnections(ufeItemParent)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 1)

        # Test we removed the properties.
        surfacePrim = usdUtils.getPrimFromSceneItem(ufeItemSurface)
        self.assertIsNotNone(surfacePrim)
        self.assertFalse(surfacePrim.HasProperty('outputs:out'))
        parentPrim = usdUtils.getPrimFromSceneItem(ufeItemParent)
        self.assertIsNotNone(parentPrim)
        self.assertTrue(parentPrim.HasProperty('outputs:out'))

        # 2. Remove an input compound attribute.

        # 2.1 Remove an input compound attribute connected to parent and child prim.

        cmd = compound1Attrs.removeAttributeCmd("inputs:file2:varnameStr")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("inputs:file2:varnameStr", compound1Attrs.attributeNames)

        # Test we removed the connection.
        ufeItemTexture = ufeUtils.createUfeSceneItem(shapeNode,
            "/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG/place2dTexture2")
        self.assertIsNotNone(ufeItemTexture)

        connections = connectionHandler.sourceConnections(ufeItemTexture)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 0)

        connections = connectionHandler.sourceConnections(ufeItemParent)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 1)

        # Test we removed the properties.
        texturePrim = usdUtils.getPrimFromSceneItem(ufeItemTexture)
        self.assertIsNotNone(texturePrim)
        self.assertFalse(texturePrim.HasProperty('inputs:geomprop'))
        self.assertTrue(parentPrim.HasProperty('inputs:file2:varnameStr'))

    @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 4, 'Test for UFE v4 or later')
    def testUniqueNameAttribute(self):
        '''Test unique name attribute'''

        ball35Path = ufe.Path([
            mayaUtils.createUfePathSegment("|transform1|proxyShape1"),
            usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")])
        ball35Item = ufe.Hierarchy.createItem(ball35Path)

        # Create an attribute with name 'MyAttribute'
        ball35Attrs = ufe.Attributes.attributes(ball35Item)
        self.assertIsNotNone(ball35Attrs)

        cmd = ball35Attrs.addAttributeCmd("MyAttribute", ufe.Attribute.kString)
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertIsNotNone(cmd.attribute)
        self.assertIn("MyAttribute", ball35Attrs.attributeNames)
        attr = ball35Attrs.attribute("MyAttribute")
        self.assertEqual(repr(attr),"ufe.AttributeString(<|transform1|proxyShape1,/Room_set/Props/Ball_35.MyAttribute>)")

        # Create another attribute with same name 'MyAttribute'
        cmd = ball35Attrs.addAttributeCmd("MyAttribute", ufe.Attribute.kString)
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertIsNotNone(cmd.attribute)

        # Test the new attribute has name 'MyAttribute1'
        self.assertIn("MyAttribute1", ball35Attrs.attributeNames)
        attr = ball35Attrs.attribute("MyAttribute1")
        self.assertEqual(repr(attr),"ufe.AttributeString(<|transform1|proxyShape1,/Room_set/Props/Ball_35.MyAttribute1>)")

    @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 4, 'Test for UFE v4 or later')
    def testRenamingAttribute(self):
        '''Test renaming an attribute'''

        # Load a scene.

        testFile = testUtils.getTestScene('MaterialX', 'MayaSurfaces.usda')
        shapeNode,shapeStage = mayaUtils.createProxyFromFile(testFile)
        ufeItem = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG')
        self.assertIsNotNone(ufeItem)

        # Then create the attributes interface for that item.
        standardSurfaceAttrs = ufe.Attributes.attributes(ufeItem)
        self.assertIsNotNone(standardSurfaceAttrs)

        # Rename the attribute.
        cmd = standardSurfaceAttrs.renameAttributeCmd("inputs:file2:varnameStr","inputs:file2:varname")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("inputs:file2:varnameStr", standardSurfaceAttrs.attributeNames)
        self.assertIn("inputs:file2:varname", standardSurfaceAttrs.attributeNames)

        # Test undo.
        cmds.undo()
        self.assertIn("inputs:file2:varnameStr", standardSurfaceAttrs.attributeNames)
        self.assertNotIn("inputs:file2:varname", standardSurfaceAttrs.attributeNames)

        # Test redo.
        cmds.redo()
        self.assertNotIn("inputs:file2:varnameStr", standardSurfaceAttrs.attributeNames)
        self.assertIn("inputs:file2:varname", standardSurfaceAttrs.attributeNames)

        # Test the connections.

        ufeItemTexture = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG/place2dTexture2')
        self.assertIsNotNone(ufeItemTexture)

        connectionHandler = ufe.RunTimeMgr.instance().connectionHandler(ufeItemTexture.runTimeId())
        self.assertIsNotNone(connectionHandler)
        connections = connectionHandler.sourceConnections(ufeItemTexture)
        self.assertIsNotNone(connectionHandler)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 1)

        srcAttr = conns[0].src
        dstAttr = conns[0].dst

        self.assertEqual(ufe.PathString.string(srcAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG')
        self.assertEqual(srcAttr.name, 'inputs:file2:varname')

        self.assertEqual(ufe.PathString.string(dstAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG/place2dTexture2')
        self.assertEqual(dstAttr.name, 'inputs:geomprop')

        # Rename the attribute.
        cmd = standardSurfaceAttrs.renameAttributeCmd("outputs:baseColor","outputs:MyColor")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("outputs:baseColor", standardSurfaceAttrs.attributeNames)
        self.assertIn("outputs:MyColor", standardSurfaceAttrs.attributeNames)

         # Test the connections.

        ufeItemStandardSurface = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG/standardSurface2')
        self.assertIsNotNone(ufeItemStandardSurface)

        connectionHandler = ufe.RunTimeMgr.instance().connectionHandler(ufeItemStandardSurface.runTimeId())
        self.assertIsNotNone(connectionHandler)
        connections = connectionHandler.sourceConnections(ufeItemStandardSurface)
        self.assertIsNotNone(connectionHandler)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 1)

        srcAttr = conns[0].src
        dstAttr = conns[0].dst

        self.assertEqual(ufe.PathString.string(srcAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG')
        self.assertEqual(srcAttr.name, 'outputs:MyColor')

        self.assertEqual(ufe.PathString.string(dstAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG/standardSurface2')
        self.assertEqual(dstAttr.name, 'inputs:base_color')

        # Create the SceneItem for a compound with out connection to the parent.
        ufeCompoundItem = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG/NodeGraph1')
        self.assertIsNotNone(ufeCompoundItem)

        # Then create the attributes interface for that item.
        compoundAttrs = ufe.Attributes.attributes(ufeCompoundItem)
        self.assertIsNotNone(compoundAttrs)

        # Rename the attribute.
        cmd = compoundAttrs.renameAttributeCmd("outputs:out", "outputs:out1")
        self.assertIsNotNone(cmd)

        ufeCmd.execute(cmd)

        self.assertNotIn("outputs:out", compoundAttrs.attributeNames)
        self.assertIn("outputs:out1", compoundAttrs.attributeNames)

        # Test the connection.

        ufeParentItem = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG')
        self.assertIsNotNone(ufeParentItem)

        connectionHandler = ufe.RunTimeMgr.instance().connectionHandler(ufeParentItem.runTimeId())
        self.assertIsNotNone(connectionHandler)
        connections = connectionHandler.sourceConnections(ufeParentItem)
        self.assertIsNotNone(connectionHandler)
        conns = connections.allConnections()
        self.assertEqual(len(conns), 2)

        srcAttr = conns[1].src
        dstAttr = conns[1].dst

        self.assertEqual(ufe.PathString.string(srcAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG/NodeGraph1')
        self.assertEqual(srcAttr.name, 'outputs:out1')

        self.assertEqual(ufe.PathString.string(dstAttr.path),
            '|stage|stageShape,/pCube2/Looks/standardSurface2SG')
        self.assertEqual(dstAttr.name, 'outputs:out')

    @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 3, 'clearMetadata is only available in UFE v3 or greater.')
    def testClearNodeGraphAttributeMetadata(self):
        '''Test cleaning a node graph attribute metadata'''

        # Load a scene.

        testFile = testUtils.getTestScene('MaterialX', 'MayaSurfaces.usda')
        shapeNode,shapeStage = mayaUtils.createProxyFromFile(testFile)
        ufeItem = ufeUtils.createUfeSceneItem(shapeNode,
            '/pCube2/Looks/standardSurface2SG/MayaNG_standardSurface2SG')
        self.assertIsNotNone(ufeItem)

        # Then create the attributes interface for that item.
        attrs = ufe.Attributes.attributes(ufeItem)
        self.assertIsNotNone(attrs)
        attr = attrs.attribute('inputs:file2:varnameStr')
        self.assertIsNotNone(attr)

        # Set a metadata for the attribute.
        self.assertTrue(attr.setMetadata('TestMetadata', 'test value'))

        # Clear the metadata for the attribute.
        self.assertTrue(attr.clearMetadata('TestMetadata'))

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


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 17:51:22 2018

@author: alex
"""

a=64
dict = {20: 36, 21: 57}
print(dict)
print(a)
clave_mayor = max(dict.keys())
mayor=dict.get(clave_mayor)
a=mayor
dict ={}
print (dict,a)

    #if ():
    #print(nc,p)


class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        isvalid = lambda row, col: 0 <= row < R  and  0 <= col < C and not visited[row][col]
        DIR = [[0,1],[1,0],[0,-1],[-1,0]]

        queue = collections.deque([(sr, sc)])
        visited = [[False for _ in range(C)] for _ in range(R)]
        color = image[sr][sc]
        while queue:
            row, col = queue.popleft()
            image[row][col] = newColor
            for direction in DIR:
                new_row, new_col = row + direction[0], col + direction[1]
                if isvalid(new_row, new_col) and image[new_row][new_col] == color:
                    visited[new_row][new_col] = True
                    queue.append((new_row, new_col))

        return image


S = list(map(int,input()))
cnt = [0,0]
prev = S[0]
for cur in S[1:]:
  if cur == prev:
    continue
  elif cur != prev:
    cnt[prev] += 1
    prev = cur
cnt[prev] += 1
print(min(cnt))


from __future__ import print_function

from numpy import abs
from numpy import array
from numpy import asarray
from numpy import float32
from numpy import tile

from scipy.sparse import coo_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import diags
from scipy.sparse import vstack as svstack

__author__     = ['Tom Van Mele <vanmelet@ethz.ch>',
                  'Andrew Liew <liew@arch.ethz.ch>']
__copyright__  = 'Copyright 2016, Block Research Group - ETH Zurich'
__license__    = 'MIT License'
__email__      = 'vanmelet@ethz.ch'

__all__ = [
    'adjacency_matrix',
    'degree_matrix',
    'connectivity_matrix',
    'laplacian_matrix',
    'face_matrix',
    'mass_matrix',
    'stiffness_matrix',
    'equilibrium_matrix'
]

def _return_matrix(M, rtype):
    if rtype == 'list':
        return M.toarray().tolist()
    if rtype == 'array':
        return M.toarray()
    if rtype == 'csr':
        return M.tocsr()
    if rtype == 'csc':
        return M.tocsc()
    if rtype == 'coo':
        return M.tocoo()
    return M

def adjacency_matrix(adjacency, rtype='array'):
    a = [(1, i, j) for i in range(len(adjacency)) for j in adjacency[i]]
    data, rows, cols = zip(*a)
    A = coo_matrix((data, (rows, cols))).asfptype()
    return _return_matrix(A, rtype)

def degree_matrix(adjacency, rtype='array'):
    d = [(len(adjacency[i]), i, i) for i in range(len(adjacency))]
    data, rows, cols = zip(*d)
    D = coo_matrix((data, (rows, cols))).asfptype()
    return _return_matrix(D, rtype)

def connectivity_matrix(edges, rtype='array'):
    r"""Creates a connectivity matrix from a list of vertex index pairs.

    The connectivity matrix encodes how edges in a network are connected
    together. Each row represents an edge and has 1 and -1 inserted into the
    columns for the start and end nodes.

    .. math::

        \mathbf{C}_{ij} =
        \cases{
            -1 & if edge i starts at vertex j \cr
            +1 & if edge i ends at vertex j \cr
            0  & otherwise
        }

    Note:
        A connectivity matrix is generally sparse and will perform superior
        in numerical calculations as a sparse matrix.

    Parameters:
        edges (list of list): List of lists [[node_i, node_j], [node_k, node_l]].
        rtype (str): Format of the result, 'array', 'csc', 'csr', 'coo'.

    Returns:
        sparse: If ``rtype`` is ``None``, ``'csc'``, ``'csr'``, ``'coo'``.

        array: If ``rtype`` is ``'array'``.

    Examples:
        >>> connectivity_matrix([[0, 1], [0, 2], [0, 3]], rtype='array')
        [[-1  1  0  0]
         [-1  0  1  0]
         [-1  0  0  1]]

    """
    m    = len(edges)
    data = array([-1] * m + [1] * m)
    rows = array(list(range(m)) + list(range(m)))
    cols = array([edge[0] for edge in edges] + [edge[1] for edge in edges])
    C    = coo_matrix((data, (rows, cols))).asfptype()
    return _return_matrix(C, rtype)

def laplacian_matrix(edges, normalize=False, rtype='array'):
    r"""Creates a laplacian matrix from a list of edge topologies.

    The laplacian matrix is defined as

    .. math::

        \mathbf{L} = \mathbf{C} ^ \mathrm{T} \mathbf{C}

    Note:
        The current implementation only supports umbrella weights,
        as other weighting schemes are not generally applicable.

    See also:
        :func:`compas.datastructures.network.numerical.matrices.network_laplacian_matrix`
        :func:`compas.datastructures.mesh.numerical.matrices.mesh_laplacian_matrix`
        :func:`compas.datastructures.mesh.numerical.matrices.trimesh_cotangent_laplacian_matrix`
        :func:`compas.datastructures.mesh.numerical.matrices.trimesh_positive_cotangent_laplacian_matrix`

    Parameters:
        edges (list of list): List of lists [[node_i, node_j], [node_k, node_l]].
        rtype (str): Format of the result, 'array', 'csc', 'csr', 'coo'.

    Returns:
        sparse: If ''rtype'' is ``None, 'csc', 'csr', 'coo'``.
        array: If ''rtype'' is ``'array'``.

    Examples:
        >>> laplacian_matrix([[0, 1], [0, 2], [0, 3]], rtype='array')
        [[ 3 -1 -1 -1]
         [-1  1  0  0]
         [-1  0  1  0]
         [-1  0  0  1]]

    """
    C = connectivity_matrix(edges, rtype='csr')
    L = C.transpose().dot(C)
    if normalize:
        L = L / L.diagonal().reshape((-1, 1))
        L = csr_matrix(L)
    return _return_matrix(L, rtype)

def face_matrix(face_vertices, rtype='array'):
    """Creates a face-vertex adjacency matrix.

    Parameters:
        face_vertices (list of list) : List of vertices per face.
        rtype (str) : The return type.

    """
    f = array([(i, j, 1) for i, vertices in enumerate(face_vertices) for j in vertices])
    F = coo_matrix((f[:, 2], (f[:, 0], f[:, 1]))).asfptype()
    return _return_matrix(F, rtype)

def mass_matrix(Ct, E, A, l, f=0, c=1, tiled=True):
    r"""Creates a network's nodal mass matrix.

    The mass matrix is defined as the sum of the member axial stiffnesses
    (inline) of the elements connected to each node, plus the force density.
    The force density ensures a non-zero value in form-finding/pre-stress
    modelling where E=0.

    .. math::

        \mathbf{m} =
        |\mathbf{C}^\mathrm{T}|
        (\mathbf{E} \circ \mathbf{A} \oslash \mathbf{l} + \mathbf{f} \oslash \mathbf{l})

    Parameters:
        Ct (sparse): Sparse transpose of the connectivity matrix (n x m).
        E (array): Vector of member Young's moduli (m x 1).
        A (array): Vector of member section areas (m x 1).
        l (array): Vector of member lengths (m x 1).
        f (array): Vector of member forces (m x 1).
        c (float): Convergence factor.
        tiled (boolean): Whether to tile horizontally by 3 for x, y, z.

    Returns:
        array : mass matrix, either (m x 1) or (m x 3).

    """
    ks = E * A / l
    m = c * (abs(Ct).dot(ks + f / l))
    if tiled:
        return tile(m, (1, 3))
    return m

def stiffness_matrix():
    raise NotImplementedError

def equilibrium_matrix(C, xyz, free, rtype='array'):
    r"""Construct the equilibrium matrix of a structural system.

    Note:
        The matrix of vertex coordinates is vectorised to speed up the
        calculations.

    Parameters:
        C (array, sparse): Connectivity matrix (m x n).
        xyz (array, list): Array of vertex coordinates (n x 3).
        free (list): The index values of the free vertices.
        rtype (str): Format of the result, 'array', 'csc', 'csr', 'coo'.

    Returns:
        sparse : If ``rtype`` is ``'csc', 'csr', 'coo'``.
        array : If ``rtype`` is ``'array'``.

    Analysis of the equilibrium matrix reveals some of the properties of the
    structural system, its size is (2ni x m) where ni is the number of free or
    internal nodes. It is calculated by

    .. math::

        \mathbf{E}
        =
        \left[
            \begin{array}{c}
                \mathbf{C}^{\mathrm{T}}_{\mathrm{i}}\mathbf{U} \\[0.3em]
                \hline \\[-0.7em]
                \mathbf{C}^{\mathrm{T}}_{\mathrm{i}}\mathbf{V}
            \end{array}
        \right].

    Examples:
        >>> C = connectivity_matrix([[0, 1], [0, 2], [0, 3]])
        >>> xyz = [[0, 0, 1], [0, 1, 0], [-1, -1, 0], [1, -1, 0]]
        >>> equilibrium_matrix(C, xyz, [0], rtype='array')
            [[ 0.  1. -1.]
             [-1.  1.  1.]]

    """
    xyz = asarray(xyz, dtype=float32)
    C   = csr_matrix(C)
    xy  = xyz[:, :2]
    uv  = C.dot(xy)
    U   = diags([uv[:, 0].flatten()], [0])
    V   = diags([uv[:, 1].flatten()], [0])
    Ct  = C.transpose()
    Cti = Ct[free, :]
    E   = svstack((Cti.dot(U), Cti.dot(V)))
    return _return_matrix(E, rtype)

# ==============================================================================
# Debugging
# ==============================================================================

if __name__ == "__main__":

    import compas
    from compas.datastructures.network import Network

    from scipy.sparse.linalg import spsolve

    class Network(Network):
        def __init__(self, **kwargs):
            super(Network, self).__init__(**kwargs)
            self.dea.update({'q': 1.0})

    network = Network.from_obj(compas.get_data('lines.obj'))

    k_i = dict((key, index) for index, key in network.vertices_enum())
    i_k = dict(network.vertices_enum())
    xyz = [network.vertex_coordinates(key) for key in network]
    edges = [(k_i[u], k_i[v]) for u, v in network.edges_iter()]
    n = len(xyz)
    m = len(edges)
    fixed = [k_i[key] for key in network.leaves()]
    free = list(set(range(n)) - set(fixed))
    q = [float(1.0) for i in range(m)]

    ij_q = dict(((k_i[u], k_i[v]), attr['q']) for u, v, attr in network.edges_iter(True))
    ij_q.update(((k_i[v], k_i[u]), attr['q']) for u, v, attr in network.edges_iter(True))

    xyz = array(xyz)

    C = connectivity_matrix(edges, 'csr')
    Q = diags([q], [0])
    Ci = C[:, free]
    Cf = C[:, fixed]

    Cit = Ci.transpose()

    CitQCi = Cit.dot(Q).dot(Ci)
    CitQCf = Cit.dot(Q).dot(Cf)

    print(CitQCf.dot(xyz[fixed]))

    CtQC = [[0.0 for j in range(n)] for i in range(n)]

    for i in range(n):
        key = i_k[i]
        Q = 0
        for nbr in network.neighbours(key):
            j = k_i[nbr]
            q = ij_q[(i, j)]
            Q += q
            CtQC[i][j] = - q
        CtQC[i][i] = Q

    CitQCi = [[CtQC[i][j] for j in free] for i in free]
    CitQCf = [[CtQC[i][j] for j in fixed] for i in free]

    CtQC = array(CtQC)

    CitQCi = csr_matrix(array(CitQCi))
    CitQCf = csr_matrix(array(CitQCf))

    xyz[free] = spsolve(CitQCi, - CitQCf.dot(xyz[fixed]))

    for key, attr in network.vertices_iter(True):
        index = k_i[key]
        attr['x'] = xyz[index, 0]
        attr['y'] = xyz[index, 1]

    vlabel = dict((key, str(index)) for index, key in network.vertices_enum())
    elabel = dict(((u, v), str(index)) for index, u, v in network.edges_enum())

    network.plot(vlabel=vlabel, elabel=None)


# Xander Kehoe
import time
maleValues = [1375, 2047, 2233, 2559, 3265]
femaleValues = [945, 2479, 3007, 3398, 4415]

def drawLine(t, x1, y1, x2, y2, colorP="black"):  # Basic method to draw lines
    t.up()
    t.goto(x1, y1)
    t.down()
    t.pencolor(colorP)
    t.goto(x2, y2)

def drawLineWithDots(t, x1, y1, x2, y2, colorP="black"):  # Basic method to draw lines with dots at each end
    t.pencolor(colorP)
    t.up()
    t.goto(x1, y1)
    t.dot(5)
    t.down()
    t.goto(x2, y2)
    t.dot(5)

def drawTickMarks(t):
    for i in range(6):  # Drawing vertical x marks
        drawLine(t, 40*i, 0, 40*i, 10)
    drawLine(t, 0, max(maleValues)/15, 10, max(maleValues)/15)  # Drawing maximum y mark for male
    drawLine(t, 0, max(femaleValues)/15, 10, max(femaleValues)/15)  # Drawing maximum y mark for female
    drawLine(t, 0, min(maleValues)/15, 10, min(maleValues)/15)  # Drawing minimal y mark for male
    drawLine(t, 0, min(femaleValues)/15, 10, min(femaleValues)/15)  # Drawing minimal y mark for female

def displayText(t):
    t.pencolor("black")
    t.up()
    t.goto(-3, (max(maleValues)/15)-10)
    t.write(max(maleValues), align="right")  # Writing maximum y value at max y mark for male
    t.goto(-3, (max(femaleValues)/15) - 10)
    t.write(max(femaleValues), align="right")  # Writing maximum y value at max y mark for female
    t.goto(-3, (min(maleValues)/15)-10)
    t.write(min(maleValues), align="right")  # Writing minimum y value at min y mark for male
    t.goto(-3, (min(femaleValues)/15) - 10)
    t.write(min(femaleValues), align="right")  # Writing minimum y value at min y mark for female
    x = 40
    for i in range(1970, 2011, 10):  # Writing years 1970-2010
        t.goto(x, -20)
        t.write(str(i), align="center")
        x += 40
    t.goto(0, -50)
    t.write("Two-year College Enrollment (in thousands)")  # Writing Title

def main():
    import turtle as t

    t.hideturtle()

    drawLine(t, 0, 0, 200, 0)
    drawLine(t, 0, 0, 0, 400)

    for i in range(1, 5):  # Drawing lines for male
        drawLineWithDots(t, 40*i, maleValues[i-1]/15, 40*(i+1), maleValues[i]/15, "blue")
    for i in range(1, 5):  # Drawing lines for female
        drawLineWithDots(t, 40*i, femaleValues[i-1]/15, 40*(i+1), femaleValues[i]/15, "red")
    drawTickMarks(t)
    displayText(t)
    time.sleep(15)  # Delay to allow user to actually look at chart so it doesn't immediately close

main()


def werewolf(numeral):
    text_numeral = str(numeral)
    before , after = text_numeral.split('.')
    even_one = list(before)
    even_one.reverse()
    new_before = ''.join(even_one)
    even_two = list(after)
    even_two.reverse()
    new_after = ''.join(even_two)
    new_number = float(f'{new_before}.{new_after}')
    return new_number

number_one = float(input('Введите первое число: '))
number_two = float(input('Введите второе число: '))
revers_one = werewolf(number_one)
revers_two = werewolf(number_two)
print(f'\nПервое число наоборот:{revers_one}')
print(f'Второе число наоборот:{revers_one}')
print(f'\nСумма:{revers_one + revers_two}')


# coding: utf-8

"""
Casino - Roulette
"""

from turtle import *
import random
from datetime import datetime, timedelta
import math

STARTUP = 1
RUNNING = 2
DONE = 3

COLOR_BLACK = "black"
COLOR_BROWN = "brown"
COLOR_GREEN = "green"
COLOR_BLUE = "blue"
COLOR_RED = "red"
COLOR_YELLOW = "yellow"
COLOR_WHITE = "white"

FONT_SCORE = ("Arial", 10, "bold")
FONT_SCORE_TITLE = ("Arial", 16, "bold")
FONT_BUTTON = ("Arial", 20, "normal")
FONT_CHIP = ("Arial", 10, "normal")
FONT_RO_SLOT = ("Arial", 8, "normal")
FONT_BET_TEXT = ("Arial", 16, "bold")

CHIPS = [1, 2, 10, 50]
RONUMS = [34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26, 0, 32, 15, 19, 4, 21, 2, 25, 17]

def in_range(x, y, x1, y1, x2, y2):
    return max(x1, x2) >= x >= min(x1, x2) and max(y1, y2) >= y >= min(y1, y2)

def write_txt(tt, x, y, text, font, color=COLOR_BLACK):
    tt.pencolor(color)
    tt.up()
    tt.goto(x, y)
    tt.down()
    tt.write(text, font=font)

def draw_chip(tt, x, y, heading, r, fgcol, bgcol, num):
    tt.up()
    tt.goto(x, y)
    tt.seth(heading)
    tt.down()
    tt.color(fgcol, bgcol)
    tt.begin_fill()
    tt.circle(r, 360)
    tt.end_fill()
    n = 0
    k = num
    while k // 10 > 0:
        n = n + 1
        k = k / 10
    dx = -3.5 * n
    dy = 8
    write_txt(tt, x + dx, y + dy, str(num), font=FONT_CHIP)

def draw_rect(tt, x, y, w, h, fgcol, bgcol, filled=False):
    tt.color(fgcol, bgcol)
    tt.up()
    tt.goto(x, y)
    tt.down()
    if filled:
        tt.begin_fill()
    tt.seth(0)
    tt.forward(w)
    tt.left(90)
    tt.forward(h)
    tt.left(90)
    tt.forward(w)
    tt.left(90)
    tt.forward(h)
    if filled:
        tt.end_fill()

class Ball:
    def __init__(self, ro_idx=0):
        self.ro_idx = ro_idx
        self.t = Turtle()
        self.t.shape("circle")
        self.t.color(COLOR_BLACK, COLOR_BROWN)
        self.X = -300
        self.Y = 200
        self.R = 170
        self.ball_pos = []
        for i in range(37):
            a = i * 360 / 37 + 5
            x = self.R * math.cos((360-a) * math.pi / 180) + self.X
            y = self.R * math.sin((360-a) * math.pi / 180) + self.Y
            self.ball_pos.append((x, y))

    def get_last_ro_index(self):
        return self.ro_idx

    def update(self, ro_idx):
        self.ro_idx = ro_idx
        tracer(True)
        self.t.up()
        self.t.goto(self.ball_pos[ro_idx])
        self.t.down()
        tracer(False)

class Score:
    def __init__(self):
        self.t = Turtle()
        self.X = 310
        self.Y = 360
        self.W = 30

    def update(self, total_score):
        self.t.clear()
        # get 6-digit number from score
        scores = [0] * 6
        n = total_score
        for i in range(6):
            scores[5 - i] = int(n % 10)
            n = n // 10
        # write title string
        write_txt(self.t, self.X, self.Y + 10, "SCORE:", font=FONT_SCORE_TITLE)
        for i in range(6):
            self.t.up()
            self.t.goto(self.X + 30 * i, self.Y)
            self.t.down()
            # draw box
            for _ in range(4):
                self.t.forward(self.W)
                self.t.right(90)
            # write number in box
            write_txt(self.t, self.X + self.W * i + 10, self.Y - 25, str(scores[i]), font=FONT_SCORE)
        self.t.ht()

class Button:
    def __init__(self):
        self.t = Turtle()
        self.X = -495
        self.Y = -195
        self.W = 155
        self.H = 40

    def clickable(self, x, y):
        return in_range(x, y, self.X, self.Y, self.X + self.W, self.Y + self.H)

    def update(self, state):
        # draw button
        #
        # background is green means button is clickable, otherwise it unable to click.
        # background is green when state are STARTUP/DONE
        #
        txt = ""
        filled = True
        if state == STARTUP:
            txt = "Start"
        elif state == RUNNING:
            filled = False
            txt = "Running "
        elif state == DONE:
            txt = "New Round"
        self.t.reset()
        dx = (self.W - len(txt)*15.5) / 2
        draw_rect(self.t, self.X, self.Y, self.W, self.H, COLOR_GREEN, COLOR_GREEN, filled)
        write_txt(self.t, self.X + dx, self.Y, txt, font=FONT_BUTTON)
        self.t.ht()

class Chip:
    def __init__(self, chip_idx=0):
        self.t = Turtle()
        self.X = 310
        self.Y = -195
        self.R = 20
        self.chip_idx = chip_idx

    def clickable(self, x, y):
        for i in range(4):
            if in_range(x, y, self.X + i * 50 - self.R, self.Y, self.X + i * 50 + self.R, self.Y + 2 * self.R):
                return True
        return False

    def get_chip_value(self):
        return CHIPS[self.chip_idx]

    def choose(self, x, y):
        chip_idx = -1
        for i in range(4):
            if in_range(x, y, self.X + i * 50 - self.R, self.Y, self.X + i * 50 + self.R, self.Y + 2 * self.R):
                chip_idx = i
                break
        if self.chip_idx != chip_idx:
            self.chip_idx = chip_idx
            self.update(STARTUP)

    def update(self, state):
        # draw chip
        #
        # background color is green means chip is clickable.
        # pencolor is red means chip has been chosen.
        #
        self.t.clear()
        pencols = [COLOR_BLACK] * 4
        bgcols = [COLOR_GREEN] * 4
        for i in range(4):
            pencol = COLOR_RED if i == self.chip_idx else pencols[i]
            bgcol = COLOR_YELLOW if i == self.chip_idx else bgcols[i]
            if state == RUNNING or state == DONE:
                bgcol = COLOR_WHITE
            draw_chip(self.t, self.X + i * 50, self.Y, 0, self.R, pencol, bgcol, CHIPS[i])
        self.t.ht()

class Table:
    def __init__(self, tot_chips):
        self.t = Turtle()
        self.tot_score = tot_chips
        self.bet_pos = [[0, 0, 0, 0]] * 44
        self.bets = [0] * 44
        self.X_NUM = -110
        self.Y_NUM = 20
        self.W_NUM = 50
        self.H_NUM = 50
        self.X_1ST = -110
        self.Y_1ST = 70
        self.W_1ST = 200
        self.H_1ST = 50
        self.X_EVEN = -110
        self.Y_EVEN = -130
        self.W_EVEN = 150
        self.H_EVEN = 50
        self.R_CHIP = 20

        # POS [0]
        self.bet_pos[0] = [self.X_NUM - 50, self.Y_NUM - 50, self.W_NUM, self.H_NUM]
        # POS [1-37]
        for i in range(12):
            for j in range(3):
                self.bet_pos[i * 3 + j + 1] = [self.X_NUM + i * 50, self.Y_NUM - j * 50, self.W_NUM, self.H_NUM]
        # POS [1st,2nd,3rd]
        for i in range(3):
            self.bet_pos[37 + i] = [self.X_1ST + i * self.W_1ST, self.Y_1ST, self.W_1ST, self.H_1ST]
        # POS [Een,Red,Odd,Black]
        for i in range(4):
            self.bet_pos[40 + i] = [self.X_EVEN + i * self.W_EVEN, self.Y_EVEN, self.W_EVEN, self.H_EVEN]

    def draw_win_pos(self, idx):
        # draw red box in the position
        for i in range(44):
            if idx == i:
                draw_rect(self.t,
                          self.bet_pos[i][0] + 5,
                          self.bet_pos[i][1] + 5,
                          self.bet_pos[i][2] - 10,
                          self.bet_pos[i][3] - 10,
                          COLOR_RED, COLOR_GREEN, False)

    def clickable(self, x, y):
        for i in range(44):
            if in_range(x, y,
                        self.bet_pos[i][0],
                        self.bet_pos[i][1],
                        self.bet_pos[i][0] + self.bet_pos[i][2],
                        self.bet_pos[i][1] + self.bet_pos[i][3]):
                return True
        return False

    def place_bet(self, x, y, chip_value):
        if self.tot_score >= chip_value:
            for i in range(44):
                if in_range(x, y,
                            self.bet_pos[i][0],
                            self.bet_pos[i][1],
                            self.bet_pos[i][0] + self.bet_pos[i][2],
                            self.bet_pos[i][1] + self.bet_pos[i][3]):
                    self.bets[i] = self.bets[i] + chip_value
                    self.tot_score = self.tot_score - chip_value
                    pos = self.get_bet_pos(i)
                    draw_chip(self.t, pos[0], pos[1], 0, self.R_CHIP, COLOR_BLACK, COLOR_YELLOW, self.bets[i])
                    return i
        return -1

    def get_bet_pos(self, idx):
        x = self.bet_pos[idx][0]
        y = self.bet_pos[idx][1]
        w = self.bet_pos[idx][2]
        h = self.bet_pos[idx][3]
        return x + w / 2, y + h / 2 - self.R_CHIP

    def get_total_score(self):
        return self.tot_score

    def get_bet_amount(self):
        tot = 0
        for i in range(44):
            if self.bets[i] > 0:
                tot = tot + self.bets[i]
        return tot

    def update(self, state, ro_idx):
        ro_num = RONUMS[ro_idx]
        self.t.clear()
        # draw bounding box
        draw_rect(self.t, -500, -200, 1000, 600, COLOR_BLACK, COLOR_BLACK, False)
        # draw bet table
        bg_color = COLOR_GREEN if state == STARTUP else COLOR_WHITE
        self.draw_table(bg_color)
        if state == STARTUP:
            # clear bets
            self.bets = [0] * 44
        elif state == RUNNING:
            # draw bets
            for i in range(44):
                if self.bets[i] > 0:
                    pos = self.get_bet_pos(i)
                    draw_chip(self.t, pos[0], pos[1], 0, self.R_CHIP, COLOR_BLACK, COLOR_YELLOW, self.bets[i])
        elif state == DONE:
            # calculate profits and draw win bets
            for i in range(44):
                is_win_pos = False
                if i == ro_num and 36 >= i >= 0:
                    self.bets[i] = self.bets[i] * 35
                    is_win_pos = True
                elif i == 37 and 12 >= ro_num >= 1:
                    self.bets[i] = self.bets[i] * 3
                    is_win_pos = True
                elif i == 38 and 24 >= ro_num >= 13:
                    self.bets[i] = self.bets[i] * 3
                    is_win_pos = True
                elif i == 39 and 36 >= ro_num >= 25:
                    self.bets[i] = self.bets[i] * 3
                    is_win_pos = True
                elif (i == 40 or i == 41) and ro_num % 2 == 1:
                    self.bets[i] = self.bets[i] * 2
                    is_win_pos = True
                elif (i == 42 or i == 43) and ro_num % 2 == 0:
                    self.bets[i] = self.bets[i] * 2
                    is_win_pos = True
                else:
                    self.bets[i] = 0
                if is_win_pos:
                    self.draw_win_pos(i)
                if self.bets[i] > 0:
                    self.tot_score = self.tot_score + self.bets[i]
                    if self.tot_score > 999999:
                        self.tot_score = 999999
                    pos = self.get_bet_pos(i)
                    draw_chip(self.t, pos[0], pos[1], 0, self.R_CHIP, COLOR_BLACK, COLOR_YELLOW, self.bets[i])
        self.t.ht()
        return

    def draw_table(self, bgcol):
        for i in range(44):
            draw_rect(self.t,
                      self.bet_pos[i][0],
                      self.bet_pos[i][1],
                      self.bet_pos[i][2],
                      self.bet_pos[i][3],
                      COLOR_BLACK, bgcol, True)

            x = self.get_bet_pos(i)[0] - 10
            y = self.get_bet_pos(i)[1] + 5
            c = COLOR_BLACK
            txt = ""
            if 36 >= i >= 0:
                txt = str(i)
                dx = 10 if i < 10 else 0
                x = x + dx
                c = COLOR_BLACK if i % 2 == 0 else COLOR_RED
            elif i == 37:
                txt = "1st"
            elif i == 38:
                txt = "2nd"
            elif i == 39:
                txt = "3rd"
            elif i == 40:
                txt = "Even"
                c = COLOR_RED
            elif i == 41:
                txt = "Red"
                c = COLOR_RED
            elif i == 42:
                txt = "Odd"
            elif i == 43:
                txt = "Black"
            write_txt(self.t, x, y, txt, font=FONT_BET_TEXT, color=c)

class Roulette:
    def __init__(self):
        self.t = Turtle()

    def update(self):
        self.t.clear()
        self.draw_roulette()
        self.t.ht()

    def draw_dot(self, slot_pos, heading, r, a, col):
        self.t.up()
        self.t.goto(slot_pos)
        self.t.seth(heading)
        self.t.down()
        self.t.circle(r, a)
        self.t.dot(10, col)
        return self.t.pos(), self.t.heading()

    def draw_roulette(self):
        a = 360 / 37
        (pos1, head1) = ((-100, 200), 90)
        (pos2, head2) = ((-120, 200), 90)
        (pos3, head3) = ((-140, 200), 90)
        for i in range(37):
            old_pos2 = pos2
            # draw arc
            (pos1, head1) = self.draw_dot(pos1, head1, 200, a, COLOR_BLUE)
            (pos2, head2) = self.draw_dot(pos2, head2, 180, a, COLOR_RED)
            (pos3, head3) = self.draw_dot(pos3, head3, 160, a, COLOR_GREEN)
            # draw line
            self.t.up()
            self.t.goto(pos1)
            self.t.down()
            self.t.goto(pos3)
            # write number (0-36)
            dx = 3.5 if i < 10 else 7
            dy = 8
            x = (pos1[0] + old_pos2[0]) / 2 - dx
            y = (pos1[1] + old_pos2[1]) / 2 - dy
            self.t.up()
            self.t.goto(x, y)
            self.t.down()
            ro_num = RONUMS[36 - i]
            c = COLOR_RED if ro_num % 2 == 1 else COLOR_BLACK
            write_txt(self.t, x, y, str(ro_num), font=FONT_RO_SLOT, color=c)

class Game:
    def __init__(self):
        self.table = Table(10000)
        self.ro = Roulette()
        self.chip = Chip()
        self.score = Score()
        self.command = Button()
        self.ball = None
        self.ro_end_time = datetime.today()
        self.state = STARTUP

    def tick(self):
        if self.state == RUNNING and self.ro_end_time >= datetime.today():
            # move ball to next position
            tracer(True)
            ro_idx = self.ball.get_last_ro_index() + 1
            if ro_idx == 37:
                ro_idx = 0
            self.ball.update(ro_idx)

            if datetime.today().second == self.ro_end_time.second:
                # it is the end time, the ball stop running
                self.state = DONE
                self.update(self.ball.get_last_ro_index())
        ontimer(self.tick, 10)

    def onclick(self, x, y):
        if self.chip.clickable(x, y):
            if self.state == STARTUP:
                # selected chip
                self.chip.choose(x, y)

        if self.table.clickable(x, y):
            if self.state == STARTUP:
                # placed bets, update score
                self.table.place_bet(x, y, self.chip.get_chip_value())
                self.score.update(self.table.get_total_score())

        if self.command.clickable(x, y):
            if self.state == DONE:
                # start next round, clear table
                self.state = STARTUP
                self.update(self.ball.get_last_ro_index())

            elif self.state == STARTUP:
                if self.table.get_bet_amount() > 0:
                    # stop bet
                    self.state = RUNNING
                    self.update(self.ball.get_last_ro_index())
                    # set the end time, the ball stops rotating at the time
                    self.ro_end_time = datetime.today() + timedelta(seconds=random.randint(8, 12))

    def update(self, ro_idx, demo=False):
        tracer(demo)
        self.table.update(self.state, ro_idx)
        self.ro.update()
        self.chip.update(self.state)
        self.score.update(self.table.get_total_score())
        self.command.update(self.state)
        if not self.ball:
            self.ball = Ball()
        self.ball.update(ro_idx)

    def run(self):
        # To show drawing process, set "demo=True"
        self.update(ro_idx=28, demo=False)
        onscreenclick(self.onclick, btn=1)
        self.tick()
        # Turtle().getscreen().getcanvas().postscript(file="roulette.eps")

def main():
    game = Game()
    game.run()
    return "EVENTLOOP"

if __name__ == '__main__':
    main()
    mainloop()


import logging
import sys
from logging.handlers import TimedRotatingFileHandler
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
LOG_FILE = "bilibili-following.log"

def get_console_handler():
   console_handler = logging.StreamHandler(sys.stdout)
   console_handler.setFormatter(FORMATTER)
   warn_filter = logging.Filter()
   warn_filter.filter = lambda record: record.levelno >= logging.WARNING
   console_handler.addFilter(warn_filter)
   return console_handler
def get_file_handler():
   file_handler = TimedRotatingFileHandler(LOG_FILE, when='midnight',encoding='utf-8')
   file_handler.setFormatter(FORMATTER)
   return file_handler
def get_logger(logger_name):
   logger = logging.getLogger(logger_name)
   logger.setLevel(logging.DEBUG)
   logger.addHandler(get_console_handler())
   logger.addHandler(get_file_handler())
   logger.propagate = False
   return logger


import os

from django import VERSION

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'abc123'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
]

if VERSION >= (2, 0):
    MIDDLEWARE = MIDDLEWARE_CLASSES

ROOT_URLCONF = 'myapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

if VERSION >= (1, 5):
    AUTH_USER_MODEL = 'user.CustomUser'
    INSTALLED_APPS.append('user')


#Your task in this exercise is to define a function make_ing_form() which given a verb
#in infinitive form returns its present participle form. Test your function
#with words such as lie, see, move and hug. However, you must not expect such simple
#rules to work for all cases.

verb = input("Please input a verb in the infinitive form. This verb will be converted to present participle tense: ")
#This is where the user shall input the infinitive word such as lie, see, move, hug
import re
#This will allow for the use of re.sub
consonant = "bcdfghjklmnpqrstvwxyz"
#This will be used later on during one of the elif statements
vowel = "aeiou"
#This will be used later on during one of the elif statements
def make_ing_form(verb):
    if verb == 'be' or verb == 'see' or verb == 'flee' or verb == 'knee':
        #This if statement is used for cases that do are exceptions to the rule, for words ending with e
       return verb + "ing"
    else:
       if verb.endswith("ie"):
           #if the verb ends with ie, then remove ie and add y and ing
          new_verb = re.sub('ie$', 'y', verb)
          return new_verb + "ing"
       elif verb.endswith("e"):
           #elif the verb ends with e, then remove the e and add ing
          new_verb = re.sub('e$', 'ing', verb)
          return new_verb
       elif verb[-2] in vowel and verb[-1] in consonant and verb[-3] in consonant and verb[-1] != 'w':
           #elif the verb ends with consonant, vowel, consonant
          new_verb = verb + verb[-1] + 'ing'
          return new_verb
       else:
           #if the verb does not fit in any of the other categories
          return verb + "ing"

print (make_ing_form(verb))


import unittest

class Solution:
    def __init__(self):
        self.stack = []

    def combination(self, arr, offset, length, k, result):
        if k == 0:
            result.append([''.join(self.stack[:])])
            return
        for i in range(offset, length):
            self.stack.append(arr[i])
            self.combination(arr, i, length, k - 1, result)
            self.stack.pop()

class TestCombination(unittest.TestCase):
    def test(self):
        sol = Solution()
        arr = ['A', 'B', 'C']
        result = []
        sol.combination(arr, 0, len(arr), 2, result)
        self.assertEqual(
            result,
            [
                ['AA'],
                ['AB'],
                ['AC'],
                ['BB'],
                ['BC'],
                ['CC'],
            ]
        )
        result = []
        sol.combination(arr, 0, len(arr), 3, result)
        self.assertEqual(
            result,
            [
                ['AAA'],
                ['AAB'],
                ['AAC'],
                ['ABB'],
                ['ABC'],
                ['ACC'],
                ['BBB'],
                ['BBC'],
                ['BCC'],
                ['CCC'],
            ]
        )

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


# https://leetcode.com/problems/move-zeroes
# O(N) T | O(1) S

def move_zeroes(nums: list[int]) -> None:
    left = 0
    for right in range(len(nums)):
        if nums[right] == 0:
            continue
        nums[left], nums[right] = nums[right], nums[left]
        left += 1
    return nums