import copy
inf = 9999

m = [[0, 1, 12, inf, inf, inf],
     [inf, 0, 9, 3, inf, inf],
     [inf, inf, 0, inf, 5, inf],
     [inf, inf, 4, 0, 13, 15],
     [inf, inf, inf, inf, 0, 4],
     [inf, inf, inf, inf, inf, 0]
     ]

# m = [[0, 2, 6, 4],
#      [inf, 0, 3, inf],
#      [7, inf, 0, 1],
#      [5, inf, 12, 0]]

size = len(m[0])

def init_route(e):
    route = copy.deepcopy(e)
    for i in range(size):
        for j in range(size):
            if e[i][j] != inf:
                route[i][j] = [i, j]
                if e[i][j] == 0:
                    route[i][j] = [i]
            else:
                route[i][j] = []
    return route

def print_route(e, route, start, end):
    if len(route[start][end]) > 1:
        route_ = [str(i) for i in route[start][end]]
        print('route: ' + '-->'.join(route_))
        print('distance: {}'.format(e[start][end]))
    elif len(route[start][end]) == 1:
        print('不动')
        print('distance: 0')

    else:
        print("Cant't Arrive!!!")

# dijkstra https://blog.csdn.net/lbperfect123/article/details/84281300
def dijkstra(e, route, rownum):
    dis = copy.deepcopy(e[rownum])
    vis = [0 for i in range(size)]
    for i in range(size):
        min = inf
        for i in range(size):
            if not vis[i] and dis[i] < min:
                min, temp = dis[i], i
        vis[temp] = 1
        for i in range(size):
            if dis[temp] + e[temp][i] < dis[i]:
                dis[i] = dis[temp] + e[temp][i]
                route[rownum][i] = route[rownum][temp][:-1] + route[temp][i]
    return dis

def dijkstra_pro(m, start, end):
    e = copy.deepcopy(m)
    route = init_route(e)
    for i in range(size):
        e[i] = dijkstra(e, route, i)

    print_route(e, route, start, end)

# floyd https://blog.csdn.net/Harington/article/details/81982299
def floyd_route(m, start, end):
    e = copy.deepcopy(m)
    route = init_route(e)
    for k in range(size):
        for i in range(size):
            for j in range(size):
                if e[i][k] != inf and e[k][j] != inf and e[i][j] > e[i][k]+e[k][j]:
                    e[i][j] = e[i][k] + e[k][j]
                    route[i][j] = route[i][k][:-1] + route[k][j]

    print_route(e, route, start, end)

if __name__ == '__main__':
    dijkstra_pro(m, 5, 4)
    floyd_route(m, 4, 5)


import os, sys, csv
import boto3, shutil
import pandas as pd
from pprint import pprint as pp

e=sys.exit
linesep	= '\n'
colsep	= ','

s3			= boto3.client('s3')
bucket 		= 'crossix-test'
file_name 	= 'cust_list2.csv'
colname 	= 'customer_name'
to_dir 	= r'N:\Analysis\unique_customers.txt'

sql_stmt = """SELECT S.%s FROM s3object S LIMIT 10"""  % colname

import tempfile

from_dir =tempfile.gettempdir()
#e()

req = s3.select_object_content(
    Bucket	= bucket,
    Key		= file_name,
    ExpressionType	= 'SQL',
    Expression		= sql_stmt,
    InputSerialization 	= {'CSV': {'FileHeaderInfo': 'USE'}},
    OutputSerialization = {'CSV': {}},
)

out=set()
if 1:
	#get usique customer names
	for event in req['Payload']:
		if 'Records' in event:
			rr=event['Records']['Payload'].decode('utf-8')
			#pp(rr)
			for rec in rr.split(linesep):
				if rec:
					row=rec.split(colsep)
					cn = row[0].strip()
					out.add(cn)

	print('Unique customer names:')
	pp(out)
	tmpfn = os.path.join(from_dir, 'unique_cn.csv')

	#write to local tmp file
	with open(tmpfn, mode='w') as fh:

		csvw = csv.writer(fh, delimiter = ',', quotechar = '"', lineterminator = '\n',  quoting=csv.QUOTE_MINIMAL)
		for cn in out:
			csvw.writerow([cn])

	assert tmpfn

	print(to_dir)
	#copy to network share
	st = shutil.copy(tmpfn, to_dir) #r'c:\tmp')

	e(0)


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

import sys
sys.path.append('../../ia/')
import logging
import os

logging.basicConfig(filename=os.path.join(os.path.dirname(os.path.abspath(__file__)), "log.log"), filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__.split('.')[0])

import communication
from socket import *
import time
import threading

myHost = ''
myPort = 2001

#init comm
com = communication.CommunicationGlobale()
sock = socket(AF_INET, SOCK_STREAM)    # create a TCP socket
sock.bind((myHost, myPort))            # bind it to the server port
sock.listen(5)                         # allow 5 simultaneous

def update():
	if len(sys.argv) == 2:
		addr = sys.argv[1]
	else:
		addr = 2
	print("Position update on adress " + str(addr))
	while 1:
		com.sendOrderAPI(addr, 'A_GET_POS')
		ret = -1
		while ret == -1:
			ret = com.readOrdersAPI()
			time.sleep(0.01)
		data = ":".join(str(el) for el in ret[2])
		print(data)
		connection.send(bytes(data, 'utf-8'))
		time.sleep(0.1)

while 1:
	# wait for next client to connect
	print("Ready, waiting for socket connection")
	global connection
	global address
	connection, address = sock.accept()   # connection is a new socket
	print("Connection established")
	threading.Thread(target=update).start()
	while 1:
		data_rec = connection.recv(1024)  # receive up to 1K bytes
		if data_rec:
			data_rec = [data.split(':') for data in str(data_rec, 'utf-8').split('!')[:-1]] #conversion chaine en liste
			for data in data_rec:
				data[0] = int(data[0])
				#conversion data
				if data[1] == 'A_GOTOA': #deux int  un float
					data[2] = int(data[2])
					data[3] = int(data[3])
					data[4] = float(data[4])
				elif data[1] == 'A_PIDA' or data[1] == 'A_PIDD' or data[1] == 'A_ROT' or data[1] == 'A_ACCMAX': #all float
					for i in range(2,len(data)):
						data[i] = float(data[i])
				elif data[1] == 'A_GOTO': #all int
					for i in range(2,len(data)):
						data[i] = int(data[i])
				elif data[1] == 'A_PWM': #all int
					for i in range(2,len(data)):
						data[i] = int(data[i])
				elif data[1] == 'A_SET_POS': #all int
					data[2] = int(data[2])
					data[3] = int(data[3])
					data[4] = float(data[4])

				if data[1] == 'A_GOTO' or data[1] == 'A_GOTOA' or data[1] == 'A_ROT' or data[1] == 'A_PWM':
					data.insert(2, 0) #ajout id

				print('Data : ' + str(data))
				com.sendOrderAPI(data[0], data[1], *data[2:])
		else:
			break
	connection.close()              # close socket


from at import physics
import matlab
import numpy
import pytest

@pytest.mark.parametrize('dp', (0, 1e-8, 1e-7, 1e-6))
@pytest.mark.parametrize('refpts', (None, [1], [1, 2, 3]))
def test_find_orbit4(engine, ml_lattice, py_lattice, dp, refpts):
    # Matlab call
    ml_refpts = (matlab.double([]) if refpts is None else
                 matlab.double(list(r + 1 for r in refpts)))
    ml_orbit4 = engine.findorbit4(ml_lattice, dp, ml_refpts)
    py_ml_orbit4 = numpy.asarray(ml_orbit4)

    # Python call
    py_orbit4 = physics.find_orbit4(py_lattice, dp, refpts)

    numpy.testing.assert_almost_equal(py_ml_orbit4, py_orbit4.T)

@pytest.mark.parametrize('dp', (0.0, 1e-8, 1e-7, 1e-6))
@pytest.mark.parametrize('refpts', (None, [1], [1, 2, 3], [145]))
def test_find_m44(engine, ml_lattice, py_lattice, dp, refpts):
    # Matlab call
    ml_refpts = (matlab.double([]) if refpts is None else
                 matlab.double(list(r + 1 for r in refpts)))
    ml_m44, ml_mstack = engine.findm44(ml_lattice, dp, ml_refpts, nargout=2)
    py_ml_m44 = numpy.asarray(ml_m44)

    # Python call
    py_m44, py_mstack = physics.find_m44(py_lattice, dp, refpts)

    py_mstack = numpy.squeeze(py_mstack)
    # Matches to 5 d.p.
    numpy.testing.assert_almost_equal(py_ml_m44, py_m44.T, decimal=5)
    assert py_mstack.T.shape == tuple(numpy.asarray(ml_mstack).shape)
    # Matches to 5 d.p.
    numpy.testing.assert_almost_equal(py_mstack.T, numpy.asarray(ml_mstack), decimal=5)


# Copyright (c) 2014, Adaptiv Design
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.

# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.

# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.

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

import os.path

from rollout.fabric.locations.base import Location
from rollout.fabric.operations import *
from rollout.shell import shell

__all__ = ['LocalLocation']

class LocalLocation(Location):

    def put(self, source, destination, raw=False, chown=True, ensure_dir=True):
        destination = self.ensure_safe_path(destination)

        if ensure_dir:
            self.ensure_dir(os.path.dirname(destination))

        def write(input):
            with open(destination, 'w') as destination_file:
                destination_file.writelines(input.readlines())

        if not raw:
            with open(source, 'r') as source_file:
                write(source_file)
        else:
            write(source)

        if chown:
            self.chown(destination)

    def chown(self, destination):
        if self.user and self.group:
            self.run('chown {0}:{1} {2} -R'.format(self.user, self.group, destination))
        elif self.user:
            self.run('chown {0} {1} -R'.format(self.user, destination))

    def exists(self, path):
        return os.path.exists(self.ensure_safe_path(path))

    def ensure_dir(self, path, present=True):
        path = self.ensure_safe_path(path)
        if present:
            self.run('mkdir {0} -p'.format(path))
            self.chown(self.path)
        else:
            if shell.confirm("Remove local dir '{0}'".format(path)):
                self.run('rm -f {0} -R'.format(path))
            else:
                raise Exception("Local dir '{0}' was not removed".format(path))

    def cd(self, path):
        return lcd(self.ensure_safe_path(path))

    def run(self, *args, **kwargs):
        if self._interactive and 'capture' not in kwargs:
            kwargs['capture'] = False
        return local(*args, **kwargs)

    def sudo(self, *args, **kwargs):
        return local(*args, **kwargs)

    def open_shell(self, *args, **kwargs):
        raise Exception("Not available for local location.")


import json
from pprint import pprint

with open ("newsafr.json") as f:
    data = json.load(data_file)
    pprint (data)

def count_length (text):
    text_list = text.split(" ")
    text_set = set()
    for i in text_list:
        if len(i) > 6:
            text_set.add(i)
    word_value = {}
    for i in text_set:
        count = 0
        for j in text_list:
            if i == j:
                count += 1
        word_value[i] = count
    return word_value