#!/usr/bin/env python
import nltk
import os
import time

import nltk

from neo4j import GraphDatabase

# uri = "bolt://localhost:7687"
uri = os.environ.get('NEO_URL', "bolt://neo:7687")
DEBUG = os.environ.get('DEBUG', False)

GRAMMAR = r"""
  NP: {<CD|DT|PP\$>?<JJ[RS]*|PRP\$*>*<NN.*>+} # Chunk sequences of DT, JJ, NN, chink out VPs
  PP: {<IN><PR.*>*<N.*>}                           # Chunk prepositions followed by NP
  XPP: {<IN><.*>+<N.*>}                           # Chunk prepositions followed by NP
  VP: {<VB(?!P).*>+<RB>*(<PRP><JJ>)*}             # Chunk verbs and their arguments
  NOUNANDVERB: {<NP><VP>}                  # Chunk NP to VP
  VERBANDPREP: {<VP><PP>}
  GOODNOUNSANDVERBS: {<NN.*><VB.*>+}
  SENTENCE: {<NOUNANDVERB><PP>}
  """

def connect_to_neo(uri=""):
    for i in range(1,60):
        while True:
            try:
                driver = GraphDatabase.driver(uri, connection_timeout=120)
            except Exception as e:
                print(f"Error number {i}. {e}.")
                print(f"Error number {i} connecting to neo, sleeping for 2 seconds")
                time.sleep(2)
            break
    return driver

def get_random_phrases(session=None, p_type="" ):
    rwords = list()
    cypher = f"""MATCH NounBit=(p:Phrase)-[r:{p_type}]-() RETURN p.text, rand() as x order by x LIMIT 10"""
    words = session.run(cypher)
    for w in words:
        rwords.append(w['p.text'])
    return rwords

def filter_good_sentences(noun_phrases=[], verb_phrases=[]):
    sentences = list()
    rD = dict()
    for noun in noun_phrases:
        for verb in verb_phrases:
            sentence = " ".join([noun, verb])
            sentences.append(sentence)
    for sentence in sentences:
        tokenized = nltk.word_tokenize(sentence)
        postagged = nltk.pos_tag(tokenized)
        chunks = cp.parse(postagged)
        care_about = ['SENTENCE' ]
        for chunk_idx, chunk in enumerate(chunks.subtrees(filter=lambda t: t.label() in care_about )):
            rD[sentence] = {"chunks": chunks, "pos": postagged}
    return rD

if __name__ == "__main__":
    cp = nltk.RegexpParser(GRAMMAR)
    stemmer = nltk.stem.PorterStemmer()
    driver = connect_to_neo(uri=uri)

    noun_phrases = list()
    verb_phrases = list()

    with driver.session() as session:
        noun_phrases = get_random_phrases(session=session, p_type="NP")
        verb_phrases = get_random_phrases(session=session, p_type="VERBANDPREP")

    prototype_phrases = list()
    keep_sentences = dict()

    keep_sentences = filter_good_sentences(noun_phrases=noun_phrases, verb_phrases=verb_phrases)

    if DEBUG:
        for sentence, bits in keep_sentences.items():
            print(sentence)
            for idx, tree in enumerate(bits['chunks'].subtrees()):
                print(tree)
            print(bits['pos'])

    for sentence in keep_sentences.keys():
        print(sentence)


import os
from mock import patch, AsyncMock
import pytest
from httpx import AsyncClient
from src.main.app import app
from src.tests.controller.view.carrer import CarrerMother

@pytest.fixture()
def auth_header():
    os.environ["ADMIN_AUTH"] = "mock_auth"
    return {"admin-auth": "mock_auth"}

@pytest.mark.anyio
@patch("src.main.controller.carrer.CarrerRepository.create")
async def test_create(repository: AsyncMock, auth_header: dict):
    carrers = CarrerMother.create_many()
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.post(
            "/carrers", json=carrers.model_dump(), headers=auth_header
        )
    repository.assert_awaited_once_with(carrers)
    assert response.status_code == 200

@pytest.mark.anyio
@patch("src.main.controller.carrer.CarrerRepository.get_all")
async def test_get(repository: AsyncMock, auth_header: dict):
    carrers = CarrerMother.create_many_paginated()
    async with AsyncClient(app=app, base_url="http://test") as client:
        repository.return_value = carrers
        response = await client.get("/carrers", headers=auth_header)
    repository.assert_awaited_once()
    assert response.status_code == 200
    assert response.json()["result"] == carrers.model_dump()

@pytest.mark.anyio
@patch("src.main.controller.carrer.CarrerRepository.delete")
async def test_delete(repository: AsyncMock, auth_header: dict):
    id = 1
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.delete(f"/carrers/{id}", headers=auth_header)
    repository.assert_awaited_once_with(id)
    assert response.status_code == 200


import re  #importar libreria re
from tkinter import EW #importar libreria tkinter
from django.shortcuts import redirect, render
from app_gestion.models import Datos_vacuna
from app_gestion.forms import Datos_vacuna_Form

def index(request):
    Datos_vacunas = Datos_vacuna.objects.all()
    return render(request, '/front/Informacion/informacion.html', {'Datos_vacuna': Datos_vacunas})

def eliminar(request, rut):
    remover = Datos_vacuna.objects.get(rut=rut)
    remover.delete()
    return redirect('informacion')

def registrar(request):
    rut = request.POST.get('rut')
    nombre = request.POST.get('nombre')
    apellido_mat = request.POST.get('apellido_mat')
    apellido_pat = request.POST.get('apellido_pat')
    edad = request.POST.get('edad')
    vacuna = request.POST.get('vacuna')
    tipo_vacuna = request.POST.get('Tipo_Vacuna')
    fecha = request.POST.get('fecha')
    registro=Datos_vacuna.objects.create(rut=rut, nombre=nombre, apellido_mat=apellido_mat, apellido_pat=apellido_pat, edad=edad, vacuna=vacuna, fecha=fecha)
    return redirect('informacion')


from rest_framework import serializers

from carts.mixins import TokenMixin
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated

from .models import Order, StoreWiseOrder, PurchaseItem, Purchase
from datetime import timedelta
from products.models import Product, ProductImage
from products.serializers import VariationSerializer
from carts.models import Cart, CartItem
from store.models import Store
from store.serializers import StoreWiseOrderSerializer, StoreSerializer
import pprint
from django.contrib.auth import get_user_model
from django.conf import settings
from hms.utils import jwt_response_payload_handler
User = get_user_model()

# parse order token
# check order not complete
# nonce is coming through
# mark cart complete
# mark order done

# class QuotationSerializer(serializers.ModelSerializer):
# 	# authentication_classes = [, BasicAuthentication]
# 	permission_classes = [IsAuthenticated]
# 	class Meta:
# 		model = Quotation
# 		fields= '__all__'
# 		# fields = []

class FinalizedOrderSerializer(TokenMixin, serializers.Serializer):
	order_token = serializers.CharField()
	payment_method_nonce = serializers.CharField()
	order_id =  serializers.IntegerField(required=False)
	user_checkout_id = serializers.IntegerField(required=False)

	def validate(self, data):
		order_token = data.get("order_token")
		order_data = self.parse_token(order_token)
		order_id = order_data.get("order_id")
		user_checkout_id = order_data.get("user_checkout_id")

		try:
			order_obj = Order.objects.get(id=order_id, user__id=user_checkout_id)
			data["order_id"] = order_id
			data["user_checkout_id"] = user_checkout_id
		except:
			raise serializers.ValidationError("This is not a valid order for this user.")

		payment_method_nonce = data.get("payment_method_nonce")
		if payment_method_nonce == None:
			raise serializers.ValidationError("This is not a valid payment method nonce")

		return data

class OrderDetailSerializer(serializers.ModelSerializer):
	url = serializers.HyperlinkedIdentityField(view_name="order_detail_api")
	subtotal = serializers.SerializerMethodField()
	class Meta:
		model = Order
		fields = [
			"url",
			"order_id",
			"user",
			"shipping_address",
			"billing_address",
			"shipping_total_price",
			"subtotal",
			"order_total",
		]

	def get_subtotal(self, obj):
		return obj.cart.subtotal

class OrderSerializer(serializers.ModelSerializer):
	subtotal = serializers.SerializerMethodField()
	class Meta:
		model = Order
		fields = [
			"id",
			"user",
			"shipping_address",
			"billing_address",
			"shipping_total_price",
			"subtotal",
			"order_total",
		]

	def get_subtotal(self, obj):
		return obj.cart.subtotal

# class UserAddressSerializer(serializers.ModelSerializer):
# 	class Meta:
# 		model = UserAddress
# 		fields = [
# 			"id",
# 			"user",
# 			"type",
# 			"street",
# 			"state",
# 			"city",
# 			"zipcode",
# 			"phone"
# 		]

	# def create(self,  validated_data):
	# 	user = self.context['request'].user
	# 	usercheckout = UserCheckout.objects.filter(user_id=user.id).first()

	# 	if usercheckout is None:

	# 		usercheckout = UserCheckout()
	# 		usercheckout.user_id = user.id
	# 		usercheckout.email = user.email
	# 		usercheckout.braintree_id = '0'
	# 		usercheckout.save()

	# 	useraddress = UserAddress.objects.filter(user_id=usercheckout.id).first()
	# 	if useraddress is None:
	# 		print('sadsd')
	# 		useraddress = UserAddress()

	# 	useraddress.user_id = usercheckout.id
	# 	useraddress.type = validated_data.get('type')
	# 	useraddress.street = validated_data.get('street')
	# 	useraddress.city =  validated_data.get('city')
	# 	useraddress.zipcode = validated_data.get('zipcode')
	# 	useraddress.state = validated_data.get('state')
	# 	useraddress.phone = validated_data.get('phone')
	# 	useraddress.save()
	# 	return useraddress

from . import service as OrderService

# /api/api/create_order/ #CartOrderApiView(CreateAPIView):
class CartOrderSerializer(serializers.ModelSerializer):
	order_total = serializers.DecimalField(required=False, max_digits=50, decimal_places=2,)
	class Meta:
		model = Order
		fields = '__all__'

	def create(self, validated_data):
		#pprint.pprint(self.context['request'].__dict__)
		#pprint.pprint(validated_data)
		user =  self.context['request'].user
		print( type(validated_data))
		#pprint.pprint(validated_data)
		validated_data['user_id'] = user.id

		order = OrderService.CreateOrderFromCart(validated_data)
		return order

	# # def saveStoreWiseOrder(self, order, user):
	# # 	print('order::')
	# # 	print(order)
	# # 	cart = order.cart
	# # 	cart_items = cart.items
	# # 	cart_items = CartItem.objects.filter(cart_id=cart.id)
	# # 	ordered_by = Store.objects.filter(fk_user_id=user.id).first()
	# 	#ordered_by_store = ordered_by.id
	# 	#print(ordered_by_store)

	# 	# print('asdasdasdasd')
	# 	for variation in cart_items:
	# 		print(variation)
	# 		store = variation.item.product.fk_store
	# 		order_id = order.order_id
	# 		store_id = store.id
	# 		store_wise = StoreWiseOrder.objects.filter(order_id=order_id).filter(fk_ordered_store_id=store_id).first()
	# 		pprint.pprint(['storewise=', store_wise])
	# 		if store_wise is None:
	# 			store_wise = StoreWiseOrder()
	# 		store_wise.order_id = order.order_id
	# 		store_wise.order_total = order.order_total
	# 		store_wise.billing_address = order.billing_address
	# 		store_wise.shipping_address = order.shipping_address
	# 		store_wise.user_id = order.user_id
	# 		store_wise.cart_id = order.cart_id
	# 		store_wise.fk_auth_user_id = order.fk_auth_user_id
	# 		store_wise.order_latitude = order.order_latitude
	# 		store_wise.order_longitude = order.order_longitude
	# 		store_wise.fk_ordered_store = store
	# 		store_wise.fk_ordered_by_store = ordered_by
	# 		store_wise.fk_payment_method = order.fk_payment_method
	# 		store_wise.save()
	# 		variation.fk_storewise_order_id = store_wise.id
	# 		variation.save()
	# 	store_wise_orders = StoreWiseOrder.objects.filter(order_id=order_id)
	# 	for store_wise_order in store_wise_orders:
	# 		sw_cart_items =  CartItem.objects.filter(fk_storewise_order_id=store_wise_order.id) #store_wise_order.fk_storewise_order_id
	# 		store_wise_order.order_total = 0
	# 		# is_depo = Store.objects.filter(fk_user_id=user.id).filter(fk_store_type_id=2).first()
	# 		# if not is_depo:
	# 		if store_wise_order.order_latitude and store_wise_order.order_longitude:
	# 			store_wise_order.fk_route = get_nearest_route(
	# 				store_wise_order.order_latitude,
	# 				store_wise_order.order_longitude,
	# 				store_wise_order.fk_ordered_store.id,
	# 				None
	# 			)
	# 		for cart_item in sw_cart_items:
	# 			store_wise_order.order_total+=cart_item.line_item_total

	# 		store_wise_order.save()

			# print(variation.product)

class OrderListStoreSerializer(serializers.ModelSerializer):
	billing_address = serializers.SerializerMethodField()
	mobile = serializers.SerializerMethodField()
	payment_method = serializers.SerializerMethodField()
	class Meta:
		model = Order
		fields = ['id', 'status', 'is_delivered', 'is_paid',
		'order_longitude', 'order_latitude', 'cart', 'user', 'order_total',
		'billing_address', 'fk_ordered_store', 'fk_delivery_user',
		 'fk_payment_method', 'mobile', "payment_method"]

	def get_billing_address(self, obj):
		return str(obj.billing_address.street)

	def get_mobile(self, obj):
		return obj.user.user.mobile

	def get_payment_method(self, obj):
		title=""
		if obj.fk_payment_method:
			title = obj.fk_payment_method.title
		return title

from users.serializers import UserSerializer

class StoreWiseOrderListSerializer(serializers.ModelSerializer):
	# billing_address = serializers.SerializerMethodField()
	ordered_stored_name = serializers.SerializerMethodField()
	total_order_price = serializers.SerializerMethodField()
	customer_name = serializers.SerializerMethodField()
	address = serializers.SerializerMethodField()
	status = serializers.SerializerMethodField()
	created_at = serializers.SerializerMethodField()
	#ordered_time = serializers.SerializerMethodField()
	# fk_auth_user = UserSerializer()

	class Meta:
		model = StoreWiseOrder
		fields = [

			"id",
            "shipping_total_price",
            "order_total",
            "order_id",
            "is_delivered",
            "is_paid",
            "is_transit",
            "is_cancelled",
            "created_at",
           # "ordered_time",
            "updated_at",
            "order_latitude",
            "order_longitude",
            "cart",
            "fk_auth_user",
            "fk_ordered_store",
            "fk_delivery_user",
            "fk_payment_method",
            "fk_ordered_by_store_id",
            "ordered_stored_name",
            "total_order_price",
            "customer_name",
            "address",
            "status"

		]
	def get_created_at(self, obj):
		order_time = ((obj.created_at + timedelta(hours=5, minutes=45))).strftime("%Y-%m-%d, %I:%M %p")
		return order_time

	# def get_ordered_time(self, obj):
	# 	print(obj.created_at)
	# 	order_time = ((obj.created_at + timedelta(hours=5, minutes=45))).strftime("%Y-%m-%d, %I:%M %p")
	# 	return order_time

	def get_status(self, obj):
		status = "pending"
		if obj.is_delivered:
			status = "delivered"
		elif obj.is_transit:
			status = "transit"
		elif obj.is_cancelled:
			status = "cancelled"

		return status

	def get_ordered_stored_name(self, obj):
		abc = ""
		abc = Store.objects.filter(pk=obj.fk_ordered_by_store_id).first()

		if abc:
			return abc.title

		return abc
	def get_address(self, obj):
		cutomer_address = ""
		customer_address = UserAddress.objects.filter(user_id=obj.fk_auth_user_id).first()
		if customer_address:
			return str(customer_address.city + customer_address.street)
		return cutomer_address

	def get_customer_name(self, obj):
		customer_name = ""
		customer = User.objects.filter(pk=obj.fk_auth_user_id).first()
		if customer:
			return str(customer.firstname + ' '+ customer.lastname + ' '+ customer.mobile)
		return customer_name

	def get_total_order_price(self, obj):
		total_price = ""
		total_price = Order.objects.filter(order_id=obj.order_id).first()
		if total_price:
			total_price = total_price.order_total
		return total_price
		# def get_ordered_by(self, obj):
		# 	print(obj)
		# 	ordered_by = ""
		# 	if obj.fk_ordered_by_store_id:
		# 		ordered_by = Store.objects.filter(pk=obj.fk_ordered_by_store_id)
		# 	return ordered_by
	# def get_billing_address(self, obj):
	# 	return str(obj.billing_address.street)

	# def get_mobile(self, obj):
	# 	return obj.user.user.mobile

class UpdateOrderStatusSerializer(serializers.ModelSerializer):
	class Meta:
		model = Order
		fields = '__all__'

class UpdateStoreWiseOrderStatusSerializer(serializers.ModelSerializer):
	class Meta:
		model = StoreWiseOrder
		fields = '__all__'

class CartOrderListStoreSerializer(serializers.ModelSerializer):
	# cart_orders = serializers.SerializerMethodField()
	class Meta:
		model = CartItem
		fields = '__all__'

class CartItemSerializer(serializers.ModelSerializer):
	#item = CartVariationSerializer(read_only=True)
	# url = serializers.HyperlinkedIdentityField(view_name='products_detail_api')
	item = serializers.SerializerMethodField()
	product_id = serializers.SerializerMethodField()
	item_title = serializers.SerializerMethodField()
	product = serializers.SerializerMethodField()
	price = serializers.SerializerMethodField()
	image = serializers.SerializerMethodField()
	class Meta:
		model = CartItem
		fields = [
			# "url",
			"product_id",
			"image",
			"item",
			"item_title",
			"price",
			"product",
			"quantity",
			"line_item_total",
		]

	def get_item(self,obj):
		return obj.item.id

	def get_product_id(self, obj):
		return obj.id

	def get_item_title(self, obj):
		return "%s %s" %(obj.item.product.title, obj.item.title)

	def get_product(self, obj):
		return obj.item.product.id

	def get_price(self, obj):
		print(obj.item.sale_price)
		print(obj.item.price)
		print(obj.item.id)
		# print(obj.item.sale_price)
		if obj.item.sale_price is None:
			return obj.item.price
		return obj.item.sale_price

	def get_image(self, obj):
		# image_url = ProductImage.objects.filter(product_id=obj.item.id).first()
		variation = obj.item
		product = variation.product

		image_url = ProductImage.objects.filter(product=product).first()
		# print(obj.item.id)
		# print(obj.__dict__)
		# print(image_url)
		# return ""
		# print(list(image_url.values('image')))

		imageUrl = "/static/no-image.jpg"
		if image_url:
			d = image_url.__dict__
			if 'image' in d:
				imageUrl = d['image']

		# return image_url.image

		return imageUrl

		# cart_items = CartItem.objects.filter(cart_id=cart.id)

class PurchaseItemSerializer(serializers.ModelSerializer):
	fk_variation = VariationSerializer()
	class Meta:
		model = PurchaseItem
		fields = '__all__'


from django.urls import path, include
from myacc import views

urlpatterns = [
    path('', views.index),
    path('insert/', views.insert),
    path('view/', views.view),
    path('update/', views.update),
    path('delete/', views.delete),
#    path('<str:acc_type>/', views.index),
]


import os, sys
Import('env')
Import('debug')
Import('sdl_cflags')
Import('sdl_libs')
Import('lib_dir')

env = env.Clone()
env.Append(CPPPATH=['..', '.'])
env.Append(LIBPATH=['../mrt'])
env.Append(CPPDEFINES=['SDLXAPI=DLLEXPORT'])

env.MergeFlags(sdl_cflags, sdl_libs)

libs = ['mrt', 'SDL', 'SDL_image']

if sys.platform != "win32":
	c_map_env= env.Clone()
	#c_map_env.Append(CXXFLAGS=['-fforce-addr', '-fprefetch-loop-arrays'])
	c_map = c_map_env.SharedObject('c_map.cpp')
	#libs.append('GL')
	libs.append('rt')
	libs.append('X11')

	env.Append(LINKFLAGS=['-Wl,-rpath,'+ lib_dir])
	env.Append(LINKFLAGS=['-Wl,-rpath-link,build/' + env['mode'] + '/mrt'])
else:
	c_map = env.SharedObject('c_map.cpp')
	libs.append('opengl32')
	libs.append('winmm')
	libs.append('user32')
	libs.append('gdi32')
	libs.append('advapi32')

sdlx_sources = 	['cursor.cpp', 'sdl_ex.cpp', 'surface.cpp', 'system.cpp', 'joystick.cpp',
	'thread.cpp', 'mutex.cpp', 'semaphore.cpp', 'color.cpp',
	c_map, 'font.cpp', 'timer.cpp', 'module.cpp', 'file_rw.cpp',
	'gfx/SDL_rotozoom.c',
	] #  'ttf.cpp',

if sys.platform == 'win32':
	sdlx_sources.append('wrappers/d3dsdl8.cpp')
	env.Append(CPPPATH=[os.environ['DXSDK_DIR'] + '\\Include'])
	env.Append(LIBPATH=[os.environ['DXSDK_DIR'] + '\\Lib'])
	#libs.append('d3dx8')
	#libs.append('d3dx9')
	libs.append('d3d8')
	libs.append('d3dx8')
else:
	sdlx_sources.append('wrappers/glSDL.c')

sdlx = env.SharedLibrary('sdlx', sdlx_sources, LIBS=libs)
Import('debug')

if sys.platform == "win32":
	sdlx_main = env.StaticLibrary('sdlx_main', ['SDL_win32_main.c'])

if sys.platform != 'win32' and len(env['prefix']) > 0:
	Import('install_targets')
	Import('lib_dir')
	install_targets.append(Install(lib_dir, sdlx))
else:
	Install('#', sdlx[0])


#!/usr/bin/env python
# coding: utf-8

# CONVERT DFA TO REGEX

import json
import sys

with open(sys.argv[1], 'r') as f:
    DFA = json.load(f)

def join(string1, string2):
    if string1 == '$':
        return string2
    if string2 == '$':
        return string1
    return string1 + string2

# remove dead states

def resolve_dead(delta):
    check = {}
    for state in DFA['states']:
        check.update({state: False})
    for state in DFA['start_states']:
        check[state] = True
    for edge in delta:
        check[edge[2]] = True
    return [edge for edge in delta if check[edge[0]]], [state for state in check if check[state]]

# simplifty parallel edges

def resolve_parallel(delta):
    hist = []
    n = len(delta)
    for i in range(n):
        for j in range(i+1, n):
            if delta[i][0] == delta[j][0] and delta[i][2] == delta[j][2]:
                new_edge = [
                    delta[i][0], '(' + delta[i][1] + '+' + delta[j][1] + ')', delta[i][2]]
                delta.remove(delta[j])
                delta.append(new_edge)
                hist.append(delta[i])
                i += 1
    for old_edge in hist:
        if old_edge in delta:
            delta.remove(old_edge)
    return delta

# removing self-loops

def resolve_selfloops(delta):
    loops = []
    for edge in delta[:]:
        if edge[0] == edge[2]:
            loops.append(edge)
            delta.remove(edge)
    for loop in loops:
        for i, edge in enumerate(delta):
            if loop[0] == edge[0]:
                delta[i][1] = join('(' + loop[1] + ')*', edge[1])
    return delta

def remove_state(state, delta):
    incoming = [edge for edge in delta if edge[2] == state]
    outgoing = [edge for edge in delta if edge[0] == state]
    for edge in (incoming + outgoing):
        delta.remove(edge)
    for inedge in incoming:
        for outedge in outgoing:
            edge = [inedge[0], join(inedge[1], outedge[1]), outedge[2]]
            delta.append(edge)
    delta = resolve_parallel(delta)
    delta = resolve_selfloops(delta)
    return delta

if __name__ == '__main__':
    delta = DFA['transition_function'].copy()

    # STEP ZERO: remove dead states

    delta, valid_states = resolve_dead(delta)

    # STEP ONE: NEW INITIAL AND FINAL STATES

    start = 'Qs'
    final = 'Qf'

    for s in DFA['start_states']:
        delta.append([start, '$', s])
    for f in DFA['final_states']:
        delta.append([f, '$', final])

    # STEP TWO: simplify parallel edges

    delta = resolve_parallel(delta)

    # STEP THREE: removing self-loops

    delta = resolve_selfloops(delta)

    for state in valid_states:
        delta = remove_state(state, delta)

    regex = {'regex': delta[0][1]}
    output = json.dumps(regex, indent=4)
    with open(sys.argv[2], 'w') as f:
        f.write(output)


'''if (any boolean value):
    print (' TRue')
else:
    print('False')'''

a=4
b=3
c=5

if a<b:
    print('a is less than b')
else:
    print('b is greater than a')

if c<5:
    print('c is less than 5')


import math

# W dwuwymiarowym wszechświecie trwa wojna pomiędzy planetami przy użyciu broni laserowej.
# Broń laserowa wysyła wiązkę w linii prostej i niszczy wszystkie planety na swojej drodze
# oraz w promieniu R od linii wiązki. Zasięg wiązki laserowej jest nieograniczony i nie jest
# ona zatrzymywana przez żadne planety będące na jej drodze. Napisz program, który na podstawie:
# nazw dwóch planet (np. A i B) i promienia R zwróci nazwy planet, które zostaną zniszczone w przypadku
# gdy planeta A wyśle wiązkę laserową w kierunku planety B, a planeta B wyśle wiązkę laserową w kierunku planety A.

laser_planets = {
    "ziemia": (2, 4),
    "mars": (3, 6)
    }

planets = {
    "wenus": (9, 0),
    "jowisz": (5, 6),
    "merkury": (2, 5),
    "saturn": (4, 8),
    "neptun": (0, 5),
    "uran": (0, 6),
    "xyz": (0, 4)
}

def reduction(name1, name2, radius):
    "prosta"
    line_between = line(laser_planets[name1], laser_planets[name2])
    "lista zniszczonych planet"
    destroyed_planets = [name1, name2]
    for planet, coordinates in planets.items():
        distance = planet_distance(coordinates, line_between)
        if destroyed(distance, radius):
            "dodanie zniszczonej planety"
            destroyed_planets.append(planet)
    return destroyed_planets

def line(coordinates1, coordinates2):
    "zwraca krotki prostej ax+by+c=0 (a, b, c)"
    if coordinates1[0] == coordinates2[0]:
        return (1, 0, -coordinates2[0])
    else:
        x1, y1 = coordinates1
        x2, y2 = coordinates2
        a = (y1-y2)/(x1-x2)
        c = y1 - x1*a
        return (a, -1, c)

def planet_distance(coordinates, line):
    "zwraca odległość planety od prostej"
    x, y = coordinates
    a, b, c = line
    denominator = a*x+b*y+c
    if denominator < 0:
        denominator = -denominator
    numerator = math.sqrt(a**2+b**2)
    return denominator/numerator

def destroyed(distance, radius):
    "zwraca czy planeta została zniszczona"
    return distance <= radius

if __name__ == "__main__":
    print(reduction("ziemia", "mars", 2))


import os
import pandas as pd
import datetime
from Functions import combine_tcrex

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Combine into one file TCRex predictions for every individual in split dataset
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
folder = './data/splitDS_IMSEQ'
# specify path to where TCRex output files are stored
directory = f'{folder}/TCRex_results'
# where to save processed TCRex output files
if not os.path.exists(f'{folder}/TCRex_processed'):
    os.makedirs(f'{folder}/TCRex_processed')
    print(f'Processed TCRex files will be saved in {folder}/TCRex_processed')
directory_new = f'{folder}/TCRex_processed'

# from CovidTCRS in PhD_2020
# list of all IDs of patients (folder names in the TCRex_results folder)
id_list = [one_id for one_id in os.listdir(directory)
           if os.path.isdir(os.path.join(directory, one_id))]

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# add seq counts and frequencies to tcrex output files
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for sample in id_list:
    # tcrex output (predictions) file
    print(str(datetime.datetime.now()) +
          f':\nStarted combining TCRex predictions with '
          f'sequencing counts data for {sample}')
    file_tcrex = f'{directory}/{sample}/filtered_results.csv'
    tcrex = pd.read_csv(file_tcrex, sep='\t', header=6)
    tcrex['sample_id'] = sample

    # sequencing files with counts
    file_seq = f'{folder}/TCRex_format_meta_TRB/{sample}.txt'
    seq = pd.read_csv(file_seq, sep='\t', index_col=0)
    seq.drop(columns=['d', 'VEnd', 'DStart', 'DEnd', 'JStart'], inplace=True)
    # Total number of sequenced TCRs
    seq['total_count'] = seq['count'].sum()
    # Total number of different TCRs (V-CDR3-J)
    seq['unique_TCRs'] = len(
        seq[['TRBV_gene', 'CDR3_beta', 'TRBJ_gene']].drop_duplicates()[
            'CDR3_beta'])
    # Total number of different CDR3s
    seq['unique_CDR3s'] = len(seq['CDR3_beta'].unique())

    # change V-J gene notation to IMGT (TCRex also has the same, IMGT)
    # remove white spaces V-J genes
    seq['TRBV_gene'] = seq['TRBV_gene'].apply(str).str.replace(' ', '')
    seq['TRBJ_gene'] = seq['TRBJ_gene'].apply(str).str.replace(' ', '')

    # Convert V-J genes to IMGT format
    # seq['TRBV_gene'] = seq['TRBV_gene'].str.replace('\*00.+$', '', regex=True)
    # change TRBV/J1- into TRBV/J01-
    seq.loc[seq['TRBV_gene'].str.contains(pat='TRBV[1-9]-',
                                          regex=True), 'TRBV_gene'] = \
        seq.loc[seq['TRBV_gene'].str.contains(pat='TRBV[1-9]-',
                                              regex=True), 'TRBV_gene'].str.replace(
            'TRBV', 'TRBV0',
            regex=False)
    seq.loc[seq['TRBJ_gene'].str.contains(pat='TRBJ[1-9]-',
                                          regex=True), 'TRBJ_gene'] = \
        seq.loc[seq['TRBJ_gene'].str.contains(pat='TRBJ[1-9]-',
                                              regex=True), 'TRBJ_gene'].str.replace(
            'TRBJ', 'TRBJ0',
            regex=False)
    # change TRBV/J1 into TRBV/J01 (no - )
    seq.loc[seq['TRBV_gene'].str.contains(pat='TRBV[1-9]$',
                                          regex=True), 'TRBV_gene'] = \
        seq.loc[seq['TRBV_gene'].str.contains(pat='TRBV[1-9]$',
                                              regex=True), 'TRBV_gene'].str.replace(
            'TRBV', 'TRBV0',
            regex=False)
    seq.loc[seq['TRBJ_gene'].str.contains(pat='TRBJ[1-9]$',
                                          regex=True), 'TRBJ_gene'] = \
        seq.loc[seq['TRBJ_gene'].str.contains(pat='TRBJ[1-9]$',
                                              regex=True), 'TRBJ_gene'].str.replace(
            'TRBJ', 'TRBJ0',
            regex=False)
    # change -1 into -01
    seq.loc[seq['TRBV_gene'].str.contains(pat='-[1-9]$',
                                          regex=True), 'TRBV_gene'] = \
        seq.loc[seq['TRBV_gene'].str.contains(pat='-[1-9]$',
                                              regex=True), 'TRBV_gene'].str.replace(
            '-', '-0',
            regex=False)
    seq.loc[seq['TRBJ_gene'].str.contains(pat='-[1-9]$',
                                          regex=True), 'TRBJ_gene'] = \
        seq.loc[seq['TRBJ_gene'].str.contains(pat='-[1-9]$',
                                              regex=True), 'TRBJ_gene'].str.replace(
            '-', '-0',
            regex=False)

    # combine tcrex and sequencing files
    tcrex_seq = pd.merge(tcrex, seq, how="left",
                         on=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene'])
    tcrex_seq.drop_duplicates(inplace=True)

    # number of different nt sequences per CDR3 with the same V-J genes, epitope, etc.
    nt_seq = tcrex_seq.groupby(
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr'],
        as_index=False, sort=False)['count'].count().rename(
        columns={'count': 'N_nt_seq'})
    # combined counts for CDR3 with the same V-J genes, epitope, etc. but different nt sequences
    new_count = tcrex_seq.groupby(
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr'],
        as_index=False, sort=False)['count'].sum()
    # combined frequencies for CDR3 with the same V-J genes, epitope, etc. but different nt sequences
    new_freq = tcrex_seq.groupby(
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr'],
        as_index=False, sort=False)['freq'].sum()

    # step-by-step merging to update count and freq columns and substitude cdr3nt with N_nt_seq
    interim = pd.merge(nt_seq, new_count, how='inner',
                       on=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope',
                           'pathology',
                           'score', 'bpr'])
    interim = pd.merge(interim, new_freq, how='inner',
                       on=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope',
                           'pathology',
                           'score', 'bpr'])
    tcrex_seq = pd.merge(tcrex_seq[
                             ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope',
                              'pathology', 'score', 'bpr',
                              'sample_id', 'total_count', 'unique_TCRs',
                              'unique_CDR3s']], interim, how='inner',
                         on=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope',
                             'pathology', 'score', 'bpr'])

    tcrex_seq.drop_duplicates(inplace=True)
    tcrex_seq.sort_values(by=['bpr', 'pathology', 'epitope', 'CDR3_beta'],
                          inplace=True)
    tcrex_seq.to_csv(f'{directory}/{sample}/results_with_seq_counts.csv',
                     index=False)
    print(f"{sample} files have been processed!")

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# combine individual sample files into one; add metadata; keep only viral TCRs
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# metadata file
meta = pd.read_csv(folder + '/metadata_TRB_10umi_filter_MiXCR_to_VDJtools.txt',
                   sep='\t')
meta = meta[
    ['sample_id', 'patient_id', 'T-cell_type', 'Repeat', 's_id', 'Gene',
     'study_patient_id', 'disease_severity', 'time']]

tcrex_data = combine_tcrex(folder, id_list, 'results_with_seq_counts.csv')
# All predicted epitopes: ['SARS-CoV-2', 'HIV', 'EBV', 'CMV', 'HCV', 'DENV1', 'Melanoma', 'Influenza',
# 'DENV2', 'DENV3/4', 'HTLV1', 'HSV2', 'Multiple Myeloma', 'YellowFeverVirus']

tcrex_viral = tcrex_data.loc[~((tcrex_data.pathology == 'Melanoma') | (
            tcrex_data.pathology == 'Multiple Myeloma'))]
tcrex_viral = tcrex_viral.sort_values(
    by=['sample_id', 'bpr', 'pathology', 'epitope', 'CDR3_beta'])

# add metadata
tcrex_viral_meta = pd.merge(tcrex_viral, meta, on='sample_id')
tcrex_viral_meta = tcrex_viral_meta.sort_values(
    by=['study_patient_id', 'patient_id', 's_id', 'Repeat',
        'bpr', 'pathology', 'epitope', 'CDR3_beta'])

# convert time from d10 (str) to day: 10 (int)
tcrex_viral_meta['time'] = tcrex_viral_meta['time'].str.replace(pat='d',
                                                                repl='',
                                                                regex=False).map(
    lambda x: int(x))
tcrex_viral_meta.rename(columns={'time': 'day'}, inplace=True)

# creating week column
tcrex_viral_meta.loc[tcrex_viral_meta['day'] <= 7, 'week'] = 1
tcrex_viral_meta.loc[(tcrex_viral_meta['day'] > 7) & (
            tcrex_viral_meta['day'] <= 14), 'week'] = 2
tcrex_viral_meta.loc[(tcrex_viral_meta['day'] > 14) & (
            tcrex_viral_meta['day'] <= 21), 'week'] = 3
tcrex_viral_meta.loc[(tcrex_viral_meta['day'] > 21) & (
            tcrex_viral_meta['day'] <= 28), 'week'] = 4
tcrex_viral_meta['week'] = tcrex_viral_meta['week'].map(lambda x: int(x))

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# MERGING (combined or intersected) REPEATS TOGETHER; PATIENTS (TP and cell type) are still SEPARATE
# ? update frequencies to the median ones when merging (adj.Freq and adj.Total_counts as an alternative)
# ? add CDR3 diversity column
# ? add N_unique V, J genes
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# new patient id will contain patient_id and cell type only (united/intersected repeats -> no s_id)
new_pat_id = []
for patient in tcrex_viral_meta['patient_id'].unique().tolist():
    for cell in ['cd4', 'cd8']:
        new_pat_id.append(f'{str(patient)}_{cell}')

# combine 3 sequencing repeats into one TCRex output file per patient
# TP and cell type are still separate samples
all_combined = pd.DataFrame()
all_intersect2 = pd.DataFrame()  # occurs at least twice, in two repeats
for new_patient in new_pat_id:
    # to drop columns 'sample_id', 'Repeat', 's_id', 'Gene'
    df1 = tcrex_viral_meta.loc[
        tcrex_viral_meta['sample_id'].str.startswith(pat=(new_patient + '_1')),
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr',
         'total_count', 'unique_TCRs', 'unique_CDR3s', 'N_nt_seq', 'count',
         'freq',
         'patient_id', 'T-cell_type', 'study_patient_id', 'disease_severity',
         'day', 'week']]
    df2 = tcrex_viral_meta.loc[
        tcrex_viral_meta['sample_id'].str.startswith(pat=(new_patient + '_2')),
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr',
         'total_count', 'unique_TCRs', 'unique_CDR3s', 'N_nt_seq', 'count',
         'freq',
         'patient_id', 'T-cell_type', 'study_patient_id', 'disease_severity',
         'day', 'week']]
    df3 = tcrex_viral_meta.loc[
        tcrex_viral_meta['sample_id'].str.startswith(pat=(new_patient + '_3')),
        ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene', 'epitope', 'pathology',
         'score', 'bpr',
         'total_count', 'unique_TCRs', 'unique_CDR3s', 'N_nt_seq', 'count',
         'freq',
         'patient_id', 'T-cell_type', 'study_patient_id', 'disease_severity',
         'day', 'week']]
    # merge all entries of all three repeats (filter later)
    df_combined = pd.concat([df1, df2, df3], ignore_index=True, sort=False)
    df_combined['new_id'] = new_patient

    # keep CDR3s that occur at least in 2 repeats out of 3
    # (many same CDR3s have different predicted specificity and V/J genes)
    # all repeated CDR3s
    # confusing keep parameter, but every repeat gets assigned True
    df_intersect2 = df_combined[
        df_combined.duplicated(subset=['CDR3_beta'], keep=False)].copy()
    df_intersect2.sort_values('CDR3_beta', inplace=True)
    try:
        # V-J-CDR3 that occur at least in two repeats
        df_intersect2 = pd.concat(g for _, g in df_intersect2.groupby(
            ['TRBV_gene', 'CDR3_beta', 'TRBJ_gene'])
                                  if len(g['total_count'].unique()) > 1)
        df_intersect2.sort_values(
            by=['total_count', 'bpr', 'pathology', 'CDR3_beta'],
            inplace=True)  # ascending
        # keep only the last one, with the highest counts (gets assigned False)
        df_intersect2 = df_intersect2[~df_intersect2.duplicated(
            subset=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene',
                    'epitope'], keep='last')]
        df_intersect2.sort_values(by=['bpr', 'pathology', 'CDR3_beta'],
                                  inplace=True)
    except ValueError as err:
        print(
            f"{err}: {new_patient} does not have sequences with the same V-J-CDR3 occurring in at least two repeats. "
            f"Looking for the same CDR3 sequences only (disregarding V-J genes.)")
        try:
            # CDR3 that occur at least in two repeats
            df_intersect2 = pd.concat(g for _, g in df_intersect2.groupby(
               'CDR3_beta') if len(g['total_count'].unique()) > 1)
            df_intersect2.sort_values(
                by=['total_count', 'bpr', 'pathology', 'CDR3_beta'],
                inplace=True)  # ascending
            # keep only the last one, with the highest counts (gets assigned False)
            df_intersect2 = df_intersect2[~df_intersect2.duplicated(
                subset=['TRBV_gene', 'CDR3_beta', 'TRBJ_gene',
                        'epitope'], keep='last')]
            df_intersect2.sort_values(by=['bpr', 'pathology', 'CDR3_beta'],
                                      inplace=True)
        except ValueError as err2:
            print(
                f"{err2}: {new_patient} does not have sequences with the same V-CDR3-J or just CDR3 occurring "
                f"in at least two repeats. Skipping to the next file.")
        else:
            print(
                f"File with the same CDR3 only occurring in at least two repeats has been created successfully "
                f"for {new_patient}.")
    else:
        print(
            f"File with the same V-CDR3-J occurring in at least two repeats has been created successfully "
            f"for {new_patient}.")
    # assemble all patients together
    all_intersect2 = all_intersect2.append(df_intersect2, ignore_index=True,
                                           sort=False)
all_intersect2.to_csv(f'{directory_new}/viralTCRexPreds_withCounts_splitDS_intersected2x_meta.tsv',
                      sep='\t', index=False)
# all_intersected_double_viral_meta


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrdervectical(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []

        level=[(root,0)]
        res={}
        mincol,maxcol=1<<31,-1<<31
        while level:
            for node,col in level:
                mincol=min(mincol,col)
                maxcol=max(maxcol,col)
                res[col]=res.get(col,[])+[node.val]
            tmp=[]
            for node,col in level:
                if node.left:
                    tmp.append((node.left,col-1))
                if node.right:
                    tmp.append((node.right,col+1))
            level=tmp
        reslist=[]
        for i in xrange(mincol,maxcol+1):
            reslist.append(res[i])
        return reslist

    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []

        level=[root]
        res=[]
        while level:
            res.append([node.val for node in level])
            tmp=[]
            for node in level:
                if node.left:
                    tmp.append(node.left)
                if node.right:
                    tmp.append(node.right)
            level=tmp

        return res


from new_kNN import *
import pandas as pd
import numpy as np

def accuracy(predictions, outcomes):
    return 100*np.mean(predictions==outcomes)

data =pd.read_csv("wine.csv")

#print(data.head(5))
numeric_data = data.drop("color",axis=1)

import sklearn.preprocessing as sp
scaled_data = sp.scale(numeric_data)
numeric_data =pd.DataFrame(scaled_data,columns=numeric_data.columns)

import sklearn.decomposition as sd
pca = sd.PCA(n_components=2)
#principal_components = pca.fit_transform(numeric_data)
principal_components=pca.fit(numeric_data).transform(numeric_data)

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
observation_colormap = ListedColormap(['red', 'blue'])
x = principal_components[:,0]
y = principal_components[:,1]

plt.title("Principal Components of Wine")
plt.scatter(x, y, alpha = 0.2,
    c = data['high_quality'], cmap = observation_colormap, edgecolors = 'none')
plt.xlim(-8, 8); plt.ylim(-8, 8)
plt.xlabel("Component 1"); plt.ylabel("Component 2")
plt.show()

predictors = np.array(numeric_data)
outcomes = np.array(data["high_quality"])

my_predictions = np.array([knn_predict(p,predictors,outcomes,k=5) for p in predictors])
percentage = accuracy(my_predictions,data.high_quality)
print(percentage)

"""
from sklearn.neighbors import KNeighborsClassifier
knn=KNeighborsClassifier(n_neighbors=3001)
knn.fit(predictors,outcomes)
scikit_prediction=knn.predict(predictors)
percentage = accuracy(scikit_prediction,data.high_quality)
print(percentage)
"""


import torch
import torch.nn as nn
from mmcv.cnn import ConvModule

from mmseg.models.decode_heads.decode_head import BaseDecodeHead
from mmseg.registry import MODELS

class UpBlock(nn.Module):
    """Upsample Block with two consecutive convolution layers."""

    def __init__(self, in_channels, out_channels, guidance_channels):
        super().__init__()
        self.up = nn.ConvTranspose2d(
            in_channels,
            in_channels - guidance_channels,
            kernel_size=2,
            stride=2)
        self.conv1 = ConvModule(
            in_channels,
            out_channels,
            3,
            padding=1,
            bias=False,
            norm_cfg=dict(type='GN', num_groups=out_channels // 16))
        self.conv2 = ConvModule(
            out_channels,
            out_channels,
            3,
            padding=1,
            bias=False,
            norm_cfg=dict(type='GN', num_groups=out_channels // 16))

    def forward(self, x, guidance=None):
        """Forward function with visual guidance."""
        x = self.up(x)
        if guidance is not None:
            T = x.size(0) // guidance.size(0)
            # guidance = repeat(guidance, "B C H W -> (B T) C H W", T=T)
            guidance = guidance.repeat(T, 1, 1, 1)
            x = torch.cat([x, guidance], dim=1)
        x = self.conv1(x)

        return self.conv2(x)

@MODELS.register_module()
class CATSegHead(BaseDecodeHead):
    """CATSeg Head.

    This segmentation head is the mmseg implementation of
    `CAT-Seg <https://arxiv.org/abs/2303.11797>`_.

    Args:
        embed_dims (int): The number of input dimensions.
        decoder_dims (list): The number of decoder dimensions.
        decoder_guidance_proj_dims (list): The number of appearance
            guidance dimensions.
        init_cfg
    """

    def __init__(self,
                 embed_dims=128,
                 decoder_dims=(64, 32),
                 decoder_guidance_dims=(256, 128),
                 decoder_guidance_proj_dims=(32, 16),
                 **kwargs):
        super().__init__(**kwargs)
        self.decoder_guidance_projection = nn.ModuleList([
            nn.Sequential(
                nn.Conv2d(
                    dec_dims,
                    dec_dims_proj,
                    kernel_size=3,
                    stride=1,
                    padding=1),
                nn.ReLU(),
            ) for dec_dims, dec_dims_proj in zip(decoder_guidance_dims,
                                                 decoder_guidance_proj_dims)
        ]) if decoder_guidance_dims[0] > 0 else None

        self.decoder1 = UpBlock(embed_dims, decoder_dims[0],
                                decoder_guidance_proj_dims[0])
        self.decoder2 = UpBlock(decoder_dims[0], decoder_dims[1],
                                decoder_guidance_proj_dims[1])
        self.conv_seg = nn.Conv2d(
            decoder_dims[1], 1, kernel_size=3, stride=1, padding=1)

    def forward(self, inputs):
        """Forward function.

        Args:
            inputs (dict): Input features including the following features,
                corr_embed: aggregated correlation embeddings.
                appearance_feats: decoder appearance feature guidance.
        """
        # decoder guidance projection
        if self.decoder_guidance_projection is not None:
            projected_decoder_guidance = [
                proj(g) for proj, g in zip(self.decoder_guidance_projection,
                                           inputs['appearance_feats'])
            ]

        # decoder layers
        B = inputs['corr_embed'].size(0)
        corr_embed = inputs['corr_embed'].transpose(1, 2).flatten(0, 1)
        corr_embed = self.decoder1(corr_embed, projected_decoder_guidance[0])
        corr_embed = self.decoder2(corr_embed, projected_decoder_guidance[1])

        output = self.cls_seg(corr_embed)

        # rearrange the output to (B, T, H, W)
        H_ori, W_ori = output.shape[-2:]
        output = output.reshape(B, -1, H_ori, W_ori)
        return output


import time

import snow_event_base as seb
import snow_ticket as st

class ManualSnowEvent(seb.SnowEventBase):
    """
    Create ServiceNow Event manually by running the script and passing
    in the correct parameters
    """

    def __init__(self):
        super(ManualSnowEvent, self).__init__()

    def _get_events(self):
        create_parser = st.ArgumentParser()

        # create subcommand
        create_parser.add_argument("--node", dest="node", type=str,
                                   action="store", required=True,
                                   help="The physical device or virtual entity"
                                   " that is being monitored")
        create_parser.add_argument("--resource", dest="resource", type=str,
                                   action="store", required=True,
                                   help="The resource on the node that "
                                   "generates the event")
        create_parser.add_argument("--type", dest="type", type=str,
                                   action="store", required=True,
                                   help="Type of the event")
        create_parser.add_argument("--severity", dest="severity", type=str,
                                   action="store", required=True,
                                   help="Severity of the event")
        create_parser.add_argument("--source", dest="source", type=str,
                                   action="store", default="",
                                   help="Source of the event")
        create_parser.add_argument("--time_of_event", dest="time_of_event",
                                   type=str, action="store", default="",
                                   help='Time of the event in "YYYY-MM-DD '
                                   'hh:mm:ss" format')
        create_parser.add_argument("--ci_identifier", dest="ci_identifier",
                                   type=str, action="store", default="{}",
                                   help="Optional JSON string that represents "
                                   "a configuration item in the users network")
        create_parser.add_argument("--additional_info", dest="additional_info",
                                   type=str, action="store", default="",
                                   help="Additional information of the event")
        create_parser.add_argument("--description", dest="description",
                                   type=str, action="store", default="",
                                   help="Description of the event")
        opts = create_parser.parse_args()
        # self.subcommand = opts.subcommand

        if self.subcommand == "update":
            self.sys_id = opts.sys_id
            return ({
                "state": opts.state,
            })
        else:
            if not opts.time_of_event:
                time_of_event = time.strftime("%Y-%m-%d %H:%M:%S",
                                              time.gmtime())
            else:
                time_of_event = opts.time_of_event

            res = {
                "node": opts.node,
                "resource": opts.resource,
                "type": opts.type,
                "severity": opts.severity,
                "source": opts.source,
                "time_of_event": time_of_event,
                "ci_identifier": opts.ci_identifier,
                "additional_info": opts.additional_info,
                "description": opts.description
            }

            res["event_class"] = "Splunk"
            return (res,)

def main():
    handler = ManualSnowEvent()
    handler.handle()

if __name__ == "__main__":
    main()


import sys
import numpy as np
from simulated_annealing import *
import time

TEST_RUNS = 50

def test():
    avg_time = 0
    n = 15
    temperature = 10
    s, f = 0, 0
    for i in range(TEST_RUNS):
        state = create_random_state(n)
        start = time.time()
        goal = simulated_annealing(state, n, temperature)
        end = time.time()
        if not is_solution(goal, n):
            f += 1
            print(f"Run {i}: Failed to find solution", end=", ")
        else:
            s += 1
            print(f"Run {i}: Found solution", end=", ")
        print(f"Run {i}: Time: {end-start:.8f} seconds")
        avg_time += end-start
    print(f"Success rate: {s/TEST_RUNS*100:.2f}%")
    print(f"Average time: {avg_time/TEST_RUNS:.8f} seconds")

def main():
    test()

if __name__ == "__main__":
    main()


#!/usr/bin/python

'''
http://projecteuler.net/problem=14

The following iterative sequence is defined for the set of positive
integers:

    n -> n/2 (n is even)
    n -> 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following
sequence:

    13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz
Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one
million.
'''

def main():
    # Create a tuple that stores the length of the longest sequence
    # and the integer that generated it
    LongestSequence = (0, 0)

    # We only need to check the integers from 500,000 to 999,999
    # because every integer from 1 to 499,999 is part of a sequence
    # that is generated by that integer * 2
    for i in range(500000, 1000000):
        SequenceLength = 0
        j = i

        # Find the length of the sequence for the current integer
        while j != 1:
            SequenceLength += 1

            if j % 2 == 0:
                j = j // 2
            else:
                j = (j * 3) + 1

        if SequenceLength > LongestSequence[1]:
            LongestSequence = (i, SequenceLength)

    # Print the answer
    print(LongestSequence[0])

if __name__ == "__main__":
    main()


def get_word(text):
    result = []
    # print(",,,,," ,enumerate(text.split(' ')))
    for i, letter in enumerate(text.split(' ')):
        result.append(len(letter))

    return result

def han():
    d = {'x':1 ,'y':2  ,'z':3  }
    for key , value in d.items():
        print(key , value)

def wen():
    k = ['1' ,'2', '3', '4']
    for value  in  range(len(k)):
        print('value :'+k[value])

text = 'Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation.'
print(get_word(text))
han()
wen()


import sys
from os import listdir
from os.path import isfile, isdir
import os, subprocess

import pandas as pd
import numpy as np

#CARPETAS ARCHIVOS

CONST='CONSTITUCIONES_TXT/'
CONSTRAD='CONSTITUCIONES_TRAD/'
CONSTFASTA='CONSTITUCIONES_FASTA/'
CONSTNUBE='CONSTITUCIONES_NUBE/'

#crea diccionario desde CODIGOS.xls

BASE = pd.read_excel('CODIGOS.xls')
BASEnp= BASE.to_numpy()
filas,cols = BASEnp.shape

#crea diccionario
DICC = {' ':'AAA'}
for fila in range(filas):
	DICC[BASEnp[fila][0]] = BASEnp[fila][4]

def LISTADO(path):   #entrega lista de archivos .txt , no 'TRAD_PAIS.txt'
	return [obj for obj in listdir(path) if isfile(path + obj) and obj[-4:]=='.txt' and obj[:4] != 'TRAD']

def SIMPLIFICA(txt):
	txt=txt.lower()
	txt=txt.replace('á','a')
	txt=txt.replace('é','e')
	txt=txt.replace('í','i')
	txt=txt.replace('ó','o')
	txt=txt.replace('ú','u')
	txt=txt.replace(',',' ')
	txt=txt.replace('.',' ')
	txt=txt.replace(';',' ')

	return txt

def TRADUCE(txt):

	txt=SIMPLIFICA(txt)

	trad=''

	for i in txt:

		try:
			trad += DICC[i]
		except:
			trad += 'TTT'

	return trad

def TRADUCIR(listadi):  #convierte textos 'PAIS.txt' a ADN, 'TRAD_PAIS.txt'

	for archivo in listadi:
		print (f'CONVIRTIENDO = {CONST}{archivo}')

		txt = open(f'{CONST}{archivo}','r').read()
		nombre = archivo[:-4]

		trad = TRADUCE(txt)

		salida = open(f'{CONSTRAD}TRAD_{nombre}.txt','w')

		salida.write(trad)
		print (f'HECHO {nombre}')

def LISTADOTRAD(path):    #entrega lista de 'TRAD_PAIS.txt'
	return [obj for obj in listdir(path) if isfile(path + obj) and obj[-4:]=='.txt' and obj[:4] == 'TRAD']

def CREAR_SEQS(listatrad):
	textoSEQ=''

	for archiv in listatrad:
		nombre = archiv[:-4]
		txt = open(archiv,'r').read()
		textoSEQ += f'>{nombre} \n'
		textoSEQ += f'{txt} \n\n'

	salida=open('SEQSALIDA.txt','w')

	salida.write(textoSEQ)

def FRECUENCIA(palabra,text):

	#text = open(f'{archivo}','r').read()
	text=SIMPLIFICA(text)

	total_occurrences = text.count(palabra)

	return [palabra, total_occurrences]

def LISTAFRECUENCIA(archivo):
	text = open(f'{archivo}','r').read()
	text=SIMPLIFICA(text)

	textosplit = text.split()

	textoset = set(textosplit)

	LISTAFREC=[]
	for palabra in textoset:
		if len(palabra)>3:

			frec = FRECUENCIA(palabra, text)
			LISTAFREC.append(frec)

	LISTAFREC.sort(key=lambda x: x[1], reverse=True)
	return LISTAFREC

def COINCIDENCIAS(txt1, txt2):

	txt1=SIMPLIFICA(txt1)
	txt2=SIMPLIFICA(txt2)

	txt1SET= set(txt1.split())
	txt2SET= set(txt2.split())

	return len(txt1SET & txt2SET)

def PASO1():  #transforma txt -> codones

	path1= os.getcwd()+'/'+CONST

	print (path1)
	listadi = LISTADO(path1)

	print (listadi)
	TRADUCIR(listadi)

def PASO2(N=100):  # obtiene fast con N letras
	path2= os.getcwd()+'/'+CONSTFASTA

	#print (f'PATH = {path2}')

	TRADFASTA= open('TRADFASTA.txt','w')
	listatrad = LISTADOTRAD(path2)

	#print (f' LISTADO TRAD = {listatrad}')

	acumula=''

	for archiv in listatrad:
		print(archiv)

		texto = open(f'{path2}{archiv}','r').read()
		textoN = texto[0:N]
		#print(texto)

		NOMBRE= archiv[:-4]
		#print(archiv[:-4])#

		#textprimero = archiv[0:N]

		#print (textprimero)

		TEXTOFAST= f'''
>{NOMBRE}
{textoN}

		'''
		acumula += TEXTOFAST
	TRADFASTA.write(acumula)

	#CREAR_SEQS(listatrad)

def PASO3():
	path3= os.getcwd()+'/'+CONSTNUBE
	listadi = LISTADO(path3)

	#print (listadi)

	for archiv in listadi:

		#print(archiv)
		texto = open(f'{path3}{archiv}','r').read()

		#print(texto)
		textosplit = texto.split()
		textoset = set(textosplit)

		#print(textosplit)

		for palabra in textoset:
			print (palabra)

def PASO4():  #ordena palabras por frecuencia

	ruta = f'{CONSTNUBE}CHILE2021.txt'

	#print (LISTAFRECUENCIA(ruta))

	for i in LISTAFRECUENCIA(ruta):
		print (i)

def PASO5():
	path= os.getcwd()+'/'+CONSTNUBE
	listadi = LISTADO(path)
	n=len(listadi)

	SALIDA=[]
	k=0
	for i in range(n):
		text1 = open(f'{path}{listadi[i]}','r').read()
		text1=SIMPLIFICA(text1)

		for j in range(i+1,n):
			k+=1
			text2 = open(f'{path}{listadi[j]}','r').read()
			text2=SIMPLIFICA(text2)

			pais1 = listadi[i][:-4]
			pais2 = listadi[j][:-4]
			coinciden =COINCIDENCIAS(text1, text2)
			numeropalabras1 = len(text1.split())
			numeropalabras2 =len(text2.split())
			n1 = round (coinciden / numeropalabras1 *100, 2)
			n2 = round (coinciden / numeropalabras2 *100, 2)

			coinci= [pais1, pais2, coinciden,numeropalabras1,numeropalabras2, n1, n2]

			SALIDA.append(coinci)
			print (k, listadi[i][:-4],listadi[j][:-4])

	ENCABEZADO = ['PAIS 1','PAIS 2','# COINCIDENCIAS','#PALABRAS PAIS 1','#PALABRAS PAIS 2','% COINCIDENCIAS 1', '% COINCIDENCIAS 2']

	SALIDA.sort(key=lambda x: x[1], reverse=True)
	SALIDA.insert(0, ENCABEZADO)

	df1 = pd.DataFrame(SALIDA)
	df1.to_excel("output.xlsx")

#PASO1()  #transforma txt -> codones
#PASO2(N=15000)  # obtiene fast con N letras
#PASO3()
#PASO4() # ordena palabras por frecuencia

PASO5()  # compara todasXtodas coicindencias palabras

print ('')
print ('TERMINE')


import requests
import openpyxl
from openpyxl import Workbook

File_Path="D:\Programming\Application Security\coe-application-security\Data Files\Data.xlsx"
Excel_Location= "D:\Programming\Application Security\coe-application-security\DataFiles\API.xlsx"
Excel_Sheet_Name = 'Sheet1'
ModuleName = "Technicalskills_POST"

def read_specific_cell_values(Excel_Location, Excel_Sheet_Name):
    try:
        Excel_WorkBook = openpyxl.load_workbook(Excel_Location)
        for SheetName in Excel_WorkBook.worksheets:
            if SheetName.title == Excel_Sheet_Name:
                print("Sheet Found")
                ActiveWorkSheet = Excel_WorkBook[SheetName.title]
                print("Title of Sheet = " + ActiveWorkSheet.title)
                # Read Cell Value
                print(ActiveWorkSheet['A2'].value)
                print(ActiveWorkSheet['B2'].value)
                break
            else:
                print("Sheet Not Found")
    except:
        print("Failed for execute")

def read_located_cell_values(Excel_Location, Excel_Sheet_Name):
    Excel_WorkBook = openpyxl.load_workbook(Excel_Location)
    for SheetName in Excel_WorkBook.worksheets:
        if SheetName.title == Excel_Sheet_Name:
            print("Sheet Found")
            ActiveWorkSheet = Excel_WorkBook[SheetName.title]
            print("Title of Sheet = " + ActiveWorkSheet.title)
            Expected_Cell_Value = SheetName.cell(2, 1)
            print(Expected_Cell_Value.value)

def read_refernce_cell_values(Excel_Location, Excel_Sheet_Name):
    Excel_WorkBook = openpyxl.load_workbook(Excel_Location)
    for SheetName in Excel_WorkBook.worksheets:
        if SheetName.title == Excel_Sheet_Name:
            print("Sheet Found")
            ActiveWorkSheet = Excel_WorkBook[SheetName.title]
            print("Title of Sheet = " + ActiveWorkSheet.title)
            Expected_Cell_Value = SheetName.cell(column=1, row=2)
            print(Expected_Cell_Value.value)

def read_number_of_rows_and_columns(Excel_Location, Excel_Sheet_Name):
    Excel_WorkBook = openpyxl.load_workbook(Excel_Location)
    for SheetName in Excel_WorkBook.worksheets:
        if SheetName.title == Excel_Sheet_Name:
            print("Sheet Found")
            ActiveWorkSheet = Excel_WorkBook[SheetName.title]
            print("Title of Sheet = " + ActiveWorkSheet.title)
    rows = SheetName.max_row
    columns = SheetName.max_column
    print("Total Rows are = " + str(rows))
    print("Total Columns are = " + str(columns))

def read_first_row_values(Excel_Location, Excel_Sheet_Name):
    Excel_WorkBook = openpyxl.load_workbook(Excel_Location)
    for SheetName in Excel_WorkBook.worksheets:
        if SheetName.title == Excel_Sheet_Name:
            print("Worksheet Found = " + SheetName.title)
            ActiveWorkSheet = Excel_WorkBook[SheetName.title]
            print("Title of Sheet = " + ActiveWorkSheet.title)

            RowLength = SheetName.max_row
            ColumnLength = SheetName.max_column
            print("Number of Payloads for " + str(SheetName.title) + " = " + str(RowLength - 1))

            for i in range(2, RowLength + 1):
                RowContents = SheetName.cell(row=i, column=1)
                print("Row "+ str(RowContents.row-1) + " = "+ RowContents.value, end="" + "\n")
                return RowContents.value


############################################
## Name: Creating Stack using Linked List ##
## Owner: Darshit Pandya                  ##
## Purpose: Data structure practice       ##
############################################

class StackNode():
	'''This is the inner child class of each Node in
	the stack'''

	def __init__(self, data_):
		self.data = data_
		self.next = None

class Stack(StackNode):
	'''This class creates a stack using a linked list
	dta structure'''

	def __init__(self):
		self.root =None

	def isEmpty(self):
		if self.root == None:
			return True
		else:
			return False

	def push(self, data_):
		# pushes each of the
		new_node = StackNode(data_)
		new_node.next = self.root
		self.root = new_node

	def pop(self):
		# returns the current root node as the head. Pop removes it from
		# the stack and hence to remove it from the linked list too
		if self.isEmpty():
			return float("-inf")
		else:
			temp = self.root
			self.root = self.root.next
			#print(temp.data)

	def peek(self):

		if self.isEmpty():
			return float("-inf")
		else:
			return self.root.data

if __name__ == "__main__":

	stack_object = Stack()

	print(stack_object.peek())
	print(stack_object.pop())
	stack_object.push(10)
	stack_object.push(20)
	stack_object.push(30)

	print(stack_object.peek())


import os
import time

import torch
from logzero import logger

import tools.utils as ut
from tools import utils
from trains import params
from trains.train import Trainer

def main():
    # 训练集
    train_dataset = ut.get_dataset(params.dataset, noise=True)
    # 测试集
    test_dataset = ut.get_dataset(params.dataset, train=False)

    # 初始化模块
    feature_extractor = params.feature_extractor_dict[params.dataset]
    label_predictor = params.label_predictor_dict[params.dataset]
    domain_classifier = params.domain_predictor_dict[params.dataset]

    # 初始化优化器
    optimizer = torch.optim.SGD([{'params': feature_extractor.parameters()},
                                 {'params': label_predictor[0].parameters()},
                                 {'params': label_predictor[1].parameters()},
                                 {'params': label_predictor[2].parameters()},
                                 {'params': domain_classifier.parameters()}],
                                lr=params.learning_rate,
                                momentum=0.9,
                                weight_decay=0.0001)

    # 加载训练参数
    save_path = params.net_save_path
    if not os.path.exists(params.save_dir):
        os.mkdir(params.save_dir)
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    if os.path.exists(save_path + "/fe.pth"):
        feature_extractor.load_state_dict(torch.load(save_path + "/fe.pth"))
    if os.path.exists(save_path + "/dc.pth"):
        domain_classifier.load_state_dict(torch.load(save_path + "/dc.pth"))
    if os.path.exists(save_path + "/lp1.pth"):
        label_predictor[0].load_state_dict(torch.load(save_path + "/lp1.pth"))
        label_predictor[1].load_state_dict(torch.load(save_path + "/lp2.pth"))
        label_predictor[2].load_state_dict(torch.load(save_path + "/lp3.pth"))

    # 初始化Trainer
    trainer = Trainer(feature_extractor, label_predictor, domain_classifier, optimizer)

    # 日志存储
    utils.log_save(params.save_dir)
    start_time = time.time()
    logger.info("initial_model")
    # 初始化训练
    for epoch in range(params.initial_epochs):
        trainer.train(epoch=epoch, dataset=train_dataset)
        # 验证
        trainer.test(dataset=test_dataset)
        # 保存日志到文件
        utils.log_save(params.save_dir, start_time=start_time, limit=3600)
        start_time = time.time()
    # 用未标记的数据集更新模型
    # trainer.update(initial_dataset=train_dataset, unlabeled_dataset=test_dataset, test_dataset=test_dataset)

if __name__ == '__main__':
    main()


"""Base for interacting with the Censys Assets API."""
import re
from typing import Any, Dict, Iterator, List, Optional

from ..api import CensysAsmAPI
from censys.common.exceptions import CensysInvalidColorException

HEX_REGEX = re.compile(r"^#(?:[0-9a-fA-F]{3}){1,2}$")

class Assets(CensysAsmAPI):
    """Assets API class."""

    def __init__(self, asset_type: str, *args, **kwargs):
        """Inits Assets.

        Args:
            asset_type (str): Type of asset to interact with.
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.
        """
        CensysAsmAPI.__init__(self, *args, **kwargs)
        self.base_path = f"assets/{asset_type}"

    def get_assets(
        self,
        page_number: int = 1,
        page_size: Optional[int] = None,
        tag: Optional[List[str]] = None,
        tag_operator: Optional[str] = None,
        source: Optional[List[str]] = None,
    ) -> Iterator[dict]:
        """Requests assets data.

        Args:
            page_number (int): Optional; Page number to begin at when searching.
            page_size (int): Optional; Page size for retrieving assets.
            tag (list): Optional; List of tags to search for.
            tag_operator (str): Optional; Operator to use when searching for tags.
            source (list): Optional; List of sources to search for.

        Yields:
            dict: The assets result returned.
        """
        args: Dict[str, Any] = {}
        if tag:
            args["tag"] = tag
        if tag_operator:
            args["tagOperator"] = tag_operator
        if source:
            args["source"] = source
        yield from self._get_page(
            self.base_path, page_number=page_number, page_size=page_size, args=args
        )

    def get_asset_by_id(self, asset_id: str) -> dict:
        """Requests asset data by ID.

        Args:
            asset_id (str): Requested asset ID.

        Returns:
            dict: Asset search result.
        """
        path = f"{self.base_path}/{asset_id}"

        return self._get(path)

    def get_comments(
        self,
        asset_id: str,
        page_number: int = 1,
        page_size: Optional[int] = None,
    ) -> Iterator[dict]:
        """Requests comments on a specified asset.

        Args:
            asset_id (str): Asset ID for requested comments.
            page_number (int): Optional; Page number to begin at when searching.
            page_size (int): Optional; Page size for retrieving comments.

        Returns:
            generator: Comment search results.
        """
        path = f"{self.base_path}/{asset_id}/comments"

        return self._get_page(
            path, page_number=page_number, page_size=page_size, keyword="comments"
        )

    def get_comment_by_id(self, asset_id: str, comment_id: int) -> dict:
        """Requests a comment on a specified asset by comment ID.

        Args:
            asset_id (str): Asset ID for requested comments.
            comment_id (int): Requested comment ID.

        Returns:
            dict: Comment search result.
        """
        path = f"{self.base_path}/{asset_id}/comments/{comment_id}"

        return self._get(path)

    def add_comment(self, asset_id: str, comment: str) -> dict:
        """Adds a comment to a specified asset on the ASM platform.

        Args:
            asset_id (str): Asset ID to add comment to.
            comment (str): New comment text.

        Returns:
            dict: Added comment results.
        """
        path = f"{self.base_path}/{asset_id}/comments"
        data = {"markdown": str(comment)}

        return self._post(path, data=data)

    def delete_comment(self, asset_id: str, comment_id: int) -> dict:
        """Deletes a comment from a specified asset on the ASM platform by comment ID.

        Args:
            asset_id (str): Asset ID to delete comment from.
            comment_id (int): Comment ID to delete.

        Returns:
            dict: Deleted comment results.
        """
        path = f"{self.base_path}/{asset_id}/comments/{comment_id}"

        return self._delete(path)

    def add_tag(self, asset_id: str, name: str, color: Optional[str] = None) -> dict:
        """Adds a tag to a specified asset on the ASM platform.

        Args:
            asset_id (str): Asset ID to add tag to.
            name (str): New tag name.
            color (str): Optional; New tag color (hex).

        Returns:
            dict: Added tag results.
        """
        path = f"{self.base_path}/{asset_id}/tags"
        data = format_tag(name, color)

        return self._post(path, data=data)

    def delete_tag(self, asset_id: str, name: str) -> dict:
        """Deletes a tag from a specified asset on the ASM platform by tag name.

        Args:
            asset_id (str): Asset ID to delete tag from.
            name (str): Tag name to delete.

        Returns:
            dict: Deleted tag results.
        """
        path = f"{self.base_path}/{asset_id}/tags/{name}"

        return self._delete(path)

def format_tag(name: str, color: Optional[str] = None) -> dict:
    """Formats tag name and color request data.

    Args:
        name (str): Tag name.
        color (str): Optional; Tag color (hex).

    Raises:
        CensysInvalidColorException: Raised if color is not a valid hex color.

    Returns:
        dict: Formatted tag request data.
    """
    if color:
        if not HEX_REGEX.match(color):
            raise CensysInvalidColorException(10037, f"{color} is not a valid color.")
        return {"name": str(name), "color": str(color)}

    return {"name": str(name)}


#!/usr/bin/env python3
import SAMDconfig
import os
import shutil

# Read all board configuration data
print("Reading board config...")
board = SAMDconfig.SAMDconfig("board_data/board-config.ini")

# setup buidl directory and move there all source files
print("Copying sources to build directory...")
board.setup_build_directory('build')

# write config files for bootloader
print("Creating config files for the board bootloader")
bootloader_config_dir = f"{board.build_directory}/uf2-samd21/boards/{board.name}"
os.mkdir(bootloader_config_dir)
board.write_board_mk(bootloader_config_dir)
board.write_board_config(bootloader_config_dir)

# build bootloader
print("Building bootloader...")
bootloader_dir, bootloader_basename = board.build_bootloader()

# copy built bootloader into the package
bootloader_dest = f"{board.package_directory}/bootloaders/{board.name}"
os.mkdir(bootloader_dest)
shutil.copy(f"{bootloader_dir}/{bootloader_basename}.bin", bootloader_dest)
shutil.copy(f"{bootloader_dir}/{bootloader_basename}.elf", bootloader_dest)
#also, copy to the top of build directory
shutil.copy(f"{bootloader_dir}/{bootloader_basename}.bin", board.build_directory)

# add bootloader filename to dictionary
board.d['bootloader_filename']=f"{bootloader_basename}.bin"

# create boards.txt, platform.txt, README.md
print("Writing boards.txt file")
board.write_boards_txt()

#compressing directory into zip archive
board.package_archive()

# create json file
print("Creating json index file")
board.write_index_json()


#!/usr/bin/env python
# Simply prints the state of the obstacle sensors

# Must be run as root - sudo python .py

import time, pi2go

pi2go.init()

try:
    # Pseudocode for robot
    # It has 3 sensors
    # Need to run IR Test

    # Ultimate goal is to go forward

    from pi2go import *

    # Bools for if obstacle on each way
    # Drive my robot forwards - this should be a function
    def update_degrees(num):
        """
        :param num: The num to add to degrees
        :return:
        """
        global degrees
        degrees = (degrees + num) % 360

    # Set sleep timer for reading sensors
    degrees = 0
    speed = 70
    counter = -1
    # Set it forever
    while True:
        # Get Information - True
        left = irLeft()
        right = irRight()
        center = irCentre()

        # If forwards is free go forward
        if not center and not left and not right:
            # Every 2 seconds
            if counter % 20 == 0:
                # Turn towards the left
                spinLeft(70)
                time.sleep(0.3)

            forward(speed)

        time.sleep(0.5)

except KeyboardInterrupt:
    print

finally:
    pi2go.cleanup()


# benodigde libraries
import atexit
import configparser
from pyVim import connect
from pyVmomi import vmodl
from pyVim.connect import Disconnect
import humanize
import sys

# config file
config = configparser.ConfigParser()
config.read('config.ini')
config.sections()

# gebruik printen in .txt file
f = open("gebruik.txt", 'w')
sys.stdout = f

MBFACTOR = float(1 << 20)

printVM = True
printDatastore = True
printHost = True

# opvragen data van vSphere
def head():
    try:
        si = connect.ConnectNoSSL(host= (config['NETLAB'].get('host')), port= 443,
        user= (config['NETLAB'].get('username')), pwd= (config['NETLAB'].get('password')))

        atexit.register(Disconnect, si)
        content = si.RetrieveContent()

        for datacenter in content.rootFolder.childEntity:
            print ("Datacenter: " + datacenter.name)

            if printDatastore:
                datastores = datacenter.datastore
                for ds in datastores:
                    data_store(ds)

            if printHost:
                if hasattr(datacenter.vmFolder, 'childEntity'):
                    hostFolder = datacenter.hostFolder
                    computeResourceList = hostFolder.childEntity

                    for computeResource in computeResourceList:
                        data_res(computeResource)

    except vmodl.MethodFault as e:
        print ("Fout:Controlleer je verbinding met de Cisco VPN en je inloggegevens van Vcenter!", e)

# data van de data store
def data_store(datastore):
    try:
        summary = datastore.summary
        capacity = summary.capacity
        freeSpace = summary.freeSpace
        uncommittedSpace = summary.uncommitted
        freeSpacePercentage = (float(freeSpace) / capacity) * 100

        print ("\nDatastore name: ", summary.name)
        print ("Capacity: ", humanize.naturalsize(capacity, binary=True))

        if uncommittedSpace is not None:
            provisionedSpace = (capacity - freeSpace) + uncommittedSpace

            print ("Provisioned space: ", humanize.naturalsize(provisionedSpace, binary=True))
            print ("Free space: ", humanize.naturalsize(freeSpace, binary=True))
            print ("Free space percentage: " + str(freeSpacePercentage) + "%")

    except Exception:
        print ("De summary kan niet geopend worden!: ", datastore.name)

        pass

# data gebruik resources
def data_res(computeResource):
    try:
        hostList = computeResource.host
        for host in hostList:
            data_host(host)

    except Exception:
        print ("Informatie hierover kan niet opgehaald worden!:", computeResource.name)

        pass

# data van de host
def data_host(host):
    try:
        summary = host.summary
        stats = summary.quickStats
        hardware = host.hardware
        cpuCapacityMhz = (host.hardware.cpuInfo.hz * host.hardware.cpuInfo.numCpuCores) / 1000 / 1000
        cpuUsage = stats.overallCpuUsage
        memoryCapacity = hardware.memorySize
        memoryCapacityInMB = hardware.memorySize/MBFACTOR
        memoryUsage = stats.overallMemoryUsage
        freeMemoryPercentage = 100 - ((float(memoryUsage) / memoryCapacityInMB) * 100)

        print ("--------------------------------------------------")
        print ("Host name: ", host.name)
        print ("Host CPU capacity: ", cpuCapacityMhz, " Mhz")
        print ("Host CPU usage: ", cpuUsage)
        print ("Host memory capacity: ", humanize.naturalsize(memoryCapacity, binary=True))
        print ("Host memory usage: ", memoryUsage / 1024, "GB")
        print ("Free memory percentage: " + str(freeMemoryPercentage) + "%")
        print ("--------------------------------------------------")

    except Exception:
        print ("De host kan niet gepingd worden!:", host.name)

        pass

if __name__ == "__main__":

    head()
    f.close()


#! /usr/bin/python3

# 782. Transform to Chessboard
# Hard
#
# An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.
#
# What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally adjacent? If the task is impossible, return -1.
#
# Examples:
# Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
# Output: 2
# Explanation:
# One potential sequence of moves is shown below, from left to right:
#
# 0110     1010     1010
# 0110 --> 1010 --> 0101
# 1001     0101     1010
# 1001     0101     0101
#
# The first move swaps the first and second column.
# The second move swaps the second and third row.
#
#
# Input: board = [[0, 1], [1, 0]]
# Output: 0
# Explanation:
# Also note that the board with 0 in the top left corner,
# 01
# 10
#
# is also a valid chessboard.
#
# Input: board = [[1, 0], [1, 0]]
# Output: -1
# Explanation:
# No matter what sequence of moves you make, you cannot end with a valid chessboard.
#
# Note:
#
#     board will have the same number of rows and columns, a number in the range [2, 30].
#     board[i][j] will be only 0s or 1s.

from typing import List

class Solution:
    def movesToChessboard(self, board: List[List[int]]) -> int:
        row0 = board[0]
        chess_size = len(row0)
        if not self.check_init_cond(board, row0):
            #print("Init cond failed for board %s" % str(board))
            return -1

        # The board is movable
        first_is_one = self.check_row_1first(row0)
        #print("Swap columns for board %s -- first_is_one is %s" % (board, first_is_one))
        swap_count = 0
        expected_cell = 1 if first_is_one else 0
        for idx in range(len(row0)-1):
            cell = row0[idx]
            if cell != expected_cell:
                # find the swap
                swapped = False
                swap_count += 1
                #print("Looking for a column to swap index %d" % (idx))
                for jdx in range(idx+1, chess_size, 2):
                    if row0[jdx] == expected_cell:
                        swapped = True
                        #print("Found the column %d to swap with %d" % (jdx, idx))
                        self.swap_columns(board, idx, jdx)
                        row0 = board[0]
                        break
                assert(swapped)
            expected_cell = 1 if (expected_cell == 0) else 0

        first_is_one = self.check_column_1first(board)
        #print("Swap rows for board %s -- first_is_one is %s" % (board, first_is_one))
        expected_cell = 1 if first_is_one else 0
        for idx in range(len(board)-1):
            row = board[idx]
            if row[0] != expected_cell:
                # find the swap
                swapped = False
                swap_count += 1
                #print("Looking for a row to swap index %d" % (idx))
                for jdx in range(idx+1, chess_size, 2):
                    if board[jdx][0] == expected_cell:
                        swapped = True
                        #print("Found the row %d to swap with %d" % (jdx, idx))
                        self.swap_rows(board, idx, jdx)
                        break
                assert(swapped)
            expected_cell = 1 if (expected_cell == 0) else 0
        #print("%d swaps for %s" % (swap_count, board))
        return swap_count

    def swap_rows(self, board, index0, index1):
        if index0 == index1: assert(False)
        if index0 >= index1:
            index0, index1 = index1, index0
        l1 = board.pop(index1)
        l0 = board.pop(index0)
        board.insert(index0, l1)
        board.insert(index1, l0)

    def swap_columns(self, board, index0, index1):
        if index0 == index1: assert(False)
        for row in board:
            tmp = row[index0]
            row[index0] = row[index1]
            row[index1] = tmp

    def check_init_cond(self, board, row0):
        diff = 1
        ones = 0
        #print("check ones")
        for cell in row0:
            if cell == 1: ones += 1
        #print("Found %d ones" % ones)
        if (len(row0) % 2) == 0:
            if ones != len(row0)/2: return False
        elif (ones != int(len(row0)/2)) and (ones != int((len(row0)/2) + 1)): return False

        #print("check diff")
        for row in board[1:]:
            same_or_invert = self.is_same_or_invert_row(row0, row)
            if same_or_invert == 0: return False
            diff += same_or_invert
        #print(diff)
        if diff != -1 and diff != 0 and diff != 1: return False
        return True

    def is_same_or_invert_row(self, ref, row):
        if ref[0] == row[0]:
            for idx, e in enumerate(row[1:]):
                if e != ref[idx+1]: return 0
        else:
            for idx, e in enumerate(row[1:]):
                if e == ref[idx+1]: return 0
        return 1 if ref[0] == row[0] else -1

    def check_row_1first(self, row):
        # Find the right columns order, check 1s first
        ones_placed = 0
        ones = 0
        for idx in range(len(row)):
            if row[idx] == 1:
                ones += 1
                if idx % 2 == 0:
                    ones_placed += 1
        if ones < (len(row) / 2):
            return False
        if ones > (len(row) / 2):
            return True
        if ones_placed > (ones / 2):
            return True
        elif ones_placed == (ones / 2):
            return (row[0] == 1)
        return False

    def check_column_1first(self, board):
        # Find the right rows order, check 1s first
        ones_placed = 0
        ones = 0
        for idx in range(len(board)):
            if board[idx][0] == 1:
                ones += 1
                if idx % 2 == 0:
                    ones_placed += 1
        # if there are less 1s than 0s, it's 0s first
        if ones < (len(board) / 2):
            return False
        if ones > (len(board) / 2):
            return True
        if ones_placed > (ones / 2):
            return True
        elif ones_placed == (ones / 2):
            return (board[idx][0] == 1)
        return False

def check_solution():
    s = Solution()

    board = [[0, 1], [1, 0]]
    result = s.movesToChessboard(board)
    assert(result == 0)

    board = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]
    result = s.movesToChessboard(board)
    assert(result == 0)

    board = [[0, 1, 0, 1], [1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 1, 0]]
    result = s.movesToChessboard(board)
    assert(result == -1)

    board = [[1, 1, 0, 1], [1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 1, 0]]
    result = s.movesToChessboard(board)
    assert(result == -1)

    board = [[1, 0], [1, 0]]
    result = s.movesToChessboard(board)
    assert(result == -1)

    board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
    result = s.movesToChessboard(board)
    assert(result == 2)

    board = [   [1,0,0,1,0,0,1,1],
                [0,1,1,0,1,1,0,0],
                [0,1,1,0,1,1,0,0],
                [1,0,0,1,0,0,1,1],
                [1,0,0,1,0,0,1,1],
                [0,1,1,0,1,1,0,0],
                [1,0,0,1,0,0,1,1],
                [0,1,1,0,1,1,0,0]]
    result = s.movesToChessboard(board)
    assert(result == 3)

    board = [   [0,1,1,0,1,1,0,0],
                [0,1,1,0,1,1,0,0],
                [1,0,0,1,0,0,1,1],
                [1,0,0,1,0,0,1,1],
                [1,0,0,1,0,0,1,1],
                [0,1,1,0,1,1,0,0],
                [1,0,0,1,0,0,1,1],
                [0,1,1,0,1,1,0,0]]
    result = s.movesToChessboard(board)
    assert(result == 3)

    board = [   [1,1,0],
                [0,0,1],
                [0,0,1]]
    result = s.movesToChessboard(board)
    assert(result == 2)

    board = [   [1,0,0],
                [0,1,1],
                [1,0,0]]
    result = s.movesToChessboard(board)
    assert(result == 1)

    board = [   [0,0,0,0,1,1,0,1,0,1,1],
                [1,1,1,1,0,0,1,0,1,0,0],
                [1,1,1,1,0,0,1,0,1,0,0],
                [0,0,0,0,1,1,0,1,0,1,1],
                [0,0,0,0,1,1,0,1,0,1,1],
                [1,1,1,1,0,0,1,0,1,0,0],
                [1,1,1,1,0,0,1,0,1,0,0],
                [1,1,1,1,0,0,1,0,1,0,0],
                [0,0,0,0,1,1,0,1,0,1,1],
                [1,1,1,1,0,0,1,0,1,0,0],
                [0,0,0,0,1,1,0,1,0,1,1]]
    result = s.movesToChessboard(board)
    assert(result == 6)

    board = [   [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [0,1,1,0,1,1,0,1,0,1,0,1,0],
                [1,0,0,1,0,0,1,0,1,0,1,0,1],
                [1,0,0,1,0,0,1,0,1,0,1,0,1]]
    result = s.movesToChessboard(board)
    assert(result == 9)

    #print("All tests passed successfully!!")

check_solution()


import random

# Defines the function
def num_guesser():

    print("Welcome friend! Let's play a game!")
    print('I\'m going to pick and number between 1 and 10! Guess what it is!')
    print("let's play!")

    # Instantiates the count
    count = 0

    # Creates Computer's number
    compy = str(random.randint(1,10))

    # Main loop
    user_is_a_loser = 1
    while user_is_a_loser:
        user_guess = input(f'Enter a number! You have made {count} guesses.\n')
        if not user_guess.isdigit():
            print('That still counts. \n')
            count += 1
            continue

        # Increases the count and shows the amount of guessses
        count += 1

        # Taunting
        if count >10:
            print('\nHow are you still guessing...\n')

        # Loop breaker
        if user_guess == compy:
            print(f'Good guess! It was {compy}!\n')
            print(f"It only took you {count} tries!\n")
            break

        # Checks to see if it is too high or too low
        else:
            if int(user_guess) > int(compy):
                print('You guessed too high!')
            else:
                print('Too low bro!')

if __name__ == "__main__":
    num_guesser()


#coding=utf-8
#思考：要存储100个人的年龄？
#解决：使用列表
#本质：是一种有序的集合

'''
创建列表
格式：列表名 = [列表选项1，列表选项2，.....列表选项n]
'''
#创建一个空列表
list1 = []
print(list1)

#创建带有元素的列表
list2 = [18, 19, 20, 21, 22]
print(list2)

#注意：列表中的元素数据可以是不同类型的
list3 = [1, 2, "Linuxcao", "good", "man", True]
print(list3)

print("*&*&*&*&*&")
#列表元素的访问  取值和替换
#注意不要越界 （下标超出了可表示的范围）
#取值 格式: 列表名[下标]
list4 = [1, 2, 3, 4, 5]
print(list4[2])

#替换
list4[2] = 300
print(list4)

#计算5个人年龄的平均值
list5 = [18, 19, 20, 21, 22]
index = 0
sum = 0
while index < 5:
    sum += list5[index]
    index += 1
    if index == 5:
        print("平均年龄是%d" % (sum / 5))

#列表的组合
list5 = [1, 2, 3]
list6 = [4, 5, 6]
list7 = list5 + list6
print(list7)

#列表的重复
list8 = [1, 2, 3]
print(list8*3)

#判断元素是否在列表中
list9 = [1,2,3,4]
print(3 in list9)
print(6 in list9)

#列表截取
list10 = [1,2,3,4,5,6,7,8,9,10]
#截取 3 4 5 6
print(list10[2:6])
#截取 3 4 5 6 7 8 9 10
print(list10[2:])
#截取 1 2 3 4
print(list10[:4])

# 二维列表
list11 = [[1,2,3],[4,5,6],[7,8,9]]
# 访问元素5
print(list11[1][1])

#列表方法

# append 在列表末尾添加新的元素
list12 = [1,2,3,4,5]
list12.append(6)
list12.append([7,8,9])
print(list12)

# 在末尾一次性追加另一个列表
list13 = [1,2,3,4,5]
list13.extend([6,7,8])
# list13.extend(6)
print(list13)

#insert
#在下标处添加一个元素，不覆盖原来数据，原数据向后顺延
list14 = [1,2,3,4,5]
list14.insert(2,100)
list14.insert(2,[200,100])
print(list14)

#pop
# 移除列表指定的下标处的元素（默认移除最后一个元素） 并返回删除的数据
list15 = [1,2,3,4,5]
list15.pop(1)
print(list15)
list15.pop()
print(list15)

#remove
#移除列表中某一个元素第一个匹配的结果
list16 = [1,2,3,4,5,6,7,4,5,6,6]
list16.remove(4)
print(list16)

#index
# 从列表中找出某一个值 第一个匹配的索引值
list18 = [1,2,3,4,5,3,4,5,6]
index18 = list18.index(3)
print(index18)
# 固定范围
list19 = [1,2,3,4,5,3,4,5,6]
index19 = list19.index(3,3,8)
print(index19)

#获取列表元素个数
list20 = [1,2,3,4,5]
print(len(list20))

#获取列表元素的最大值
list21 = [1,2,3,4,20]
print(max(list21))

#获取列表元素的最小值
list22 = [1,2,3,4,20]
print(min(list22))

#查看元素在列表中出现的次数
list23 = [1,2,3,4,5,6,5,4,3,2,1]
print(list23.count(3))

#举例
#删除列表中所有元素3
list24 = [1,2,3,4,5,6,5,4,3,2,1]
print(list24.count(3))
num24 = 0
all = list24.count(3)
while num24 < all:
    list24.remove(3)
    num24 += 1
print(list24)

# 倒叙
list25 = [1,2,3,4,5]
list25.reverse()
print(list25)

# 排序
list26 = [1,2,4,3,5]
list26.sort()
print(list26)

# 将元祖转换成列表  (1,2,3,4)  ---> [1,2,3,4]
list31 = list((1,2,3,4))
print(list31)

#实例
#输入10个整数，并且找出第二大数值
listNum = []
num = 0
while num < 10:
    listNum.append(int(input()))
    num += 1
print(listNum)

#首先排序（默认升序）
listNum.sort()
print(listNum)

num1 = 0
all = listNum.count(max(listNum))
listNum_max = max(listNum)
while num1 < all:
    listNum.remove(listNum_max)
    num1 += 1
listNum_second_max = max(listNum)
print(listNum_second_max)


"""Attachments."""

from __future__ import annotations

from logging import getLogger
from pathlib import Path

logger = getLogger(__name__)

filetypes = {
    "画像": [
        "jpg",
        "jpeg",
        "png",
        "aping",
        "gif",
        "tiff",
        "bmp",
        "webp",
    ],
    "動画": [
        "mp4",
        "webm",
        "avi",
        "mov",
    ],
    "音声": [
        "mp3",
        "m4a",
        "wav",
        "flac",
    ],
}

def judge_filetype(filename: str) -> str:
    ext = Path(filename).suffix
    # ドットを削除
    ext = ext.replace(".", "")
    for key in filetypes:
        if ext.lower() in filetypes[key]:
            return key
    return "ファイル"

def extract_filetypes(filenames: list[str]) -> str:
    """ファイル名のリストから読み上げ内容を取得.

    「画像,音声を送信しました」
    """
    logger.debug("receved files: %s", str(filenames))
    result = set()
    for f in filenames:
        t = judge_filetype(f)
        if t:
            result.add(t)
    logger.debug(result)
    if result:
        return ",".join(result) + "を送信しました。"
    return ""


import matplotlib.pyplot as plt
def calc_money(num,syakkin):
    b = num
    #print(b)
    y1 = syakkin
    month=0
    while month < 360:
        y2 = y1+y1 * 0.02 / 12.0 - b
        y1 = y2

        month += 1
        if y1<=0:
            break
    return y1,month

if __name__ == '__main__':
    saiteki_kingaku =[]
    syakkin = int(input('いくらの借金をしますか?'))
    for b in range(100000,115000,1):
        result = calc_money(b,syakkin)
        if result[0] <=0 and result[1]==360:
            #print('月'+str(b)+'円の時クリア')
            saiteki_kingaku.append(b)
            #print(result[0],result[1])
            plt.plot(result[0],result[1],marker='o')
    print(saiteki_kingaku)
    plt.show()


#이코테 180p 정렬 실전문제2
n=int(input())
arrays=[]
for i in range(n):
  data=list(input().split())
  arrays.append((data[0],int(data[1])))

arrays=sorted(arrays,key=lambda data:data[1])

for i in arrays:
  print(i[0],end=' ')

Sort/성적이낮은순서로 학생출력.py

성적이낮은순서로 학생출력.py


"""
CLI tool for uploading to zenodo
"""
import logging
import os
from functools import partial
from pathlib import Path

import click
from dotenv import load_dotenv
from openscm_zenodo.zenodo import create_new_zenodo_version, get_bucket_id, upload_file
from tqdm.contrib.concurrent import thread_map

DEPOSITION_ID_OLD: str = "7972657"
"""
Deposition ID of our Zenodo archive. This can be any version.
"""

ZENODO_URL: str = "zenodo.org"
"""Zenodo URL to upload to"""

ZENODO_FILE_NAME: str = "zenodo.json"
"""Name of the file in which the Zenodo metadata is written"""

openscm_zenodo_logger = logging.getLogger("openscm_zenodo")
openscm_zenodo_logger.setLevel(logging.INFO)

logFormatter = logging.Formatter(
    "%(levelname)s - %(asctime)s %(name)s %(threadName)s (%(module)s:%(funcName)s:%(lineno)d):  %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
stdoutHandler = logging.StreamHandler()
stdoutHandler.setFormatter(logFormatter)

openscm_zenodo_logger.addHandler(stdoutHandler)

@click.command()
@click.argument(
    "bundle_path",
    type=click.Path(exists=True, file_okay=False, resolve_path=True, path_type=Path),
)
def upload_bundle(bundle_path: Path) -> None:
    """
    Upload bundle to zenodo

    Parameters
    ----------
    bundle_path
        Path to bundle
    """
    load_dotenv()

    new_version_deposition_id = create_new_zenodo_version(
        deposition_id=DEPOSITION_ID_OLD,
        zenodo_url=ZENODO_URL,
        token=os.environ["ZENODO_TOKEN"],
        deposit_metadata=bundle_path / ZENODO_FILE_NAME,
    )

    click.echo(f"Deposition ID to use: {new_version_deposition_id}")

    bucket_id = get_bucket_id(
        deposition_id=new_version_deposition_id,
        zenodo_url=ZENODO_URL,
        token=os.environ["ZENODO_TOKEN"],
    )

    click.echo(f"Uploading to bucket: {bucket_id}")

    files_to_upload = []
    for dir_path, _, files in os.walk(bundle_path):
        # Ignore interim outputs
        if "interim" in dir_path:
            continue

        for file in files:
            # Ignore unexecuted notebooks for upload
            if "unexecuted" in file:
                continue

            files_to_upload.append(Path(dir_path) / file)

    click.echo(f"{len(files_to_upload)} files to upload")

    thread_map(
        partial(
            upload_file,
            bucket=bucket_id,
            root_dir=str(bundle_path),
            zenodo_url=ZENODO_URL,
            token=os.environ["ZENODO_TOKEN"],
        ),
        (str(file) for file in files_to_upload),
        desc="File uploads",
        total=len(files_to_upload),
    )

if __name__ == "__main__":
    upload_bundle()


def read_data_from_file(input_filename):
    '''
    считывает данные из файла
    '''
    walls_data=[]
    walls_number=0
    heals_data=[]
    heals_number=0
    cactuses_data=[]
    cactuses_number=0
    units_data=[]
    units_number=0
    with open(input_filename, 'r') as input_file:
        for line in input_file:
            if len(line.strip()) == 0 or line[0] == '#':
                continue  # пустые строки и строки-комментарии пропускаем
            object_type = line.split()[0]
            if object_type == "unit":
                units_data.append([])
                parse_unit_parameters(line, units_data, units_number)
                units_number += 1
            if object_type == "wall":
                walls_data.append([])
                parse_wall_parameters(line, walls_data, walls_number)
                walls_number += 1
            if object_type == "heal":
                heals_data.append([])
                parse_heal_parameters(line, heals_data, heals_number)
                heals_number += 1
            if object_type == "cactus":
                cactuses_data.append([])
                parse_cactus_parameters(line, cactuses_data, cactuses_number)
                cactuses_number += 1
    return((walls_data,units_data, heals_data, cactuses_data))

def parse_wall_parameters(line, walls_data, walls_number):
    '''
    считывает данные класса стен
    '''
    split = line.split()
    for i in range(1,len(split)):
        split[i] = int(split[i])
        walls_data[walls_number].append([])
        walls_data[walls_number][i-1]=split[i]

def parse_heal_parameters(line, heals_data, heals_number):
    '''
    считывает данные класса аптечек
    '''
    split = line.split()
    for i in range(1,len(split)):
        split[i] = int(split[i])
        heals_data[heals_number].append([])
        heals_data[heals_number][i-1]=split[i]

def parse_cactus_parameters(line, cactuses_data, cactuses_number):
    '''
    считывает данные класса кактусов
    '''
    split = line.split()
    for i in range(1,len(split)):
        split[i] = int(split[i])
        cactuses_data[cactuses_number].append([])
        cactuses_data[cactuses_number][i-1]=split[i]

def parse_unit_parameters(line, units_data, units_number):
    '''
    считывает данные класса юнитов
    '''
    split = line.split()
    unit_points=[]
    for i in range(1,len(split)):
        split[i] = int(split[i])
    for i in range(6):
        units_data[units_number].append(split[i+1])
    unit_points.append(split[7])
    for i in range(9,len(split),2):
        unit_points.append((split[i-1],split[i]))
    units_data[units_number].append(unit_points)