import sys
import os, datetime
import xbmc, xbmcgui, xbmcaddon, xbmcplugin, xbmcvfs

__addon__        = xbmcaddon.Addon()
__addonid__      = __addon__.getAddonInfo('id')
__addonversion__ = __addon__.getAddonInfo('version')
__language__     = __addon__.getLocalizedString

Addon_Data_Path = os.path.join( xbmc.translatePath("special://profile/addon_data/%s" % __addonid__ ).decode("utf-8") )
def log(txt):
    if isinstance(txt, str):
        txt = txt.decode("utf-8")
    message = u'%s: %s' % (__addonid__, txt)
    xbmc.log(msg=message.encode("utf-8"), level=xbmc.LOGDEBUG)

def startPlaylist():
    if not xbmc.getCondVisibility("Player.HasMedia"):
        playlistpath = __addon__.getSetting("playlistpath")
        if xbmcvfs.exists(playlistpath):
            xbmc.Player().play(playlistpath)
            xbmcPlaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            xbmcPlaylist.shuffle()

class Daemon:
    def __init__( self ):
        log("version %s started" % __addonversion__ )
        self.Player = BgMusic_Player( enabled = True )
        self.run_backend()

    def run_backend(self):
        self._stop = False
        xbmc.sleep(1000)
        startPlaylist()
        while (not self._stop) and (not xbmc.abortRequested):
            if __addon__.getSetting("playonce") == "false":
                log("start playlist")
                startPlaylist()
                xbmc.sleep(1000)
            log("backend active")
            xbmc.sleep(1000)

class BgMusic_Player( xbmc.Player ):
    def __init__(self, *args, **kwargs):
        xbmc.Player.__init__( self )
        self.enabled = kwargs['enabled']

    def onPlayBackEnded( self ):
        # Will be called when xbmc stops playing a file
        if not __addon__.getSetting("playonce") == "false":
            pass

    def onPlayBackStopped( self ):
        # Will be called when user stops xbmc playing a file
        if not __addon__.getSetting("playonce") == "false":
            pass

if ( __name__ == "__main__" ):
    Daemon()
log('finished')


"""Attenuation Object
=====================

Defines the abstract `AttenuationObject` class and provides basic
implementations of this class for some simple shapes.

"""
from abc import ABC, abstractmethod

import numpy as np
import scipy as sp
import scipy.integrate

class AttenuationObject(ABC):
    """Abstract class for an attenuation object.

    An abstract class is a way of define what a set of objects should do,
    without explicitly implementing them all individually.

    """

    @abstractmethod
    def attenuation(self, x: float, y: float) -> float:
        """Return the attenuation factor μ at the point `(x, y)` in the
        original Cartesian coordinates.

        Note that this function is *abstract* meaning that the sub-class must
        implement this method.

        """

    def project_attenuation(
        self, theta: float, xi: float, eta_range: (float, float)
    ) -> float:
        """Return the integrated attenuation factor for a given xi and theta
        value.

        The integration is done along the specified range of eta values.

        """
        # Although we don't know what the underlying object is (as this is an
        # abstract class), we know that we will be able get the attenuation at
        # a given `(x, y)` coordinate.  Based on this alone, we can calculate
        # the projected attenuation.
        def integrand_eta(eta):
            x = xi * np.cos(theta) + eta * np.sin(theta)
            y = eta * np.cos(theta) -  xi * np.sin(theta)
            #this gives us the attenuation factor for a specific x and y in the
            #eta and xi coordinates
            return (self.attenuation(x , y))
        #Gives an integrand across all of eta
        return (sp.integrate.quad(integrand_eta,eta_range[0],eta_range[1])[0])

    def to_array(self, x, y):
        """Create a 2D array in the `(x, y)` coordinate of the attenuation.

        With the entries corresponding the the attenuation at the location.  No
        projection is done here, this function just creates a 2D 'image' of the
        projection over the specified range.

        """
        data = np.zeros((x.size, y.size), dtype=float)
        for idx in np.ndindex(data.shape):
            data[idx] = self.attenuation(x[idx[0]], y[idx[1]])

        return data

class Rectangle(AttenuationObject):
    """Implementat the `AttenuationObject` for a rectangle."""

    def __init__(
        self, x1: float, x2: float, y1: float, y2: float, attenuation_factor: float
    ):
        """Create a new Rectangle object bounded by `x1` and `x2` in the
        `x`-axis, and `y1` and `y2` in the `y`-axis.

        """
        self.x1 = min(x1, x2)
        self.x2 = max(x1, x2)
        self.y1 = min(y1, y2)
        self.y2 = max(y1, y2)
        self.attenuation_factor = attenuation_factor

    def attenuation(self, x, y):
        if self.x1 <= x <= self.x2 and self.y1 <= y <= self.y2:
            return self.attenuation_factor
        else:
            return 0

class Circle(AttenuationObject):
    """Implementat the `AttenuationObject` for a circle."""

    def __init__(self, x0, y0, r, attenuation_factor):
        """Create a new Circle object centered on `(x0, y0)` with radius `r`
        and the specified `attenuation_factor`."""
        self.x0 = x0
        self.y0 = y0
        self.r = abs(r)
        self.attenuation_factor = attenuation_factor

    def attenuation(self, x, y):

        if (np.sqrt((x - self.x0)**2 + (y - self.y0)**2)) <= self.r:
            return self.attenuation_factor
        else:
            return 0

class ObjectCollection(AttenuationObject):
    """Implementat the `AttenuationObject` for a collection of objects."""

    def __init__(self):
        self.objects = []

    def append(self, obj):
        """Add a new object to the collection."""
        if not isinstance(obj, AttenuationObject):
            raise RuntimeError("Object must be an AttenuationObject.")

        self.objects.append(obj)

    def attenuation(self, x, y):
        """Return the overall attenuation from all objects in the
        collection."""
        attenuation = 0
        for obj in self.objects:
            attenuation += obj.attenuation(x, y)
        return attenuation

class ImageObject(AttenuationObject):
    """Implement the `AttenuationObject` for images.

    The image is rescaled so that if fits within the `[-1, 1]^2`.  For a square
    image, this means that the coordinate `(-1, -1)` will correspond to the
    lower left corner, and the coordinate `(1, 1)` corresponds to the upper
    right corner.

    """

    def __init__(self, image):
        self.image = image.copy().convert(mode="L")
        self.width, self.height = self.image.size
        self.scale_factor = max(self.width, self.height) / 2

    def attenuation(self, x, y):
        # We scale the input (x, y) coordinates so the correspond to a pixel
        # index.
        x *= self.scale_factor
        y *= self.scale_factor

        x += self.width / 2
        y += self.height / 2

        # Get the pixel as the desired point if we're in the image, otherwise
        # return 0.
        if 0 <= x < self.width and 0 <= y < self.height:
            return self.image.getpixel((x, y))
        return 0


import sys, pygame

from alien  import Alien
from bullet import Bullet
from time   import sleep

def ship_hit(settings, stats, screen, ship, aliens, bullets):

    if stats.ships_left > 0:
        stats.ships_left -= 1

        #empty the lists of aliens and bullets
        aliens.empty()
        bullets.empty()

    #create a new fleet and center the ship
        create_fleet(settings, screen, ship, aliens)
        ship.center_ship()

    #pause
        sleep(0.5)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)

def check_events(settings, screen, stats, play_button, ship, aliens, bullets):
    #watch for keyboard and mouse events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(settings, screen, stats, play_button, ship, aliens, bullets,  mouse_x, mouse_y)
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

def check_play_button(settings, screen, stats, play_button, ship, aliens, bullets,  mouse_x, mouse_y):
    """Start a new game when play is selected"""
    if play_button.rect.collidepoint(mouse_x, mouse_y):
        button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
        if button_clicked and not stats.game_active:
            settings.inititialize_dynamic_settings()
            pygame.mouse.set_visible(False)
            stats.reset_stats()
            stats.game_active = True

            #empty aliens and bullets list
            aliens.empty()
            bullets.empty()

            #create a new fleet and center the ship
            create_fleet(settings, screen, ship, aliens)
            ship.center_ship()

def check_keydown_events(event, settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        #move ship to the right
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullets(settings, screen, ship, bullets)
    elif event.key == pygame.K_q:
        sys.exit()

def check_keyup_events(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False

def update_screen(sb, stats, screen, settings, ship, bullets, aliens, play_button):
    screen.fill(settings.screen_color)

    #redraw all the bullets behind the ship
    for bullet in bullets.sprites():
        bullet.draw_bullets()

    ship.blitme()
    aliens.draw(screen)

    sb.show_score()

    if not stats.game_active:
        play_button.draw_button()
    #make the most recently drawn screen visible
    pygame.display.flip()

def update_bullets(settings, screen, stats, sb, ship, aliens, bullets):
    """Update the position of the bullet and delete bullets that have gone off screen"""
    bullets.update()

    #Get rid of bullets that have dissapeared
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
        #print(len(bullets))
    check_bullet_alien_collisions(settings, screen, stats, sb, ship, aliens, bullets)

def check_bullet_alien_collisions(settings, screen, stats, sb, ship, aliens, bullets):
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    if collisions:
        for aliens in collisions.values():
            stats.score += settings.alien_points * len(aliens)
            sb.prep_score()

    if len(aliens) == 0:
        bullets.empty()
        settings.increase_speed()
        create_fleet(settings, screen, ship, aliens)

def fire_bullets(settings, screen, ship, bullets):
    #create a new bullet and add it to the group bullets
    if len(bullets) < settings.bullet_limit:
        new_bullet = Bullet(settings, screen, ship)
        bullets.add(new_bullet)

def create_fleet(settings, screen, ship, aliens):
    """Creates a fleet of aliens"""
    alien = Alien(settings, screen)
    number_aliens_x = get_number_of_aliens_x(settings, alien.rect.width)
    number_rows = get_number_of_rows(settings, ship.rect.height, alien.rect.height)

    #create the first row of aliens
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(settings, screen, aliens, alien_number, row_number)

def get_number_of_aliens_x(settings, alien_width):
    available_space_x = settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x

def create_alien(settings, screen, aliens, alien_number, row_number):
    alien = Alien(settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)

def get_number_of_rows(settings, ship_height, alien_height):
    available_space_y = (settings.screen_height -
                        (3 * alien_height) - ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows

def update_aliens(settings, stats, screen, ship, aliens, bullets):
    check_fleet_edges(settings, aliens)
    aliens.update()

    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(settings, stats, screen, ship, aliens, bullets)
        check_aliens_bottom(settings, stats, screen, ship, aliens, bullets)

def check_fleet_edges(settings, aliens):
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(settings, aliens)
            break

def change_fleet_direction(settings, aliens):
    for alien in aliens.sprites():
        alien.rect.y += settings.drop_speed
    settings.fleet_direction *= -1

def check_aliens_bottom(settings, stats, screen, ship, aliens, bullets):
    """check if any aliens have reached the bottom of the screen"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hit(settings, stats, screen, ship, aliens, bullets)
            break

def check_high_score(stats, sb):
    """Check to see if there is a new high score"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()


from setuptools import setup, find_packages

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='mlflow-dbstore',
    version='1.0.1',
    description='Plugin that provides DB Artifact Store functionality for MLflow',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Avrilia Floratou',
    author_email='avflor@microsoft.com',
    url="https://github.com/avflor/mlflow-dbstore",
    packages=find_packages(),
    install_requires=[
        'mlflow',
    ],
    entry_points={
        "mlflow.artifact_repository": [
            "mssql=dbstoreplugin.store.artifact:DBArtifactRepository"
        ]
    },
)


#DFS
#Whether its BFS / DFS in order to avoid backedge store the parent
#eg. memo.add( (x,y) )  and then explore the childern
class Solution(object):

    def exist(self, board, word):

        if(not board) : return False
        m, n = map(len, [board, board[0]])

        idx_dict = {}
        for i in range(m) :
            for j in range(n) :
                if(board[i][j] not in idx_dict) :
                    idx_dict[ board[i][j] ] = [ ]
                idx_dict[ board[i][j] ] += [ (i,j) ]

        start = word[0]
        if(start not in idx_dict) : return False

        flst = idx_dict[start] #collect all the frontiers

        for fnt in flst :
            if (self.dfs(fnt, board, word) == True) :
                return True
        return False

    def dfs(self, fnt, board, word, idx=0, memo = set()) :
        wlen = len(word)
        if(idx == wlen) :
            return True
        m, n = map(len, [board, board[0]])

        (x,y) = fnt

        if( (x, y) in memo or \
                x >= m or y >= n or x < 0 or y < 0 or \
                word[idx] != board[x][y]) :

            return False

        memo.add( (x,y) )  #Store parent To avoid visiting backedge
        res = self.dfs( (x+1, y) , board, word, idx + 1, memo) or \
                self.dfs((x-1, y) , board, word, idx + 1, memo) or \
                self.dfs((x, y+1) , board, word, idx + 1, memo) or \
                self.dfs((x, y-1) , board, word, idx + 1, memo)
        memo.remove( (x,y) )
        return res

# In place DFS
#Avoid backedge
#board[i][j] = "#"  # avoid visit agian
def exist(self, board, word):
    if not board:
        return False
    for i in xrange(len(board)):
        for j in xrange(len(board[0])):
            if self.dfs(board, i, j, word):
                return True
    return False

# check whether can find word, start at (i,j) position
def dfs(self, board, i, j, word):
    if len(word) == 0: # all the characters are checked
        return True
    if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:
        return False
    tmp = board[i][j]  # first character is found, check the remaining part
    board[i][j] = "#"  # avoid visit agian
    # check whether can find "word" along one direction
    res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \
    or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
    board[i][j] = tmp
    return res

#Given a 2D board and a word, find if the word exists in the grid.
#The word can be constructed from letters of sequentially adjacent cell, where
#"adjacent" cells are those horizontally or vertically neighboring. The same
#letter cell may not be used more than once.
#For example,
#Given board =
#[
#  ['A','B','C','E'],
#  ['S','F','C','S'],
#  ['A','D','E','E']
#]
#word = "ABCCED", -> returns true,
#word = "SEE", -> returns true,
#word = "ABCB", -> returns false


#!/usr/bin/env python

# -*- coding: utf-8 -*-

import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options

import os
import aiml

os.chdir('./aiml')
alice = aiml.Kernel()
alice.learn("startup.xml")
alice.respond("load aiml b")
print(os.path.abspath('.'))

define('port', default=8888, help='run on the given port', type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', MainHandler),
            (r'/chat', ChatHandler),
        ]

        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), 'templates'),
            static_path=os.path.join(os.path.dirname(__file__), 'static'),
            debug=True,
        )

        # conn = pymongo.Connection('localhost', 12345)
        # self.db = conn['demo']
        tornado.web.Application.__init__(self, handlers, **settings)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

    def post(self):

        result = {
            'is_success': True,
            'message': '123'
        }

        respon_json = tornado.escape.json_encode(result)
        self.write(str(respon_json))

    def put(self):
        respon_json = tornado.escape.json_encode("{'name':'qixiao','age':123}")
        self.write(respon_json)

class ChatHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('chat.html')

    def post(self):
        try:
            message = self.get_argument('msg', None)

            print(str(message))

            result = {
                'is_success': True,
                'message': str(alice.respond(message))
            }

            print(str(result))

            respon_json = tornado.escape.json_encode(result)

            self.write(respon_json)

        except Exception as ex:
            repr(ex)
            print(str(ex))

            result = {
                'is_success': False,
                'message': ''
            }

            self.write(str(result))

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    print('HTTP server starting ...')
    main()


def euclids(m, n):
    while m != 0:
        n, m = m, n % m
    return n

def inputs():
    validNumber = False
    while validNumber == False:
        try:
            m = eval(input("Enter the number you want to divide: "))
            n = eval(input("Enter the number you want to divide by: "))
            if m > 0 and n > 0:
                validNumber = True
            else:
                print("Both numbers must be larger than 0")
        except NameError:
            print("Enter a valid number")
    return m, n

def intro():
    print("This program finds the greatest common divisor")
    print("using Euclid's algorithm")

def main():
    intro()
    m, n = inputs()
    gcd = euclids(m, n)
    print("The greatest common denominator for {0} and {1} is {2}".format(m, n, gcd))

main()


import os
import uuid
import errno
import logging
from enum import Enum, unique
from hashlib import md5

import cephfs

from ..pin_util import pin
from .metadata_manager import MetadataManager
from ..trash import create_trashcan, open_trashcan
from ...fs_util import get_ancestor_xattr
from ...exception import MetadataMgrException, VolumeException

log = logging.getLogger(__name__)

@unique
class SubvolumeFeatures(Enum):
    FEATURE_SNAPSHOT_CLONE       = "snapshot-clone"
    FEATURE_SNAPSHOT_AUTOPROTECT = "snapshot-autoprotect"

class SubvolumeBase(object):
    LEGACY_CONF_DIR = "_legacy"

    SUBVOLUME_TYPE_NORMAL = "subvolume"
    SUBVOLUME_TYPE_CLONE  = "clone"

    def __init__(self, fs, vol_spec, group, subvolname, legacy=False):
        self.fs = fs
        self.cmode = None
        self.user_id = None
        self.group_id = None
        self.vol_spec = vol_spec
        self.group = group
        self.subvolname = subvolname
        self.legacy_mode = legacy
        self.load_config()

    @property
    def uid(self):
        return self.user_id

    @uid.setter
    def uid(self, val):
        self.user_id = val

    @property
    def gid(self):
        return self.group_id

    @gid.setter
    def gid(self, val):
        self.group_id = val

    @property
    def mode(self):
        return self.cmode

    @mode.setter
    def mode(self, val):
        self.cmode = val

    @property
    def base_path(self):
        return os.path.join(self.group.path, self.subvolname.encode('utf-8'))

    @property
    def config_path(self):
        return os.path.join(self.base_path, b".meta")

    @property
    def legacy_dir(self):
        return os.path.join(self.vol_spec.base_dir.encode('utf-8'), SubvolumeBase.LEGACY_CONF_DIR.encode('utf-8'))

    @property
    def legacy_config_path(self):
        m = md5()
        m.update(self.base_path)
        meta_config = "{0}.meta".format(m.digest().hex())
        return os.path.join(self.legacy_dir, meta_config.encode('utf-8'))

    @property
    def namespace(self):
        return "{0}{1}".format(self.vol_spec.fs_namespace, self.subvolname)

    @property
    def group_name(self):
        return self.group.group_name

    @property
    def subvol_name(self):
        return self.subvolname

    @property
    def legacy_mode(self):
        return self.legacy

    @legacy_mode.setter
    def legacy_mode(self, mode):
        self.legacy = mode

    @property
    def features(self):
        raise NotImplementedError

    def load_config(self):
        if self.legacy_mode:
            self.metadata_mgr = MetadataManager(self.fs, self.legacy_config_path, 0o640)
        else:
            self.metadata_mgr = MetadataManager(self.fs, self.config_path, 0o640)

    def set_attrs(self, path, size, isolate_namespace, pool, uid, gid):
        # set size
        if size is not None:
            try:
                self.fs.setxattr(path, 'ceph.quota.max_bytes', str(size).encode('utf-8'), 0)
            except cephfs.InvalidValue as e:
                raise VolumeException(-errno.EINVAL, "invalid size specified: '{0}'".format(size))
            except cephfs.Error as e:
                raise VolumeException(-e.args[0], e.args[1])

        # set pool layout
        if pool:
            try:
                self.fs.setxattr(path, 'ceph.dir.layout.pool', pool.encode('utf-8'), 0)
            except cephfs.InvalidValue:
                raise VolumeException(-errno.EINVAL,
                                      "invalid pool layout '{0}' -- need a valid data pool".format(pool))
            except cephfs.Error as e:
                raise VolumeException(-e.args[0], e.args[1])

        # isolate namespace
        xattr_key = xattr_val = None
        if isolate_namespace:
            # enforce security isolation, use separate namespace for this subvolume
            xattr_key = 'ceph.dir.layout.pool_namespace'
            xattr_val = self.namespace
        elif not pool:
            # If subvolume's namespace layout is not set, then the subvolume's pool
            # layout remains unset and will undesirably change with ancestor's
            # pool layout changes.
            xattr_key = 'ceph.dir.layout.pool'
            xattr_val = None
            try:
                self.fs.getxattr(path, 'ceph.dir.layout.pool').decode('utf-8')
            except cephfs.NoData as e:
                xattr_val = get_ancestor_xattr(self.fs, os.path.split(path)[0], "ceph.dir.layout.pool")
        if xattr_key and xattr_val:
            try:
                self.fs.setxattr(path, xattr_key, xattr_val.encode('utf-8'), 0)
            except cephfs.Error as e:
                raise VolumeException(-e.args[0], e.args[1])

        # set uid/gid
        if uid is None:
            uid = self.group.uid
        else:
            try:
                uid = int(uid)
                if uid < 0:
                    raise ValueError
            except ValueError:
                raise VolumeException(-errno.EINVAL, "invalid UID")
        if gid is None:
            gid = self.group.gid
        else:
            try:
                gid = int(gid)
                if gid < 0:
                    raise ValueError
            except ValueError:
                raise VolumeException(-errno.EINVAL, "invalid GID")
        if uid is not None and gid is not None:
            self.fs.chown(path, uid, gid)

    def _resize(self, path, newsize, noshrink):
        try:
            newsize = int(newsize)
            if newsize <= 0:
                raise VolumeException(-errno.EINVAL, "Invalid subvolume size")
        except ValueError:
            newsize = newsize.lower()
            if not (newsize == "inf" or newsize == "infinite"):
                raise VolumeException(-errno.EINVAL, "invalid size option '{0}'".format(newsize))
            newsize = 0
            noshrink = False

        try:
            maxbytes = int(self.fs.getxattr(path, 'ceph.quota.max_bytes').decode('utf-8'))
        except cephfs.NoData:
            maxbytes = 0
        except cephfs.Error as e:
            raise VolumeException(-e.args[0], e.args[1])

        subvolstat = self.fs.stat(path)
        if newsize > 0 and newsize < subvolstat.st_size:
            if noshrink:
                raise VolumeException(-errno.EINVAL, "Can't resize the subvolume. The new size '{0}' would be lesser than the current "
                                      "used size '{1}'".format(newsize, subvolstat.st_size))

        if not newsize == maxbytes:
            try:
                self.fs.setxattr(path, 'ceph.quota.max_bytes', str(newsize).encode('utf-8'), 0)
            except cephfs.Error as e:
                raise VolumeException(-e.args[0], "Cannot set new size for the subvolume. '{0}'".format(e.args[1]))
        return newsize, subvolstat.st_size

    def pin(self, pin_type, pin_setting):
        return pin(self.fs, self.base_path, pin_type, pin_setting)

    def init_config(self, version, subvolume_type, subvolume_path, subvolume_state):
        self.metadata_mgr.init(version, subvolume_type, subvolume_path, subvolume_state)
        self.metadata_mgr.flush()

    def discover(self):
        log.debug("discovering subvolume '{0}' [mode: {1}]".format(self.subvolname, "legacy" if self.legacy_mode else "new"))
        try:
            self.fs.stat(self.base_path)
            self.metadata_mgr.refresh()
            log.debug("loaded subvolume '{0}'".format(self.subvolname))
        except MetadataMgrException as me:
            if me.errno == -errno.ENOENT and not self.legacy_mode:
                self.legacy_mode = True
                self.load_config()
                self.discover()
            else:
                raise
        except cephfs.Error as e:
            if e.args[0] == errno.ENOENT:
                raise VolumeException(-errno.ENOENT, "subvolume '{0}' does not exist".format(self.subvolname))
            raise VolumeException(-e.args[0], "error accessing subvolume '{0}'".format(self.subvolname))

    def trash_base_dir(self):
        if self.legacy_mode:
            self.fs.unlink(self.legacy_config_path)
        subvol_path = self.base_path
        create_trashcan(self.fs, self.vol_spec)
        with open_trashcan(self.fs, self.vol_spec) as trashcan:
            trashcan.dump(subvol_path)
            log.info("subvolume with path '{0}' moved to trashcan".format(subvol_path))

    def create_base_dir(self, mode):
        try:
            self.fs.mkdirs(self.base_path, mode)
        except cephfs.Error as e:
            raise VolumeException(-e.args[0], e.args[1])

    def info (self):
        subvolpath = self.metadata_mgr.get_global_option('path')
        etype = self.metadata_mgr.get_global_option(MetadataManager.GLOBAL_META_KEY_TYPE)
        st = self.fs.statx(subvolpath, cephfs.CEPH_STATX_BTIME | cephfs.CEPH_STATX_SIZE |
                                       cephfs.CEPH_STATX_UID | cephfs.CEPH_STATX_GID |
                                       cephfs.CEPH_STATX_MODE | cephfs.CEPH_STATX_ATIME |
                                       cephfs.CEPH_STATX_MTIME | cephfs.CEPH_STATX_CTIME,
                                       cephfs.AT_SYMLINK_NOFOLLOW)
        usedbytes = st["size"]
        try:
            nsize = int(self.fs.getxattr(subvolpath, 'ceph.quota.max_bytes').decode('utf-8'))
        except cephfs.NoData:
            nsize = 0

        try:
            data_pool = self.fs.getxattr(subvolpath, 'ceph.dir.layout.pool').decode('utf-8')
            pool_namespace = self.fs.getxattr(subvolpath, 'ceph.dir.layout.pool_namespace').decode('utf-8')
        except cephfs.Error as e:
            raise VolumeException(-e.args[0], e.args[1])

        return {'path': subvolpath, 'type': etype, 'uid': int(st["uid"]), 'gid': int(st["gid"]),
            'atime': str(st["atime"]), 'mtime': str(st["mtime"]), 'ctime': str(st["ctime"]),
            'mode': int(st["mode"]), 'data_pool': data_pool, 'created_at': str(st["btime"]),
            'bytes_quota': "infinite" if nsize == 0 else nsize, 'bytes_used': int(usedbytes),
            'bytes_pcent': "undefined" if nsize == 0 else '{0:.2f}'.format((float(usedbytes) / nsize) * 100.0),
            'pool_namespace': pool_namespace, 'features': self.features}


import socket
import os
import time
import numpy as np

os.system('sudo ntpdate 0.es.pool.ntp.org')
UDP_IP = '239.0.0.1'
UDP_PORT = 1234
UDP_PORT2 = 1235
print ("Preparado para recibir datos")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2 = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
socketPlayer = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
socket. socket (socket.AF_INET, socket.SOCK_STREAM)
sock.bind((UDP_IP, UDP_PORT))
socketPlayer.bind(('', 8081))
socketPlayer.listen(1)
print ('Esperando')
conn, addr = socketPlayer.accept()
print ('Conexion establecida con VLC')
sock2.sendto("hola", (UDP_IP, UDP_PORT2))

lista = [None] * 128
bandera = 0
total = 0
data, addr = sock.recvfrom(2048)
elementos = data.split("----")
conn.sendall(elementos[2])

while True:
    data, addr = sock.recvfrom(2048)
    elementos = data.split("----")
    hora = elementos[1]
    print(time. time() - float(hora))
    total+=1

    if bandera==1:
        conn.sendall(lista[total%128])

    lista[((elementos[0]))%128] = elementos[2]
    if total == 127:
        bandera = 1

sock.close()


import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.channel = 3
        self.conv = nn.Conv2d(3, self.channel, kernel_size=3, stride=1, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
        self.dropout = nn.Dropout(p=0.5)
        self.fc1 = nn.Linear(self.channel * 48 * 48, 64)
        self.fc2 = nn.Linear(64, 8)

    def forward(self, x):
        x = self.conv(x)
        x = self.pool(x)
        x = self.dropout(x)
        x = self.conv(x)
        x = self.pool(x)
        x = self.dropout(x)
        x = self.conv(x)
        x = self.pool(x)
        x = self.dropout(x)
        x = x.view(-1, self.channel * 48 * 48)
        x = F.leaky_relu(self.fc1(x))
        x = self.fc2(x)
        return x


#!/usr/bin/env python

import sys, os.path
from sys import argv
from os import system
from string import *
import scipy
import scipy.io as sio
import numpy as np
import argparse
import time
from .liblinearutil import *
from .subr import *

new_class = []

def build_new_file(file, file_name):
	out_file = open(file_name,"w")
	in_file = open(file,"r")
	for line in in_file:
		spline = line.split()

		labels = []
		if spline[0].find(':') == -1:
			labels = spline[0].split(',')
			labels.sort()

		if (labels not in new_class):
			new_class.append(labels)

		if len(labels) == 0:
			out_file.write("%s %s\n"%(new_class.index(labels), ' '.join(spline)))
		else:
			out_file.write("%s %s\n"%(new_class.index(labels), ' '.join(spline[1:])))
	out_file.close()
	in_file.close()

def trans_class(trainFile, testFile, path, dataset):
	build_new_file(trainFile, path+dataset+"-train")
	# print "Number of Training classes (sets of labels) is %s" % len(new_class)

	out_class = open(path+dataset+"-class","w")
	for cl in new_class:
		out_class.write("%s\n" % ",".join(map(lambda num:("%s"%num),cl)))
	out_class.close()

	build_new_file(testFile, path+dataset+"-test")

def mlc_liblinear(trainFile, testFile, path, dataset):
	# transform to multi-class problem
	trans_class(trainFile, testFile, path, dataset)
	tmp_train = path + dataset + "-train"
	tmp_test = path + dataset + "-test"
	tmp_class = path + dataset + "-class"
	model = path + dataset + "-train.model"

	Ytr, Xtr = svm_read_problem(tmp_train)
	Yts, Xts = svm_read_problem(tmp_test)

	# train and predict
	m = train(Ytr, Xtr, '-s 2 -c 1 -q')
	save_model(model, m)
	p_predict, p_acc, p_val = predict(Yts, Xts, m)

	# measure
	original = read_first_column(testFile)
	train_new_class = read_first_column(tmp_class)

	prediction = []
	for i in range(len(p_predict)):
		idx = int(str(int(p_predict[i])))
		prediction.append(train_new_class[idx])

	if(len(prediction) != len(original)):
		print ("Error: lines of %s and %s are different." % (argv[1],argv[2]))
		sys.exit(1)

	labels = []
	for i in range(len(train_new_class)):
		for lab in train_new_class[i]:
			if (lab not in labels):
				labels.append(lab)

	# print "number of labels = %s" % len(labels)

	# result[0]: exact match ratio; result[1]: Micro-F1; result[2]: Macro-F1
	result = measure(original,prediction,labels)
	return result

def main():
	trainFile = 'test/blog-train-1-1.txt'
	testFile = 'test/blog-test-1-1.txt'
	path = 'deepwalk/'
	dataset = 'blog'
	result = mlc_liblinear(trainFile, testFile, path, dataset)
	print (result)

if __name__ == "__main__":
    main()

# def mlc_liblinear(trainFile, testFile, path):
# 	# transform to multi-class problem
# 	trans_class(trainFile, testFile, path)
# 	tmp_train = path + "tmp_train"
# 	tmp_test = path + "tmp_test"
# 	tmp_class = path + "tmp_class"
# 	tmp_predict = path + "tmp_predict"
# 	model = path + 'tmp_train.model'

# 	Ytr, Xtr = svm_read_problem(tmp_train)
# 	Yts, Xts = svm_read_problem(tmp_test)
# 	tmp_pre = open(tmp_predict, "w")

# 	# train and predict
# 	m = train(Ytr, Xtr, '-s 2 -c 1 -q')
# 	save_model(model, m)
# 	p_predict, p_acc, p_val = predict(Yts, Xts, m)

# 	for i in range(len(p_predict)):
# 		tmp_pre.write('{}\n'.format(str(int(p_predict[i]))))
# 	tmp_pre.close()

# 	# measure
# 	original = read_first_column(testFile)
# 	train_new_class = read_first_column(tmp_class)
# 	test_output = read_first_column(tmp_predict)

# 	prediction = []
# 	for i in range(len(test_output)):
# 		idx = atoi(test_output[i][0])
# 		prediction.append(train_new_class[idx])

# 	if(len(prediction) != len(original)):
# 		print "Error: lines of %s and %s are different." % (argv[1],argv[2])
# 		sys.exit(1)

# 	labels = []
# 	for i in range(len(train_new_class)):
# 		for lab in train_new_class[i]:
# 			if (lab not in labels):
# 				labels.append(lab)

# 	print "number of labels = %s" % len(labels)

# 	# result[0]: exact match ratio; result[1]: Micro-F1; result[2]: Macro-F1
# 	result = measure(original,prediction,labels)
# 	return result


from random import randint

# Class to represent a system user
class User:
    """User of a campus Unix system"""

    def __init__(self, first_name, last_name, username, dept, admin=False):
        self.first_name = first_name
        self.last_name = last_name
        self.username = username
        self.dept = dept
        self.admin = admin  # boolean value
        self.login_attempts = 0

    def describe_user(self):
        """Print out user description"""
        print(f"Username: {self.username} -- login attempts: "
            f"{self.login_attempts}")
        print(f"Name: {self.first_name} {self.last_name} -- {self.dept}")
        if self.admin == True:
            print("\t**Admin-level user**")

    def greet_user(self):
        """Print out greeting to the user"""
        print(f"Welcome back {self.username}. Let's get to work.\n")

    def increment_login(self):
        """Add one to login_attempts each time the user logs in"""
        self.login_attempts += 1

    def reset_login_attempts(self):
        """Reset login_attempts to 0"""
        self.login_attempts = 0

# Create empty array to hold instances of User
users = []

# Instantiate four users and add them to the array
dev_boy1 = User('Tyler', 'Rogers', 'snuffle_puffle', 'accounting')
dev_boy2 = User('Thomas', 'The Tank Engine', 'sirchuggsalot', 'finance')
tech_lead_a = User('Pratik', 'Praudhuri', 'pratik58', 'IT', True)
qa_tester5 = User('William', 'Foster', 'stardust', 'qa testing')
users.append(dev_boy1)
users.append(dev_boy2)
users.append(tech_lead_a)
users.append(qa_tester5)

# Describe the different users via a loop
for user in users:
    # Randomize number of logins
    logins = randint(1, 25)
    while logins > 0:
        user.increment_login()
        logins -= 1
    # Run methods
    user.describe_user()
    user.greet_user()

# Reset all user login attempts to 0
for user in users:
    user.reset_login_attempts()
    print(f"Resetting login attempts for user '{user.username}' "
        f"to {user.login_attempts}.")


import pandas as pd
import sys
import datetime as dt
sys.path.append("D:\\Program Files\\Tinysoft\\Analyse.NET")
import TSLPy3 as ts
from makeCSI500Portfolio import *

class TsTickData(object):

    def __enter__(self):
        if ts.Logined() is False:
            self.__tsLogin()
            return self

    def __tsLogin(self):
        ts.ConnectServer("tsl.tinysoft.com.cn", 443)
        dl = ts.LoginServer("fzzqjyb", "fz123456")

    def __exit__(self, *arg):
        ts.Disconnect()

    def getCurrentPrice(self, ticker):
        ts_sql = '''
        setsysparam(pn_stock(),'{}');
        rds := rd(6);
        return rds;
        '''.format(ticker)
        fail, value, _ = ts.RemoteExecute(ts_sql, {})
        return value

    def getHistoricalPrice(self, ticker, date):
        ts_sql = '''
        setsysparam(pn_stock(), "{0}");
        setsysparam(pn_date(), inttodate({1}));
        return close();
        '''.format(ticker, date)
        fail, value, _ = ts.RemoteExecute(ts_sql, {})
        return value

    def getMarketTable(self, code, start_date, end_date):
        ts_template = Template('''begT:= StrToDate('{{start_date}}');
                                  endT:= StrToDate('{{end_date}}');
                                  setsysparam(pn_cycle(),cy_1s());
                                  setsysparam(pn_rate(),0);
                                  setsysparam(pn_RateDay(),rd_lastday);
                                  r:= select  ["StockID"] as 'ticker', datetimetostr(["date"]) as "time", ["price"]
                                      from markettable datekey begT to endT of "{{code}}" end;
                                  return r;''')
        ts_sql = ts_template.render(start_date=dateparse(start_date).strftime('%Y-%m-%d'),
                                    end_date=dateparse(end_date).strftime('%Y-%m-%d'),
                                    code=code)
        fail, data, _ = ts.RemoteExecute(ts_sql, {})

        def gbk_decode(strlike):
            if isinstance(strlike, (str, bytes)):
                strlike = strlike.decode('gbk')
            return strlike

        def bytes_to_unicode(record):
            return dict(map(lambda s: (gbk_decode(s[0]), gbk_decode(s[1])), record.items()))

        if not fail:
            unicode_data = list(map(bytes_to_unicode, data))
            return pd.DataFrame(unicode_data).set_index(['time', 'ticker'])
        else:
            raise Exception("Error when execute tsl")

def adjust_weight(position_file: str, prev_date: str) -> None:
    # Position file should be 股份查询-股份组合，存成xlsx并去除千位符
    # Prev_date is the last trading day.
    port = pd.read_excel(position_file, encoding="gbk", skiprows=range(0, 4), index_col=None)
    port.index = list(range(port.shape[0]))
    port.drop([port.shape[0] - 1], axis=0, inplace=True)
    port = port[["证券代码", "证券名称", "股份余额"]]   # 股份余额是按昨日余额结转的，实时持仓是当前余额
    port["证券代码"] = port["证券代码"].apply(lambda k: str(int(k)).zfill(6))
    port["证券代码"] = port["证券代码"].apply(lambda s: "SH" + s if s.startswith('6') else "SZ" + s)
    port = port[(port["证券代码"] != "SZ511880") & (port["证券代码"] != "SZ511990") \
                          & (port["证券代码"] != "SZ511660") & (port["股份余额"] != 0)]  # Delete money fund and debts
    index = makePortfolio(10000000, tradeDay=prev_date, hundred=False)
    index["证券代码"] = index["证券代码"].apply(lambda s: s[-2:] + s[:6])
    port = port.set_index('证券代码').squeeze()
    index = index.set_index('证券代码').squeeze()
    unionIndex = index.index.union(port.index)
    unionPrice = pd.DataFrame()
    with TsTickData() as tsl:
        for tsl_ticker in list(unionIndex):
            price = tsl.getHistoricalPrice(ticker=tsl_ticker, date=prev_date)
            unionPrice = unionPrice.append([[tsl_ticker, price],])
    unionPrice.columns = ["证券代码", "前收价格"]
    port = pd.merge(port, unionPrice, left_index=True, right_on="证券代码")
    index = pd.merge(index, unionPrice, left_index=True, right_on="证券代码")
    port["持仓金额"] = port["股份余额"].mul(port["前收价格"])
    port_sum = port["持仓金额"].sum()
    port["权重"] = port["持仓金额"] / port_sum
    index["篮子金额"] = index["篮子数量"].mul(index["前收价格"])
    index_sum = index["篮子金额"].sum()
    index["权重"] = index["篮子金额"] / index_sum
    portWeight = port[["证券代码", "权重"]].set_index('证券代码').squeeze()
    indexWeight = index[["证券代码", "权重"]].set_index('证券代码').squeeze()
    unionIndex = indexWeight.index.union(portWeight.index)
    indexWeight = indexWeight.reindex(unionIndex, fill_value = 0.)
    portWeight = portWeight.reindex(unionIndex, fill_value = 0.)
    indexWeight.to_csv("debug.csv", encoding="gbk")
    portWeight.to_csv("debug2.csv", encoding="gbk")
    diffWeight = indexWeight - portWeight
    value = diffWeight * port_sum
    portfolio = pd.DataFrame(value)
    portfolio.reset_index(inplace=True)
    portfolio.columns = ["证券代码", "篮子金额"]
    portfolio = pd.merge(portfolio, unionPrice, on="证券代码")
    portfolio["篮子数量"] = portfolio["篮子金额"].div(portfolio["前收价格"])
    portfolio["证券代码"] = portfolio["证券代码"].apply(lambda s: s[3:] + '.' + s[:2])
    portfolio_buy = portfolio[portfolio["篮子数量"] > 0]
    portfolio_sell = portfolio[portfolio["篮子数量"] < 0]
    pos_sum = portfolio_buy["篮子金额"].sum()
    neg_sum = portfolio_sell["篮子金额"].sum()
    print("买入", round(pos_sum / 10000, 2), "万， 卖出", round(neg_sum / 10000, 2), "万")
    numOfPortfolio = int(input("请输入要分成的篮子数量："))
    portfolio_buy = portfolio_buy[["证券代码", "篮子数量"]]
    portfolio_sell = portfolio_sell[["证券代码", "篮子数量"]]
    portfolio_buy["篮子数量"] = portfolio_buy["篮子数量"].apply(lambda x: round(x / numOfPortfolio, -2)).astype(int)
    portfolio_sell["篮子数量"] = portfolio_sell["篮子数量"].apply(lambda x: round(x / numOfPortfolio, -2)).astype(int)
    portfolio_buy = portfolio_buy[portfolio_buy["篮子数量"] > 0]
    portfolio_sell = portfolio_sell[portfolio_sell["篮子数量"] < 0]
    portfolio_sell["篮子数量"] = - portfolio_sell["篮子数量"]
    portfolio_buy.to_excel("portfolio_buy.xls", encoding="gbk", index=None)
    portfolio_sell.to_excel("portfolio_sell.xls", encoding="gbk", index=None)
    print(portfolio_buy)
    print(portfolio_sell)

if __name__ == "__main__":
    adjust_weight("position_1224.xlsx", prev_date="20191223")


"""
usage from command line:
python remove_duplicates.py path/to/infile path/to/outfile
"""

import json

def load_data(path):
    with open(path, 'r+', encoding='utf-8') as json_file:
        parsed = json.load(json_file)
    return parsed

def save_data(outfile, clean_data):
    with open(outfile, 'w+', encoding='utf-8') as outfile:
        json.dump(clean_data, outfile, ensure_ascii=False)

def parse_feautre(feature):
    coordinates = feature['geometry']['coordinates']
    flatten_coordinates = list(itertools.chain(*coordinates))

    first, coors = flatten_coordinates[0], flatten_coordinates[1:-1]

    new_coors = []

    for element in coors:
        if element not in [first]:
            if element not in new_coors:
                new_coors.append(element)

    # first and last coordinat must be the same
    cleaned_coors = [[first] + new_coors + [first]]
    feature['geometry']['coordinates'] = cleaned_coors

    return feature

def remove_duplicates(json_data):

    clean_features = []

    for feature in json_data['features']:
        clean_feature = parse_feautre(feature)
        clean_features.append(clean_feature)

    clean_parsed = json_data
    clean_parsed['features'] = clean_features

    return clean_parsed

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('infile', help='path to directory with data')
    parser.add_argument('outfile', help='path to directory with outfile')
    args = parser.parse_args()
    json_data = load_data(args.infile)
    cleaned_data = remove_duplicates(json_data)
    save_data(args.outfile, cleaned_data)


import os
import cv2
import json
import tqdm
import gzip
import argparse
import numpy as np

import torch

import habitat
import habitat_extensions

from habitat.utils.visualizations import maps

from einops import rearrange, asnumpy
from occant_baselines.rl.policy import Mapper
from occant_baselines.config.default import get_config

class DummyRLEnv(habitat.RLEnv):
    def __init__(self, config, dataset=None, env_ind=0):
        super(DummyRLEnv, self).__init__(config, dataset)
        self._env_ind = env_ind

    def get_reward_range(self):
        return -1.0, 1.0

    def get_reward(self, observations):
        return 0.0

    def get_done(self, observations):
        done = False
        if self._env.episode_over:
            done = True
        return done

    def get_info(self, observations):
        return self.habitat_env.get_metrics()

    def get_env_ind(self):
        return self._env_ind

def colorize_ego_map(ego_map):
    """
    ego_map - (V, V, 2) array where 1st channel represents prob(occupied space) an
              d 2nd channel represents prob(explored space)
    """
    explored_mask = ego_map[..., 1] > 0.5
    occupied_mask = np.logical_and(ego_map[..., 0] > 0.5, explored_mask)
    free_space_mask = np.logical_and(ego_map[..., 0] <= 0.5, explored_mask)
    unexplored_mask = ego_map[..., 1] <= 0.5

    ego_map_color = np.zeros((*ego_map.shape[:2], 3), np.uint8)

    # White unexplored map
    ego_map_color[unexplored_mask, 0] = 255
    ego_map_color[unexplored_mask, 1] = 255
    ego_map_color[unexplored_mask, 2] = 255

    # Blue occupied map
    ego_map_color[occupied_mask, 0] = 0
    ego_map_color[occupied_mask, 1] = 0
    ego_map_color[occupied_mask, 2] = 255

    # Green free space map
    ego_map_color[free_space_mask, 0] = 0
    ego_map_color[free_space_mask, 1] = 255
    ego_map_color[free_space_mask, 2] = 0

    return ego_map_color

def safe_mkdir(path):
    try:
        os.mkdir(path)
    except:
        pass

def main(args):

    config = get_config()

    mapper_config = config.RL.ANS.MAPPER
    mapper_config.defrost()
    mapper_config.map_size = 65
    mapper_config.map_scale = 0.05
    mapper_config.freeze()

    mapper = Mapper(mapper_config, None)

    M = args.global_map_size

    config_path = args.config_path
    save_dir = args.save_dir
    safe_mkdir(save_dir)

    config = habitat_extensions.get_extended_config(config_path)

    dataset_path = config.DATASET.DATA_PATH.replace("{split}", config.DATASET.SPLIT)
    with gzip.open(dataset_path, "rt") as fp:
        dataset = json.load(fp)

    num_episodes = len(dataset["episodes"])

    env = DummyRLEnv(config=config)
    env.seed(1234)
    device = torch.device("cuda:0")

    for i in tqdm.tqdm(range(num_episodes)):
        _ = env.reset()

        # Initialize a global map for the episode
        global_map = torch.zeros(1, 2, M, M).to(device)

        grid_size = config.TASK.GT_EGO_MAP.MAP_SCALE
        coordinate_max = maps.COORDINATE_MAX
        coordinate_min = maps.COORDINATE_MIN
        resolution = (coordinate_max - coordinate_min) / grid_size
        grid_resolution = (int(resolution), int(resolution))

        top_down_map = maps.get_topdown_map(env.habitat_env.sim, grid_resolution, 20000)

        map_w, map_h = top_down_map.shape

        intervals = (max(int(1.0 / grid_size), 1), max(int(1.0 / grid_size), 1))
        x_vals = np.arange(0, map_w, intervals[0], dtype=int)
        y_vals = np.arange(0, map_h, intervals[1], dtype=int)
        coors = np.stack(np.meshgrid(x_vals, y_vals), axis=2)  # (H, W, 2)
        coors = coors.reshape(-1, 2)  # (H*W, 2)
        map_vals = top_down_map[coors[:, 0], coors[:, 1]]
        valid_coors = coors[map_vals > 0]

        real_x_vals = coordinate_max - valid_coors[:, 0] * grid_size
        real_z_vals = coordinate_min + valid_coors[:, 1] * grid_size
        start_y = env.habitat_env.sim.get_agent_state().position[1]

        for i in range(real_x_vals.shape[0]):
            for theta in np.arange(-np.pi, np.pi, np.pi / 3.0):
                position = [
                    real_x_vals[i].item(),
                    start_y.item(),
                    real_z_vals[i].item(),
                ]
                rotation = [
                    0.0,
                    np.sin(theta / 2).item(),
                    0.0,
                    np.cos(theta / 2).item(),
                ]

                sim_obs = env.habitat_env.sim.get_observations_at(
                    position, rotation, keep_agent_at_new_pose=True
                )
                episode = env.habitat_env.current_episode
                obs = env.habitat_env.task.sensor_suite.get_observations(
                    observations=sim_obs, episode=episode, task=env.habitat_env.task
                )
                ego_map_gt = torch.Tensor(obs["ego_map_gt"]).to(device)
                ego_map_gt = rearrange(ego_map_gt, "h w c -> () c h w")
                pose_gt = torch.Tensor(obs["pose_gt"]).unsqueeze(0).to(device)
                global_map = mapper.ext_register_map(global_map, ego_map_gt, pose_gt)

        # Save data
        global_map_np = asnumpy(rearrange(global_map, "b c h w -> b h w c")[0])
        episode_id = env.habitat_env.current_episode.episode_id
        np.save(os.path.join(save_dir, f"episode_id_{episode_id}.npy"), global_map_np)

if __name__ == "__main__":

    parser = argparse.ArgumentParser()

    parser.add_argument("--config-path", type=str, required=True)
    parser.add_argument("--save-dir", type=str, required=True)
    parser.add_argument("--global-map-size", type=int, required=True)

    args = parser.parse_args()

    main(args)


import json
import pandas as pd
import datetime
import pathlib
from smart_open import open

two_days_ago = (datetime.date.today() - datetime.timedelta(days=2)).strftime('%Y%m%d')

IS_GS = True

def get_path(path, data_type, file_type):
    if data_type == 'music_charts':
        file_name = f'music_chart_{two_days_ago}.{file_type}'
        sink = path.joinpath('music_charts', file_name)
    elif data_type == 'countries':
        file_name = f'countries.{file_type}'
        sink = path.joinpath('countries', file_name)
    return 'gs:/' + str(sink) if IS_GS else str(sink)

def read_from_file(source):
    file = open(source,'r')
    text = file.read()
    file.close
    return json.loads(text)

def create_table(path_source, path_sink):
    #music_chart
    music_chart = read_from_file(get_path(path_source, 'music_charts', 'json'))
    #print(music_chart)
    # create a dict with a composite key instead of nested dicts
    music_chart_dict = {}
    for country, inner_dict in music_chart.items():
        for position, innerest_dict in inner_dict.items():
            music_chart_dict[(country, position)] = innerest_dict
    # print(music_chart_dict)
    df = pd.DataFrame.from_dict(music_chart_dict, orient='index')
    df.rename_axis(['country', 'position'], inplace=True)
    df.to_csv(path_or_buf = get_path(path_sink, 'music_charts', 'csv'))
    #print(df)

    #countries
    countries = read_from_file(get_path(path_source, 'countries', 'json'))
    #print(countries)
    dc = pd.DataFrame.from_dict(countries, orient='index', columns=['countryFullName'])
    dc.rename_axis(['country'], inplace=True)
    dc.to_csv(path_or_buf = get_path(path_sink, 'countries', 'csv'))

if __name__ == "__main__":
    IS_GS = False
    create_table(pathlib.Path('./source_files/output_raw'), pathlib.Path('./source_files/output_tables'))


# -*- coding: utf-8 -*-

import os

from tvb.basic.neotraits.api import Attr

from tvb_multiscale.core.spiking_models.network import SpikingNetwork
from tvb_multiscale.tvb_annarchy.config import Config, CONFIGURED, initialize_logger
from tvb_multiscale.tvb_annarchy.annarchy_models.brain import ANNarchyBrain
from tvb_multiscale.tvb_annarchy.annarchy_models.devices import \
    ANNarchyOutputSpikeDeviceDict, ANNarchyOutputContinuousTimeDeviceDict

LOG = initialize_logger(__name__)

class ANNarchyNetwork(SpikingNetwork):

    """
        ANNarchyNetwork is a class representing a ANNarchy spiking network comprising of:
        - a ANNarchyBrain class, i.e., neural populations organized per brain region they reside and neural model,
        - a pandas.Series of DeviceSet classes of output (measuring/recording/monitor) devices,
        - a pandas.Series of DeviceSet classes of input (stimulating) devices,
        all of which are implemented as indexed mappings by inheriting from pandas.Series class.
        The class also includes methods to return measurements (mean, sum/total data, spikes, spikes rates etc)
        from output devices, as xarray.DataArrays.
        e.g. ANnarchyPopulations can be indexed as:
        annarchy_network.brain_regions['rh-insula']['E'] for population "E" residing in region node "rh-insula",
        and similarly for an output device:
        annarchy_network.output_devices['Excitatory']['rh-insula'],
        which measures a quantity labelled following the target population ("Excitatory"),
        residing in region node "rh-insula".
    """

    config = Attr(
        label="Configuration",
        field_type=Config,
        doc="""Configuration class instance.""",
        required=True,
        default=CONFIGURED
    )

    brain_regions = Attr(
        field_type=ANNarchyBrain,
        label="NEST brain regions",
        default=None,
        required=True,
        doc="""A NESTBrain instance holding all NEST neural populations
                   organized per brain region they reside and neural model""")  # spiking_brain['rh-insula']['E']

    network_path = Attr(
        label="ANNarchy network path",
        field_type=str,
        doc="""Path to the compiled code of the ANNarchy network.""",
        required=False,
        default=""
    )

    annarchy_instance = None

    _network = None

    _dt = None

    _OutputSpikeDeviceDict = ANNarchyOutputSpikeDeviceDict
    _OutputContinuousTimeDeviceDict = ANNarchyOutputContinuousTimeDeviceDict

    def __init__(self, annarchy_instance=None, **kwargs):
        self.annarchy_instance = annarchy_instance
        super(ANNarchyNetwork, self).__init__(**kwargs)

    @property
    def spiking_simulator_module(self):
        return self.annarchy_instance

    @property
    def network(self):
        if self._network is None:
            if self.annarchy_instance is not None:
                self._network = self.annarchy_instance.Network(everything=True)
        return self._network

    @property
    def dt(self):
        if self._dt is None:
            self._dt = self.annarchy_instance.Global.dt()
        return self._dt

    @property
    def min_delay(self):
        return self.dt

    def compile_network(self, *args, **kwargs):
        self.network_path = kwargs.pop("network_path", self.network_path)
        if not os.path.isdir(self.network_path):
            directory = str(kwargs.pop("directory", self.config.out.FOLDER_RES))
            cwd = os.getcwd()
            if directory.find(cwd) > -1:
                self.network_path = os.path.join(directory.split(cwd)[-1][1:].split("res")[0],
                                                 self.__class__.__name__)
        self.annarchy_instance.compile(directory=self.network_path, *args, **kwargs)

    def configure(self, *args, **kwargs):
        super(ANNarchyNetwork, self).configure()
        self.compile_network(*args, **kwargs)

    def Run(self, simulation_length=None, **kwargs):
        """Method to simulate the ANNarchy network for a specific simulation_length (in ms).
           It will run annarchy_instance.simulate(simulation_length, *args, **kwargs)
        """
        if simulation_length is None:
            simulation_length = self.dt
        measure_time = kwargs.pop("measure_time", False)
        for dev_name, out_dev_set in self.output_devices.items():
            out_dev_set.do_for_all("resume")
        self.annarchy_instance.simulate(simulation_length, measure_time=measure_time, **kwargs)
        for dev_name, out_dev_set in self.output_devices.items():
            out_dev_set.do_for_all("pause")

    def info(self, recursive=0):
        info = super(ANNarchyNetwork, self).info(recursive=recursive)
        info["ANNarchy_Network"] = self.network
        return info


# Read the number of test cases
t = int(input())

# Iterate over each test case
for _ in range(t):
    # Read the lengths of the sides of the triangle
    a, b, c = map(int, input().split())

    # Check if the triangle is scalene
    if a != b and b != c and c != a:
        print("YES")
    else:
        print("NO")


# -*- coding: utf-8 -*-

from numpy import *
import operator
#字符识别导入目录中的数据
from os import listdir

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1],[2,2],[2.1,2.0]])
    labels=["A","A","B","B","C","C"]
    return group,labels

def classify0(inX ,dataSet,labels,k):
    #计算给出的二级数组的个数，此处为6个。
    dataSetSize=dataSet.shape[0]
    #print(dataSetSize)
    #计算测试点列到阵列中各个点的坐标距离，并形成距离矩阵。
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    #print(diffMat)
    #将距离做平方
    sqDiffMat=diffMat**2
    #print(sqDiffMat)
    #将平方加和
    sqDistances=sqDiffMat.sum(axis=1)
    #print(sqDistances)
    #计算平方根，即为欧氏距离。
    distances=sqDistances**0.5
    #print(distances)
    #根据到目标点的欧氏距离对训练集进行排序
    sortDistIndicies=distances.argsort()
    #print(sortDistIndicies)
    classCount={}
    for i in range(k):
        #将点按照投票来排序 450132对应 CCAABB
        voteIlabel=labels[sortDistIndicies[i]]
        #print(voteIlabel)
        #计算字典中key是否存在，存在则加1，后面那个0代表从多少开始计数
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
        #print(classCount[voteIlabel])
    sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
    #print(sortedClassCount)#计算计数之后的结果 [('C', 2), ('A', 1)]
    return sortedClassCount[0][0]

#group,labels=createDataSet()
#print(classify0([2,2],group,labels,3))
def file2matrix(filename):
    fr=open(filename)
    arrayOLines=fr.readlines()
    numberOfLines=len(arrayOLines)
    returnMat=zeros((numberOfLines,3))
    #print("returnMat %s",returnMat)
    classLabelVector=[]
    index=0
    for line in arrayOLines:
        line=line.strip()
        #切分每一行数据得到一个列表形式的数据
        listFromLine=line.split('\t')
        #为二维数组的每一份儿数据赋值，每行三个数据组成数组，文件有多长，这样的数组就有多少个。
        returnMat[index,:]=listFromLine[0:3]
        #将数组中最后一个分类数据存储在列表中，最后一项数据代表分类。根据喜欢程度分成三个层次。
        classLabelVector.append(int(listFromLine[-1]))
        index+=1
    return returnMat,classLabelVector

def autoNorm(dataSet):
    minVals=dataSet.min(0)
    maxVals=dataSet.max(0)
    ranges=maxVals-minVals
    #print("min %f max %f range %f",minVals,maxVals,ranges)
    normDataSet=zeros(shape(dataSet))
    m=dataSet.shape[0]
    normDataSet=dataSet-tile(minVals,(m,1))
    normDataSet=normDataSet/tile(ranges,(m,1))
    return normDataSet,ranges,minVals

#2-4 分类器针对约会网站的测试代码
def datingClassTest():
    hoRatio=0.10
    #将文件读入到矩阵当中
    datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
    #将矩阵归一化
    normMat,ranges,minVals=autoNorm(datingDataMat)
    #拿到矩阵的第一层的个数 1000
    m=normMat.shape[0]
    #print("m =",m)
    #取得百分之10的样本的数量
    numTestVecs=int(m*hoRatio)
    errorCount=0.0
    #1000行记录循环100次。
    for i in range(numTestVecs):
        #字段1输入测试点，从第一行到numtestvecs行。
        #字段2输入测试集合。从numtestvecs行到结尾。
        #字段3输入
        #print("111111111111",datingLabels[numTestVecs:m])
        #字段4输入k的个数。
        classifierResult=classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)
        print("经过训练得到的结果为: %d, 实际结果为: %d" % (classifierResult,datingLabels[i]))
        if (classifierResult != datingLabels[i]):
            errorCount+=1.0
    #print(len(datingLabels[numTestVecs:m]))
    #print(datingLabels[numTestVecs:m])
    print("the total error rate is :%f" % (errorCount/float(numTestVecs)))
#import importlib
#importlib.reload(kNN)

#import matplotlib
#import matplotlib.pyplot as plt
#fig=plt.figure()
#ax=fig.add_subplot(111)
#ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),10.0*array(datingLabels))
#plt.show()

def classifyPerson():
    resultList=["几乎不可能","有可能","希望很大"]
    percentTats= float(input("玩儿视频游戏所耗时间百分比："))
    ffMiles=float(input("每年在天上的公里数："))
    iceCream=float(input("每年吃冰激凌的升数："))
    #将文件读入到矩阵当中
    datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
    #将矩阵归一化
    normMat,ranges,minVals=autoNorm(datingDataMat)
    inArr=array([ffMiles,iceCream,percentTats])
    classifierResult=classify0(((inArr-minVals)/ranges),normMat,datingLabels,3)
    print("你喜欢这个人的程度预测为",resultList[classifierResult-1])

#算法总结：
    #1.读取一个文件，文件内容为可变为矩阵的内容。
    #2.读取文件后形成矩阵，并得到每一行数据的类型数据。
    #3.将矩阵取出大部分作为训练集，设计K临近算法对训练内容进行实际分类。
    #4。将剩余的数据内容部分作为实例，测试分类器的错误率。
    #5。如果训练集得到的错误率很低，就可以使用这个训练集进行相应的预测活动。
#该算法可用用于进行一些分类工作。可以适当修改数值和意义，来实现新的分类含义。

#下面的代码例子用于字符识别
#将文件内容中的数字进行序列化，变为一个1024长度的数组。
def img2vector(filename):
    returnVect=zeros((1,1024))
    fr=open(filename)
    for i in range(32):
        lineStr=fr.readline()
        for j in range(32):
            returnVect[0,32*i+j]=int(lineStr[j])
    return returnVect

#手写识别系统的测试代码。
def handewritingClassTest():
    hwLabels=[]
    #指定训练目录中的文件列表
    trainingFileList=listdir('trainingDigits')
    m=len(trainingFileList)
    trainingMat=zeros((m,1024))
    for i in range(m):
        fileNameStr=trainingFileList[i]
        #得到文件名前缀
        fileStr=fileNameStr.split('.')[0]
        #得到类型信息
        classNumStr=int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:]=img2vector('trainingDigits/%s' % fileNameStr)
    testFileList=listdir('testDigits')
    errorCount=0.0
    mTest=len(testFileList)
    for i in range(mTest):
        fileNameStr=testFileList[i]
        fileStr=fileNameStr.split('.')[0]
        classNumStr=int(fileStr.split('_')[0])
        vectorUnderTest=img2vector('testDigits/%s' % fileNameStr)
        #测试集内容vectorUnderTest，训练集矩阵trainingMat，类型列表hwLabels。
        classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)
        print("分类器返回值为：%d 实际的值为：%d" % (classifierResult,classNumStr))
        if(classifierResult!=classNumStr):
            errorCount+=1.0
    print("错误数为：%d" % errorCount)
    print("错误率为: %f" % (errorCount/float(mTest)))

#handewritingClassTest()

#手写识别算法总结
#1、将测试集中的每一个文件中的内容都转化为1024字符的列表。
#2、拿这个列表针对所有训练集进行训练，通过k临近算法找到最接近的类型。


import argparse
import sys
from os import path

ROOT_DIR = path.dirname(path.abspath(__file__))
SETTING_DIR = path.join(ROOT_DIR, '..', 'setting')
sys.path.append(SETTING_DIR)

from queue.scanner import Scanner

def scan_all(workspace, extension, db_path,
             module_search_path, libs_in_xml):
    for path_ in module_search_path:
        sys.path.append(path_)
    scanner = Scanner(libs_in_xml)
    scanner.scan(
        workspace=workspace,
        ext=extension,
        db_path=db_path
    )

def scan_single(file_path, db_path, libs_in_xml):
    scanner = Scanner(libs_in_xml)
    scanner.scan_single_file(file_path=file_path, db_path=db_path)

if __name__ == '__main__':
    c_parser = argparse.ArgumentParser(
        description='Scanning Robot data from system Python')
    c_parser.add_argument(
        'mode',
        choices=['all', 'single'],
        help='Scanning mode: all or single'
    )
    c_parser.add_argument(
        '--workspace',
        help='Root of the folder where data parsing is performed'
    )
    c_parser.add_argument(
        '--extension',
        help='File extension for Robot data, example "robot" or "txt"'
    )
    c_parser.add_argument(
        '--db_path',
        required=True,
        help='Folder where scanning result is saved'
    )
    c_parser.add_argument(
        '--module_search_path',
        nargs='*',
        help='List of paths where libraries are searched when scanning')
    c_parser.add_argument(
        '--path_to_file',
        help='Path to file which is scanned')
    c_parser.add_argument(
        '--path_to_lib_in_xml',
        help='Path to libraries in XML format')
    args = c_parser.parse_args()
    module_search_path = []
    if args.module_search_path:
        module_search_path = args.module_search_path
    if args.mode == 'all':
        if not args.workspace:
            raise ValueError('--workspace is needed with mode: {0}'.format(
                args.mode))
        elif not args.extension:
            raise ValueError('--extension is needed with mode: {0}'.format(
                args.mode))
        else:
            scan_all(
                args.workspace,
                args.extension,
                args.db_path,
                module_search_path,
                args.path_to_lib_in_xml)
    elif args.mode == 'single':
        if not args.path_to_file:
            raise ValueError(
                '--path_to_file is needed with mode: {0}'.format(
                    args.mode
                )
            )
        else:
            scan_single(
                args.path_to_file,
                args.db_path,
                args.path_to_lib_in_xml
            )


from collections import OrderedDict
from grt.core import GRTMacro

class FourBarMacro(GRTMacro):
    """
    Drive Macro; drives forwards a certain distance while
    maintaining orientation
    """
    leftSF = 1
    rightSF = -1
    distance = None
    previously_on_target = False

    def __init__(self, fourbar, distance=0, timeout=None, index_id=200):
        """
        Pass drivetrain, distance to travel (ft), and timeout (secs)
        """
        super().__init__(timeout)
        self.fourbar= fourbar
        self.distance = distance
        self.fourbar_encoder = fourbar.fourbar_encoder
        #self.STATE_DICT = {'level0_release' : 0, 'level0' : 0, 'level0.5_release' : 0, 'level0.5' : 7, 'level1_release' : 12, 'level1' : 17, 'level2_release' : 27, 'level2' : 33, 'level3_release' : 42, 'level3' : 50}
        self.STATE_DICT = OrderedDict()
        #self.STATE_DICT['full_down'] = 55
        self.STATE_DICT['down'] = 50
        self.STATE_DICT['up'] = 0
        #self.STATE_DICT['full_up'] = -5

        self.setpoint = distance
        self.zero = self.fourbar_encoder.e.getDistance()
        self.current_state = 'up'
        self.enabled = False
        self.at_top = False
        self.at_bottom = False
        self.index_id = index_id
        self.ERROR = 0
        self.counter = 0 #counter of attempted pickups
        self.prev_pressed = False #for counter
        #self.run_threaded()

    def macro_initialize(self):
        self.initial_distance = self.fourbar_encoder.e.getDistance()
        print("Initialized")

    def macro_periodic(self):
        """
        self.initial_distance = self.fourbar_encoder.e.getDistance()
        print(self.initial_distance)
        if(self.setpoint>self.initial_distance):
            while(self.traveled_distance() < self.setpoint * .8):
                print("travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(.6)
                if not self.running:
                    print("Clearing close")
                    return
            while(self.traveled_distance() < self.setpoint):
                print("half power travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(.3)
            self.fourbar.stop()
        elif(self.setpoint<self.initial_distance):
            while(self.traveled_distance() > self.setpoint * .8):
                print("travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(-.6)
            while(self.traveled_distance() > self.setpoint):
                print("half power travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(-.3)
            self.fourbar.stop()
        print("Cleared close")
        self.terminate()
        """
        #print("Polling")
        #print(self.initial_distance)
        #print(self.zero)

        #Move initial distance logic to a special if statement
        # that gets called only once when the macro is first enabled.
        # self.initialize() calls will be useless for these macros.
        #print(self.fourbar_encoder.distance)
        if self.enabled:
            self.ERROR = self.setpoint - self.fourbar_encoder.distance
            #If the setpoint is above the current distance.
            #print("Bottom switch: ", self.fourbar.bottom_switch.get())
            #print("Bottom limit switch: ", self.fourbar.bottom_limit_switch.get())
            #print("Encoder distance: ", self.fourbar_encoder.distance)
            #if not (self.fourbar.top_switch.get() and self.fourbar.bottom_switch.get()):
             #   self.macro_stop()
            if self.ERROR >= 0: # and self.fourbar.top_switch.get():
                #print("Started")
                #if self.ERROR < self.setpoint * .8:
                #    self.fourbar.elevate_speed(.6zse                #elif self.fourbar_encoder.distance < self.setpoint:
                #    self.fourbar.elevate_speed(.3)
                if self.ERROR > 3:
                    self.fourbar.elevate_speed(.8)
                if self.ERROR > 2 and abs(self.ERROR) <= 3:
                    self.fourbar.elevate_speed(.2)
                elif self.ERROR <= 2 and self.ERROR > .5:
                    self.fourbar.elevate_speed(.1)
                if self.ERROR <= .5:
                    #self.ERROR = 0
                    #print("Stopped +")
                    self.macro_stop()
            elif self.ERROR < 0:
                #print("Started")
                #if self.ERROR < self.setpoint * .8:
                #    self.fourbar.elevate_speed(.6)
                #elif self.fourbar_encoder.distance < self.setpoint:
                #    self.fourbar.elevate_speed(.3)
                if abs(self.ERROR) > 3:
                    self.fourbar.elevate_speed(-.8)
                if abs(self.ERROR) > 2 and abs(self.ERROR) <= 3:
                    self.fourbar.elevate_speed(-.2)
                elif abs(self.ERROR) <= 2 and abs(self.ERROR) > .5:
                    self.fourbar.elevate_speed(-.1)
                if abs(self.ERROR) <= .5:
                    #self.ERROR = 0
                    #print("Stopped -")
                    self.macro_stop()
            else:
                print("Stopping")
                #self.counter += 1
                #print(self.counter)
                self.macro_stop()

        """else:
            if not self.fourbar.bottom_switch.get() and self.fourbar.bottom_limit_switch.get() and self.fourbar.fourbar_motor.get() < 0:
                print("Slowly descending")
                #if self.fourbar.fourbar_motor.get() < 0:
                self.fourbar.elevate_speed(-.1)
            if not self.fourbar.bottom_limit_switch.get():
                if self.fourbar.fourbar_motor.get() < 0:
                    print("Stopping")
                    self.macro_stop()"""

            #if not self.fourbar.bottom_limit_switch.get():
            #    self.macro_stop()
            #else:
            #    self.macro_stop()

            #if not self.fourbar.top_switch.get():
             #   self.macro_stop()
              #  self.at_top = True
            #if not self.fourbar.bottom_switch.get():
             #   self.macro_stop()
              #  self.at_bottom = True

    def macro_stop(self):
        self.fourbar.stop()

    def re_zero(self):
        #We want to be able to do other things on the robot while the re-zeroing is occurring.
        temp_thread = threading.Thread(target=self.run_re_zero)
        temp_thread.start()

    def run_re_zero(self):
        tinit = time.time()
        tdif = time.time() - tinit
        while self.fourbar.bottom_limit_switch.get() and tdif < 5:
            self.enabled = False #Prevents the macro from fighting the re-zero.
            self.fourbar.elevate_speed_safe(-.2)
            tdif = time.time() - tinit
            time.sleep(.2)
        self.enabled = True
        self.fourbar_encoder.reset()
        self.setpoint = 0
        self.current_state = "level0"
        self.lift_to("level0")
        if self.fourbar.bottom_limit_switch.get():
            print("Re-zeroing has timed out! The encoder has been reset anyway, but the zero may not be correct.")
        else:
            print("Re-zeroing successfully completed.")

    def getDeviceID(self):
        #Yes, this is pretending to be a Talon.
        return self.index_id
    def get(self):
        """if self.index_id == 0:
            return self.current_state
        elif self.index_id == 1:
            return self.fourbar_encoder.distance
        elif self.index_id == 2:
            return self.setpoint
        elif self.index_id == 3:
            return self.ERROR
        else:
            print("This index does not record anything.")
            return "No record"
        """
        """
        Call the following code (or something similar) on this tuple to re-parse it
        and return the value you want:

        a = [(1,2,3),(4,5,6),(7,8,9)]
        b = []
        for i in a:
            b.append(i[0])  #Replace 0 with the index you want.
        print(b)

        Yes, this means that the instructions will be an ordered dictionary of lists of tuples. :)
        """

        #return self.current_state, self.fourbar_encoder.distance, self.setpoint, self.ERROR
        return self.setpoint

    def set(self, state):
        #wanted_instructions = []
        #wanted_instructions.append()
        self.setpoint = state #state[2]
        #print(state)

    def lift_to(self, state):
        #Add in self.enabled logic here!
        #These macros are always running, each in their own separate background thread, but
        #they only do anything interesting when enabled by their specific methods.
        #They can also stop themselves easily (or be stopped by something else easily)
        #by disabling them.
        #In an emergency, their threads can also be terminated. This method will require
        #the macro's thread to be restarted before it can be used again.
        #self.running = False
        self.initial_distance = 0
        self.setpoint = self.STATE_DICT[state] #-self.STATE_DICT[state] + self.fourbar_encoder.distance #self.STATE_DICT[self.current_state]
        self.current_state = state
        #self.terminate()
        #print("Open threads: ", threading.active_count())
        print(self.setpoint)
        print("Encoder distance: ", self.fourbar_encoder.distance)
        #self.run_threaded()
        #thread = threading.Thread(target=self.initialize)
        #thread.Start()
        #self.initialize()

    def traveled_distance(self):
        return abs(self.fourbar_encoder.distance - self.initial_distance)
        #return self.fourbar_encoder.distance

    """
    def run_fourbar_macro(self):
        if(self.setpoint>0):
            while(self.traveled_distance() < self.setpoint * .8):
                print("travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(.6)
            while(self.traveled_distance() < self.setpoint):
                print("half power travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(.3)
            self.fourbar.stop()
        elif(self.setpoint<0):
            while(self.traveled_distance() > self.setpoint * .8):
                print("travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(-.6)
            while(self.traveled_distance() > self.setpoint):
                print("half power travel: %f" % self.traveled_distance())
                self.fourbar.elevate_speed(-.3)
            self.fourbar.stop()
        self.kill()
    """


import speech_recognition as sr
import pyttsx3
# import win32api

recog = sr.Recognizer()
engine = pyttsx3.init()

def listen():
    with sr.Microphone() as source:
        sound = recog.listen(source)

    try:
        result = recog.recognize_google(sound)
        return {"result": result}

    except sr.UnknownValueError:
        return {"error": "Google Speech Recognition could not understand audio"}

    except sr.RequestError as e:
        return {"error": "Could not request results from Google Speech Recognition service; {0}".format(e)}

def speak(text):
    # # Language in which you want to convert
    # language = 'en'

    # myobj = gTTS(text=text, lang=language, slow=False)

    # # Saving the converted audio in a mp3 file named
    # # welcome
    # myobj.save("text.mp3")

    # # Playing the converted file
    # system("text.mp3")

    # getting details of current speaking rate
    # rate = engine.getProperty('rate')
    # print(rate)  # printing current voice rate
    engine.setProperty('rate', 150);

    # voices = engine.getProperty('voices')  # getting details of current voice
    # print(voices)
    # engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
    engine.setProperty('voice', engine.getProperty('voices')[0].id)

    # getting to know current volume level (min=0 and max=1)
    # volume = engine.getProperty('volume')
    # print(volume)  # printing current volume level

    engine.say(text)
    engine.runAndWait()


'''comment'''
from fastapi import APIRouter
from fastapi_pagination import  Page, add_pagination, paginate
from config.database import SessionLocal
from schemas.comment import CommentSchema, CommentBase, EpisodeComment, CharacterComment, CommentUpdate
from crud.comment import create_comment, create_comment_episode, create_comment_character, get_exported_comment
from models.comment import Comment

app = APIRouter()
session=SessionLocal()
@app.post("/commentsCharactersEpisodes/", response_model=CommentSchema)
def add_comment(comment_data:CommentBase):
    """Add a comment for character in episode."""
    comment_data= create_comment(session, comment_data)
    return comment_data

@app.post('/addCommentEpisode')
def create_episode_comment(episode_comment:EpisodeComment):
    """Add a comment for episode."""
    comment_episode=create_comment_episode(session,episode_comment)
    return comment_episode

@app.post('/addCommentCharacter')
def add_character_comment(character_comment:CharacterComment):
    """Add a comment for character."""
    comment_character=create_comment_character(session,character_comment)
    return comment_character

@app.get("/comments/page", response_model=Page[CommentSchema])
def get_comments():
    """Add pagination."""
    db_comments = session.query(Comment).all()
    return paginate(db_comments)

@app.get("/comments/{id}", response_model=CommentSchema)
def get_comments_by_id(id_comment:int):
    """Get comments by id."""
    db_comments = session.query(Comment).get(id_comment)
    return db_comments

@app.get('/ExportComments')
def export_comments():
    """ Export comments API."""
    get_exported_comment(session)
    return {'message': 'Comments are exported into csv'}

@app.delete("/comment/{id}")
def delete_comment_info(id_comment: int):
    """Delete Comments by id."""
    comment_info = session.query(Comment).get(id_comment)
    session.delete(comment_info)
    session.commit()
    return {'message': 'The comment is deleted successfully'}

@app.put("/comment/{id}")
def update_comment(id_comment: int, comment_update: CommentUpdate)->Comment:
    """Modify comments."""
    comment_info = session.query(Comment).get(id_comment)
    comment_info.comment = comment_update.comment
    session.commit()
    session.refresh(comment_info)
    return comment_info

add_pagination(app)


from PyQt5.QtWidgets import QWidget,QDesktopWidget,QLineEdit,QPushButton,QLabel,QMessageBox
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
import sys

from utils.UserMsgUnpick import addfriendunpick
from web.setting import *

class AddFriend(QWidget):
    def __init__(self):
        super().__init__()
        self.__initUI()

    def __initUI(self):
        self.loadInput()
        self.loadSubmit()
        self.hidelabel()
        self.setStyleSheet("""
            QWidget{
                background-color: #4169E1;
            }
            QWidget#msgLabel{
                font-size: 40px;
                font-family: 'Microsoft Yahei';
            }
        """)
        # self.loadbackground()
        # self.loadHiddenLabel()
        # self.loadExitMenu()
        self.loadFriend()
        self.addbtn()

        self.loadSelf()
        self.closelabel()

    def md5_analyse(self, psw):
        if self.md5 != psw:
            return False
        else:
            return True

    def addbtn(self):
        self.add_friend_btn = QPushButton(self)
        self.add_friend_btn.resize(60, 30)
        self.add_friend_btn.setText("添加好友")
        self.add_friend_btn.clicked.connect(self.addfriend)
        self.add_friend_btn.move(145, 180)
        self.add_friend_btn.close()

    def hidelabel(self):
        self.headlabel = QLabel(self)
        self.namelabel = QLabel(self)
        self.idlabel = QLabel(self)
        self.headlabel.setStyleSheet(testBorder)
        self.namelabel.setStyleSheet(testBorder)
        self.idlabel.setStyleSheet(testBorder)

    def addfriend(self):
        opid = self.lineText.text()
        data = REQUEST_HEADS["ADD_FRIEND_HEAD"] + SEPARATE + opid + SEPARATE + self.uid + SEPARATE + self.md5
        self.sock.writeData(data.encode())

    def closelabel(self):
        self.nullLabel.show()
        self.add_friend_btn.close()
        self.idlabel.close()
        self.headlabel.close()
        self.namelabel.close()

    def loadSelf(self):
        self.setFixedSize(350, 300)
        self.center()
        self.setWindowTitle("添加好友")

    def handle_click(self, userid, sock , key):
        self.sock = sock
        self.uid = userid
        self.md5 = key
        self.show()

    def loadInput(self):
        self.lineText = QLineEdit(self)
        self.lineText.resize(250, 30)
        self.lineText.move(20, 250)
        self.lineText.setPlaceholderText("输入对方SQ号")

    def loadSubmit(self):
        submitBtn = QPushButton(self)
        submitBtn.resize(50, 30)
        submitBtn.setText("查找")
        submitBtn.move(274, 250)
        submitBtn.clicked.connect(self.search_friend)

    def search_friend(self):
        id_or_name = self.lineText.text()
        send_str = REQUEST_HEADS["GET_USER_HEAD"] + SEPARATE + id_or_name + SEPARATE + self.md5
        self.sock.writeData(send_str.encode())
        # if not user:
        #     self.nullLabel.setText("什么都没找到哦^-^")
        # else:
        #     self.friend = user
        #     self.loadFriend()

    def loadFriend(self):
        if not hasattr(self, "friend"):
            self.nullLabel = QLabel(self)
            self.nullLabel.setObjectName("msgLabel")
            self.nullLabel.resize(300, 200)
            self.nullLabel.setText("点击按钮查找>-<")
            self.nullLabel.move(25, 25)
        else:
            self.nullLabel.close()

            id = self.friend.get_id()
            id = "SQ号："+str(id)
            name = "对方昵称："+self.friend.get_name()
            head = self.friend.get_head()

            self.idlabel.setText(id)
            self.idlabel.move(145, 110)

            self.namelabel.setText(name)
            self.namelabel.move(130, 150)

            self.headlabel.resize(70, 70)
            if not head:
                self.headlabel.setPixmap(QPixmap(DEFAULT_HEAD))
            else:
                self.headlabel.setPixmap(QPixmap(head))
            self.headlabel.setScaledContents(True)
            self.headlabel.move(140, 30)

            self.idlabel.show()
            self.headlabel.show()
            self.namelabel.show()
            self.add_friend_btn.show()

    def closeEvent(self, event):
        event.accept()

    # 移动至中心
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def show_warn_msgbox(self, msg):
        reply = QMessageBox.information(self, "提示", msg,QMessageBox.Yes)

if __name__ == "__main__":
    appstart = QtWidgets.QApplication(sys.argv)
    addfriend = AddFriend()
    addfriend.show_warn_msgbox()
    sys.exit(appstart.exec_())


import sys

__author__ = 'lizuyao'
# print(__doc__)
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import datasets
from sklearn.decomposition import PCA
from sklearn import preprocessing
from unbalanced_dataset import UnderSampler
import numpy
# import some data to play with
fileName=sys.argv[1]
X,Y = datasets.load_data(fileName)
# X = numpy.loadtxt("tsne_python/mnist2500_X.txt")
# Y = numpy.loadtxt("tsne_python/mnist2500_labels.txt")
# scaler = preprocessing.StandardScaler().fit(X)
# X=scaler.transform(X)

# To getter a better understanding of interaction of the dimensions
# plot the first three PCA dimensions
fig = plt.figure(1, figsize=(8, 6))
ax = Axes3D(fig, elev=-150, azim=110)
pca=PCA()
X_reduced = pca.fit_transform(X)

# plt.figure(1, figsize=(4, 3))
# plt.clf()
# plt.axes([.2, .2, .7, .7])
# plt.plot(pca.explained_variance_, linewidth=2)
# plt.axis('tight')
# plt.xlabel('n_components')
# plt.ylabel('explained_variance_')

# Generate the new dataset using under-sampling method
verbose = False
# 'Random under-sampling'
# ratio of majority elements to sample with respect to the number of minority cases.
US = UnderSampler(ratio=1.,verbose=verbose)
X_reduced, Y = US.fit_transform(X_reduced, Y)

ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=Y, cmap=plt.cm.Paired)
ax.set_title("First three PCA directions")
ax.set_xlabel("1st eigenvector")
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("2nd eigenvector")
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("3rd eigenvector")
ax.w_zaxis.set_ticklabels([])
# outFile3D=sys.argv[2]
# fig.savefig(outFile3D)

# for ii in xrange(0,360,1):
#     ax.view_init(elev=10., azim=ii)
#     fig.savefig("move_r/movie"+str(ii)+".png")

# To getter a better understanding of interaction of the dimensions
# plot the first two PCA dimensions
x_min, x_max = X_reduced[:, 0].min() - .5, X_reduced[:, 0].max() + .5
y_min, y_max = X_reduced[:, 1].min() - .5, X_reduced[:, 1].max() + .5
plt.figure(2, figsize=(8, 6))
plt.clf()
# Plot the training points
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=Y, cmap=plt.cm.Paired)
plt.xlabel('1st eigenvector')
plt.ylabel('2nd eigenvector')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
# outFile2D=sys.argv[3]
# plt.savefig(outFile2D="pic/pca_2_r.png")
plt.show()


#!/usr/bin/python3

import stl
import sys
import math

def minmax_r(m):
    by_x = {}

    for xx, yy, zz in zip(list(m.x), list(m.y), list(m.z)):
        for x, y, z in zip(list(xx), list(yy), list(zz)):
            r = math.hypot(y, z)
            m, M = by_x.get(x, (r, r))
            by_x[x] = min(m, r), max(M, r)

    d3 = []
    for x, (y, Y) in by_x.items():
        d3.append((x, y))
        d3.append((x, Y))

    d3.sort()
    return d3

for p in sys.argv[1:]:
    print(p)
    m = stl.mesh.Mesh.from_file(p)
    d3 = minmax_r(m)
    csv = open(p.removesuffix('.stl') + '.csv', 'w')
    for x, y in d3:
        print(x, y, file=csv, sep=',')


# Crear una función que se llame ordenarCaracteres que reciba una cadena de caracteres como parámetro  y
# su responsabilidad es ordenar los caracteres de manera ascendente dentro de la cadena. Ejemplo si le pasamos
# "algoritmo" la deja como "agilmoort"

def ordenarCaracteres(cadena):
    lista=[]
    for caracter in cadena:
        lista.append(caracter)
    tam=len(lista)
    for i in range(tam-1):
        for j in range(i+1,tam):
            if(lista[i]>lista[j]):
                aux=lista[i]
                lista[i]=lista[j]
                lista[j]=aux
    cadena_reordenada="".join(lista)
    return cadena_reordenada

cadena=input("Cadena -> :")
orden_ascendente=ordenarCaracteres(cadena)
print(orden_ascendente)


# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'Country'
        db.create_table('countrytotrialnumbermapping_country', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('country_name', self.gf('django.db.models.fields.TextField')(unique=True)),
            ('country_code', self.gf('django.db.models.fields.TextField')()),
        ))
        db.send_create_signal('countrytotrialnumbermapping', ['Country'])

        # Adding model 'Network'
        db.create_table('countrytotrialnumbermapping_network', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('network_name', self.gf('django.db.models.fields.TextField')()),
            ('trial_sms_number', self.gf('django.db.models.fields.TextField')()),
        ))
        db.send_create_signal('countrytotrialnumbermapping', ['Network'])

        # Adding M2M table for field country on 'Network'
        db.create_table('countrytotrialnumbermapping_network_country', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('network', models.ForeignKey(orm['countrytotrialnumbermapping.network'], null=False)),
            ('country', models.ForeignKey(orm['countrytotrialnumbermapping.country'], null=False))
        ))
        db.create_unique('countrytotrialnumbermapping_network_country', ['network_id', 'country_id'])

    def backwards(self, orm):

        # Deleting model 'Country'
        db.delete_table('countrytotrialnumbermapping_country')

        # Deleting model 'Network'
        db.delete_table('countrytotrialnumbermapping_network')

        # Removing M2M table for field country on 'Network'
        db.delete_table('countrytotrialnumbermapping_network_country')

    models = {
        'countrytotrialnumbermapping.country': {
            'Meta': {'object_name': 'Country'},
            'country_code': ('django.db.models.fields.TextField', [], {}),
            'country_name': ('django.db.models.fields.TextField', [], {'unique': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'countrytotrialnumbermapping.network': {
            'Meta': {'object_name': 'Network'},
            'country': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['countrytotrialnumbermapping.Country']", 'symmetrical': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'network_name': ('django.db.models.fields.TextField', [], {}),
            'trial_sms_number': ('django.db.models.fields.TextField', [], {})
        }
    }

    complete_apps = ['countrytotrialnumbermapping']


import numpy as np
from numpy import tile

class Algorithm_kNN(object):
    """k近邻算法简单实现"""

    def __init__(self, sample_data, label, k):
        self.sample_data = sample_data
        self.label = label
        self.k = k

    def autoNorm(self, dataSet):
        """归一化特征值"""
        # newValue = (oldValue-min)/(max-min)
        dataMax = dataSet.max(0)
        dataMin = dataSet.min(0)
        m = dataSet.shape[0]
        dataSetMin = tile(dataMin, (m, 1))
        dataSetRange = tile(dataMax - dataMin, (m, 1))
        return (dataSet - dataSetMin)/dataSetRange

    def run(self, target_data):

        #样本数
        sample_count = self.sample_data.shape[0]

        # 获取目标向量和样本之间的距离（欧式距离公式）d = ((xA0-xB0)**2 + (xA1-xB1)**2 + ...+ (xAn-xBn)**2)**0.5
        target_ = np.tile(target_data, (sample_count, 1)) - self.sample_data
        target_dis = ((target_**2).sum(axis=1))**0.5

        # 获取最近k个样本的标签索引
        tar_dis_order = target_dis.argsort()

        # 获取目标预测
        result = dict()
        for i in range(self.k):
            label = self.label[tar_dis_order[i]]
            result[label] = result.get(label, 0) + 1

        #对预测的结果进行排序，取出最优结果
        resultOrder = sorted(result.items(), key=lambda x: x[0], reverse=True)
        return resultOrder[0][0]

if __name__ == '__main__':
    sampleData = np.array([[0, 0], [0, 0.1], [1, 1], [1.1, 1]])
    label = ['A', 'A', 'B', 'B']
    textData = np.array([[0.1, 0.2], [1, 2], [100, 100], [-1, -1]])
    knn = Algorithm_kNN(sampleData, label, 2)
    for data in knn.autoNorm(textData):
        targetLable = knn.run(data)
        print(data, targetLable)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter
from time import localtime, strftime
from threading import Thread, Semaphore, Condition

class GUI(tkinter.Tk):

    def __init__(self, parent, nick, networkhandler):
        tkinter.Tk.__init__(self, parent)
        self.grid()
        self.title("Cryptchat")
        self.out_message = []

        self.text = TextArea(self, height=25, width=50, font=("Droid Sans Mono", 12))
        self.text.grid(row=0, column=0, sticky="NW")
        self.text.pack()

        self.entry = TextEntry(self, nick, 50, font=("Droid Sans Mono", 12))
        self.entry.grid(row=2, column=0, sticky="SW")
        self.entry.pack()

        self.out_sem = Semaphore(0)
        self.out_condition = Condition()
        self.app_condition = Condition()

        sthread = SendThread(self, networkhandler)
        rthread = ReceiveThread(self, networkhandler)
        sthread.start()
        rthread.start()

        self.resizable(width=False, height=False)
        self.mainloop()

    def appendstring(self, sender, string):
        self.app_condition.acquire()
        t = ["<", strftime("%H:%M:%S", localtime()), "> ", "[", sender, "] ", string, "\n"]
        self.text.appendstring("".join(t))
        self.app_condition.notifyAll()
        self.app_condition.release()

    def get_sendmessage(self):
        '''
        Called by SendThread
        '''
        self.out_sem.acquire()
        self.out_condition.acquire()
        m = self.out_message.pop(0)
        self.out_condition.notifyAll()
        self.out_condition.release()
        return m

    def queue_sendmessage(self, m):
        '''
        Called by TextEntry
        '''
        self.out_condition.acquire()
        self.out_message.append(m)
        self.out_sem.release()
        self.out_condition.notifyAll()
        self.out_condition.release()

class TextArea(tkinter.Text):

    def __init__(self, parent, height, width, font):
        tkinter.Text.__init__(self, parent, height=height, width=width, font=font)
        self.parent = parent
        self.config(state="disabled")

    def appendstring(self, string):
        self.config(state="normal")
        self.insert(tkinter.END, string)
        self.see(tkinter.END)
        self.config(state="disabled")

class TextEntry(tkinter.Entry):

    def __init__(self, parent, nick, width, font):
        tkinter.Entry.__init__(self, parent, width=width, font=font)
        self.parent = parent
        self.nick = nick
        self.bind("<Return>", self.actionperformed)

    def actionperformed(self, *args):
        string = self.get()
        if len(string) > 0:
            self.parent.appendstring(self.nick, string)
            self.parent.queue_sendmessage(" ".join([self.nick, string]))
            self.delete(0, tkinter.END)

class ReceiveThread(Thread):

    def __init__(self, gui, networkhandler):
        super(ReceiveThread, self).__init__()
        self.networkhandler = networkhandler
        self.gui = gui
        self.setDaemon(True)

    def run(self):
        while True:
            m = self.networkhandler.receive()
            splitted = m.split(" ", 1)
            self.gui.appendstring(splitted[0], splitted[1])

class SendThread(Thread):

    def __init__(self, gui, networkhandler):
        super(SendThread, self).__init__()
        self.networkhandler = networkhandler
        self.gui = gui
        self.setDaemon(True)

    def run(self):
        while True:
            m = self.gui.get_sendmessage()
            self.networkhandler.send(m)


# Напишите программу для проверки истинности утверждения ¬(X ⋁ Y ⋁ Z) = ¬X ⋀ ¬Y ⋀ ¬Z для всех значений предикат.
# ¬ - Отрицание ⋁ - логическое "Или" ⋀ - логическое "И"

ls = [True, True, True]
for i in range(2):
    ls[0] = True if ls[0] == False else False
    for j in range(2):
        ls[1] = True if ls[1] == False else False
        for h in range(2):
            ls[2] = True if ls[2] == False else False
            x = ls[0]
            y = ls[1]
            z = ls[2]
            print(f'X = {x} Y = {y} Z = {z}')
            a = not (x or y or z)
            print(f"¬(X ⋁ Y ⋁ Z) = {a}")
            b = (not x) and (not y) and (not z)
            print(f'¬X ⋀ ¬Y ⋀ ¬Z = {b}')
            result = a == b
            print(f"¬({x} ⋁ {y} ⋁ {z}) = ¬{x} ⋀ ¬{y} ⋀ ¬{z} is {result}\n")

Знакомство с языком Python/Semminar1/Task2/Task2.py