import accept
import logging

from aiohttp import web, web_exceptions
from aiohttp_swagger import setup_swagger
from model import ClientModel, ItemNotFoundException
from protocol import *
from prometheus_client import REGISTRY, exposition
from urllib.parse import parse_qs
from voluptuous import MultipleInvalid

class Api:
    DEFAULT_CONTENT_TYPE = "application/json"
    logger = logging.getLogger(__name__)

    registry = REGISTRY
    __encoders = {
        "application/xml": XMLEncoder(),
        "application/json": JsonEncoder()
    }

    def __init__(self, host, port, transactor):
        self.__app = web.Application()
        self.__host = host
        self.__port = port
        self.__app.add_routes([
            web.get('/', self.health),
            web.get('/metrics', self.metrics),
            web.get('/v1/cards', self.card_list),
            web.post('/v1/cards', self.add_card),
            web.get('/v1/clients', self.client_list),
            web.post('/v1/clients', self.add_client),
            web.get(r'/v1/clients/{id:\d+}/balance', self.client_balance),
            web.put(r'/v1/cards/{id:\d+}', self.change_card)
        ])
        self.__client_model = ClientModel(transactor)

    def __paginate(self, request):
        qs = parse_qs(request.query_string)
        offsets = qs.get('offset', [0])
        if len(offsets) > 1:
            raise web_exceptions.HTTPBadRequest(text='Invalid offset value')

        limits = qs.get('limit', [20])
        if len(limits) > 1:
            raise web_exceptions.HTTPBadRequest(text='Invalid limit value')

        return int(offsets[0]), int(limits[0])

    def __choose_encoder(self, request):
        for accept_header in accept.parse(request.headers.get('Accept')):
            if accept_header.media_type == '*/*':
                return self.__encoders.get(self.DEFAULT_CONTENT_TYPE)
            encoder = self.__encoders.get(accept_header.media_type)
            if encoder is not None:
                return encoder
        raise web_exceptions.HTTPNotAcceptable()

    async def __decode_post(self, request):
        if request.content_type == "application/json":
            return await request.json()
        if request.content_type == "application/xml":
            return {"data": "xml"}
        raise web_exceptions.HTTPBadRequest(
            text="Unknown Content-Type header. Only application/json, application/xml are allowed."
        )

    async def start(self):
        setup_swagger(self.__app, swagger_url='/v1/docs')
        runner = web.AppRunner(self.__app)
        await runner.setup()
        service = web.TCPSite(runner, self.__host, self.__port)
        await service.start()
        self.logger.info('Service is started at %s:%s', self.__host, self.__port)

    async def health(self, _):
        """
        ---
        description: Запрос для проверки успешного запуска сервиса.
        tags:
        - Health check
        produces:
        - text/plain
        responses:
            "200":
                description: успех. Возвращает информацию о сервисе
        """
        return web.Response(text="Ok")

    async def metrics(self, request):
        """
        ---
        description: Запрос для получения метрик сервиса
        tags:
        - Metrics
        produces:
        - text/plain
        responses:
            "200":
                description: успех. Возвращает метрики
        """
        encoder, content_type = exposition.choose_encoder(request.headers.get('Accept'))
        scrape = encoder(self.registry)
        return web.Response(headers=dict([('Content-Type', content_type)]), body=scrape)

    async def card_list(self, request):
        """
        ---
        description: Запрос для получения списка карт клиентов
        tags:
        - Cards
        produces:
        - application/json
        - application/xml
        parameters:
        - name: offset
          in: query
          description: Pagination offset
          required: false
          type: integer
        - name: limit
          in: query
          description: Pagination limit
          required: false
          type: integer
        responses:
            "200":
                description: успех. Возвращает список карт клиентов
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        encoder = self.__choose_encoder(request)
        offset, limit = self.__paginate(request)
        cards, count = await self.__client_model.all_cards(offset, limit)
        return web.Response(content_type=encoder.content_type, body=encoder.encode(cards), headers={"X-Total": str(count)})

    async def add_card(self, request):
        """
        ---
        description: Запрос для добавления новой карты клиента
        tags:
        - Cards
        produces:
        - application/json
        - application/xml
        parameters:
        - name: card
          in: body
          description: данные новой карты
          required: true
          schema:
            type: object
            properties:
              owner_id:
                type: integer
                description: идентификатор владельца карты
                required: true
              payment_system:
                type: string
                description: платежная система
                required: true
              currency:
                type: string
                description: валюта карты
                required: true
              balance:
                type: numeric
                description: баланс карты
                required: true
        responses:
            "200":
                description: успех. Возвращает данные новой карты клиента
            "404":
                description: ошибка. Клиент не найден
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        encoder = self.__choose_encoder(request)
        data = await self.__decode_post(request)
        try:
            card = await self.__client_model.add_card(data)
            return web.HTTPCreated(content_type=encoder.content_type, body=encoder.encode(card))
        except MultipleInvalid as e:
            raise web_exceptions.HTTPBadRequest(text=str(e))
        except ItemNotFoundException as e:
            raise web_exceptions.HTTPNotFound(text=str(e))

    async def client_list(self, request):
        """
        ---
        description: Запрос для получения списка клиентов
        tags:
        - Clients
        produces:
        - application/json
        - application/xml
        parameters:
        - name: offset
          in: query
          description: Pagination offset
          required: false
          type: integer
        - name: limit
          in: query
          description: Pagination limit
          required: false
          type: integer
        responses:
            "200":
                description: успех. Возвращает список клиентов
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        encoder = self.__choose_encoder(request)
        offset, limit = self.__paginate(request)
        clients, count = await self.__client_model.all_clients(offset, limit)
        return web.Response(content_type=encoder.content_type, body=encoder.encode(clients), headers={"X-Total": str(count)})

    async def add_client(self, request):
        """
        ---
        description: Запрос для добавления нового клиента
        tags:
        - Clients
        produces:
        - application/json
        - application/xml
        parameters:
        - name: card
          in: body
          description: данные нового клиента
          required: true
          schema:
            type: object
            properties:
              name:
                type: string
                description: имя клиента
        responses:
            "200":
                description: успех. Возвращает данные нового клиента
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        encoder = self.__choose_encoder(request)
        data = await self.__decode_post(request)
        try:
            client = await self.__client_model.add_client(data)
            return web.HTTPCreated(content_type=encoder.content_type, body=encoder.encode(client))
        except MultipleInvalid as e:
            raise web_exceptions.HTTPBadRequest(text=str(e))

    async def client_balance(self, request):
        """
        ---
        description: Запрос для получения баланса клиента
        tags:
        - Clients
        produces:
        - application/json
        - application/xml
        parameters:
        - name: id
          in: path
          description: идентификатор клиента
          required: false
          type: integer
        responses:
            "200":
                description: успех. Возвращает данные нового клиента
            "404":
                description: ошибка. Клиент не найден
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        client_id = int(request.match_info.get('id'))
        encoder = self.__choose_encoder(request)
        client = await self.__client_model.client_balance(client_id)
        return web.Response(content_type=encoder.content_type, body=encoder.encode(client))

    async def change_card(self, request):
        """
        ---
        description: Запрос для изменение данных по карте
        tags:
        - Cards
        produces:
        - application/json
        - application/xml
        parameters:
        - name: id
          in: path
          description: идентификатор карты
          required: true
          type: integer
        - name: card
          in: body
          description: данные карты
          required: true
          schema:
            type: object
            properties:
              owner_id:
                type: integer
                description: идентификатор владельца карты
              payment_system:
                type: string
                description: платежная система
              currency:
                type: string
                description: валюта карты
              balance:
                type: float
                description: баланс карты
        responses:
            "200":
                description: успех. Возвращает измененные данные карты
            "400":
                description: ошибка клиента. Указаны неверные данные карты
            "404":
                description: ошибка. Карта не найдена
            "406":
                description: ошибка клиента. Указан неверный Accept
        """
        card_id = int(request.match_info.get('id'))
        encoder = self.__choose_encoder(request)
        data = await self.__decode_post(request)
        try:
            card = await self.__client_model.change_card(card_id, data)
            return web.Response(content_type=encoder.content_type, body=encoder.encode(card))
        except MultipleInvalid as e:
            raise web_exceptions.HTTPBadRequest(text=str(e))


#!/usr/bin/python -tt
# -*- coding: utf-8 -*-

# Examen LAGRS, diciembre 2018
# NOMBRE: Jorge Luzon Lopez
# LOGIN: jluzon

import telepot
import telepot.namedtuple
import time
import subprocess,sys
import os
from telepot.loop import MessageLoop
from optparse import OptionParser

PUERTOS_TCP = [6666 , 443 , 7899]

def readkey():
  try:
    file = open("token.txt","r")
    key = file.readline()
    file.close()
    return key
  except IOError:
    sys.stderr.write("Could not read key\n")
    raise SystemExit

def iduser():
  try:
    file = open("id_usuario.txt","r")
    key = file.readline()
    file.close()
    return key
  except IOError:
    sys.stderr.write("Could not read key\n")
    raise SystemExit

TOKEN = readkey()
ID_USUARIO = iduser()
bot = telepot.Bot(TOKEN)

def checkpuerto(port):
  for p in PUERTOS_TCP:
    if int(p) == int(port):
      return True

def checkline(lines):
  r=""
  for l in lines:
    fields=l.split()
    if checkpuerto(fields[3].split(":")[-1]):
      r+=fields[3].split(":")[-1] + " " + fields[5] + "\n"
  return r

def donetstat():
  cmd = "netstat -tupan"
  try:
    out=subprocess.check_output(cmd.split())
    out=out.split("\n")
    out.pop(0)
    out.pop(0)
    out.pop()
    r=checkline(out)
    return r
  except:
    sys.stderr.write("CMD failed\n")
    raise SystemExit

def handle():
  respuesta = donetstat()
  if len(respuesta) > 0:
    respuesta += "Ports USED\n"
    bot.sendMessage(ID_USUARIO,respuesta)
  return

def main():

  handle()

if __name__ == '__main__':
  main()


import torch
from torch import nn
from torch.autograd import Variable

class topk_crossEntrophy(nn.Module):
    def __init__(self, top_k=0.7):
        super(topk_crossEntrophy, self).__init__()
        self.loss = nn.NLLLoss()
        self.top_k = top_k
        self.softmax = nn.LogSoftmax()
        return

    def forward(self, input, target):
        softmax_result = self.softmax(input)

        loss = Variable(torch.Tensor(1).zero_()).cuda()
        for idx, row in enumerate(softmax_result):
            gt = target[idx]
            pred = torch.unsqueeze(row, 0)
            gt = torch.unsqueeze(gt, 0)
            cost = self.loss(pred, gt)
            loss = torch.cat((loss, cost.unsqueeze(0)), 0)

        loss = loss[1:]
        if self.top_k == 1:
            valid_loss = loss

        index = torch.topk(loss, int(self.top_k * loss.size()[0]))
        valid_loss = loss[index[1]]

        return torch.mean(valid_loss)


import re
import json
import base64
import pandas as pd
import networkx as nx
from textblob import TextBlob
from collections import defaultdict
from arabic_reshaper import reshape
from bidi.algorithm import get_display
from requests_toolbelt.multipart import decoder

def generate_hashtag_data(file_path):
    # Read the excel file
    df = pd.read_excel(file_path)

    # Define function to extract hashtags from each tweet
    def extract_hashtags(text):
        hashtags = re.findall(r'\#\w+', text)
        return hashtags

    # Create a list of all hashtags in the dataframe
    all_hashtags = []
    for tweet in df['Tweet']:
        hashtags = extract_hashtags(tweet)
        all_hashtags.extend(hashtags)

    # Create a dictionary to store the frequency of each hashtag
    frequency = {}
    for hashtag in all_hashtags:
        if hashtag in frequency:
            frequency[hashtag] += 1
        else:
            frequency[hashtag] = 1

    # Reshape and reorder the text
    reshaped_text = {}
    for k, v in frequency.items():
        reshaped_k = reshape(k)
        bidi_k = get_display(reshaped_k)
        reshaped_text[bidi_k] = v

    # Return the data
    return {
        "hashtag_frequency": frequency,
        "reshaped_text": reshaped_text
    }

def generate_sentiment_data(file_path):
    # Load the data from Excel file
    df = pd.read_excel(file_path)

    # Define function to calculate sentiment polarity
    def get_sentiment(text):
        blob = TextBlob(text)
        return blob.sentiment.polarity

    # Create a dictionary to store sentiment values for each user
    sentiments = defaultdict(list)

    # Iterate over each row in the DataFrame
    for index, row in df.iterrows():
        # Get the user and tweet
        user = row['User']
        tweet = row['Tweet']

        # Calculate sentiment polarity of the tweet
        sentiment = get_sentiment(tweet)

        # Append sentiment to the list of sentiments for the user
        sentiments[user].append(sentiment)

    # Create a list of sentiment data for each user
    sentiment_data = []
    for user in df['User'].unique():
        user_sentiments = sentiments[user]
        indices = list(range(1, len(user_sentiments) + 1))
        sentiment_data.append(
            {"user": user, "indices": indices, "sentiments": user_sentiments})

    return sentiment_data

def generate_user_tweet_counts(file_path):
    # Read the Excel file into a Pandas DataFrame
    df = pd.read_excel(file_path)

    # Group the data by user and count the number of tweets for each user
    user_counts = df.groupby('User').size().reset_index(name='count')

    # Convert the user_counts DataFrame into a list of dictionaries
    user_tweet_counts = user_counts.to_dict('records')

    return user_tweet_counts

def generate_user_mentions_graph_data(file_path):
    # Load the Excel file into a Pandas DataFrame
    df = pd.read_excel(file_path)

    # Extract the usernames from the tweet column using regular expressions
    df['username'] = df['Tweet'].str.extract(r'@(\w+)')

    # Create a list of unique usernames
    users = list(df['username'].dropna().unique())

    # Create an empty directed graph using NetworkX
    G = nx.DiGraph()

    # Add nodes to the graph for each user
    for user in users:
        G.add_node(user)

    # Add edges to the graph for each mention
    for tweet in df['Tweet']:
        # Find all mentions in the tweet using regular expressions
        mentions = re.findall(r'@(\w+)', tweet)
        # Create edges between the mentioned users
        for i in range(len(mentions)):
            for j in range(i+1, len(mentions)):
                G.add_edge(mentions[i], mentions[j])

    # Calculate the degree centrality of each node (user)
    centrality = nx.degree_centrality(G)

    # Sort the centrality dictionary by value in descending order
    sorted_centrality = sorted(
        centrality.items(), key=lambda x: x[1], reverse=True)

    # Get the top 10 most influential users
    top_users = [user[0] for user in sorted_centrality[:10]]

    # Create a subgraph of the top users
    H = G.subgraph(top_users)

    # Create a dictionary containing the necessary data for the frontend
    graph_data = {
        'nodes': [node for node in H.nodes()],
        'edges': [{'source': edge[0], 'target': edge[1]} for edge in H.edges()],
    }

    return graph_data

def generate_map_data(file_path):
    # Load the data from the Excel file
    data = pd.read_excel(file_path)

    # Filter out rows without coordinates
    data = data[data['coordinates'].notna()]

    # Extract coordinates and create a list of dictionaries with lat and lon
    coords_list = []
    for i, row in data.iterrows():
        coords_str = row['coordinates']
        lon = float(coords_str.split(',')[0].split('=')[1])
        lat = float(coords_str.split(',')[1].split('=')[1][:-1])
        coords_list.append({'lat': lat, 'lon': lon})

    # Return the coordinates data
    return coords_list

headers = {
    "Access-Control-Allow-Origin": "*",  # Adjust the value according to your needs
    "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key",
    "Access-Control-Allow-Methods": "OPTIONS,GET,POST,PUT,PATCH,DELETE",
    "Access-Control-Allow-Credentials": "true",
}

def handler(event, context):
    # decode the multipart form data
    decoded_str = base64.b64decode(event["body"])

    content_type_header = event["headers"]["content-type"]

    multipart_data = decoder.MultipartDecoder(
        decoded_str, content_type_header)

    # get the file data from the multipart data
    file = multipart_data.parts[0]

    # print the file name
    print(file.headers[b'Content-Disposition'].decode().split(';')[1])

    # generate hashtag data
    hashtag_data = generate_hashtag_data(file.content)

    # generate sentiment data
    sentiment_data = generate_sentiment_data(file.content)

    # generate user tweet counts
    user_tweet_counts = generate_user_tweet_counts(file.content)

    # generate user mentions graph data
    user_mentions_graph_data = generate_user_mentions_graph_data(file.content)

    # generate map data
    map_data = generate_map_data(file.content)

    # return the response
    return {
        "statusCode": 200,
        "headers": headers,
        "body": json.dumps({
            "hashtag_data": hashtag_data,
            "sentiment_data": sentiment_data,
            "user_tweet_counts": user_tweet_counts,
            "user_mentions_graph_data": user_mentions_graph_data,
            "map_data": map_data
        })
    }


import math
def roundPrice(A):
    # attention: in python3, round(1.5) = 1 !!!
    def round(x):
        fac = x - math.floor(x)
        return math.ceil(x) if fac >= 0.5 else math.floor(x)

    if not A:
        return A
    roundSum = sum(map(round, A))
    sumRound = round(sum(A))
    print(roundSum)
    print(sumRound)
    res = [round(a) for a in A]
    if roundSum == sumRound:
        return res
    elif roundSum > sumRound:
        cnt = roundSum - sumRound # need to make cnt number to round(number) - 1
        nums = sorted([(a - math.floor(a), a, i) for i, a in enumerate(A)])
        for fac, a, i in nums:
            if fac >= 0.5 and cnt > 0:
                res[i] = math.floor(a)
                cnt -= 1
            else:
                res[i] = round(a)
        return res
    else:
        cnt = sumRound - roundSum  # need to make cnt number to round(number) + 1
        nums = sorted([(a - math.floor(a), a, i) for i, a in enumerate(A)])[::-1]
        for fac, a, i in nums:
            if fac < 0.5 and cnt > 0:
                res[i] = math.ceil(a)
                cnt -= 1
            else:
                res[i] = round(a)
        return res

print(roundPrice([1,2,3,4]))


'''
Created on May 29, 2017

@author: hfrieden
Export ASC DEM files

'''

import struct
import bpy
import bmesh
import os.path as path
import ArmaToolbox
from math import sqrt

def vertIdx(x,y,ncols, nrows):
    return y*ncols + x

def exportASC(context, fileName):
    filePtr = open(fileName, "wt")
    obj = context.object
    props = obj.armaHFProps

    # dump Header
    verts = len(obj.data.vertices)
    rowcols = sqrt(verts)

    filePtr.write("ncols         " + str(rowcols) + "\n")
    filePtr.write("nrows         " + str(rowcols) + "\n")
    filePtr.write("xllcorner     " + str(props.northing) + "\n")
    filePtr.write("yllcorner     " + str(props.easting) + "\n")
    filePtr.write("cellsize      " + str(props.cellSize) + "\n")
    filePtr.write("NODATA_value  " + str(props.undefVal) + "\n")

    # dump the heightfield. One line contains one row of vertices
    row = rowcols
    for v in obj.data.vertices:
        filePtr.write("{:.4f}".format(v.co[2]))
        row -= 1
        if row == 0:
            filePtr.write("\n")
            row = rowcols
        else:
            filePtr.write(" ")

    filePtr.close()


# 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 isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        unival = root.val

        stack = [root]
        while len(stack) > 0:
            cur = stack.pop()
            if cur != None:
                if cur.val != unival:
                    return False
                stack.append(cur.left)
                stack.append(cur.right)

        return True


from __future__ import absolute_import

import hashlib
import json
import os
import re
import socket

from mercurial.i18n import _

from mercurial import (
    error,
    pathutil,
    url as urlmod,
    util,
    vfs as vfsmod,
    worker,
)

from ..largefiles import lfutil

# 64 bytes for SHA256
_lfsre = re.compile(r'\A[a-f0-9]{64}\Z')

class lfsvfs(vfsmod.vfs):
    def join(self, path):
        """split the path at first two characters, like: XX/XXXXX..."""
        if not _lfsre.match(path):
            raise error.ProgrammingError('unexpected lfs path: %s' % path)
        return super(lfsvfs, self).join(path[0:2], path[2:])

    def walk(self, path=None, onerror=None):
        """Yield (dirpath, [], oids) tuple for blobs under path

        Oids only exist in the root of this vfs, so dirpath is always ''.
        """
        root = os.path.normpath(self.base)
        # when dirpath == root, dirpath[prefixlen:] becomes empty
        # because len(dirpath) < prefixlen.
        prefixlen = len(pathutil.normasprefix(root))
        oids = []

        for dirpath, dirs, files in os.walk(self.reljoin(self.base, path or ''),
                                            onerror=onerror):
            dirpath = dirpath[prefixlen:]

            # Silently skip unexpected files and directories
            if len(dirpath) == 2:
                oids.extend([dirpath + f for f in files
                             if _lfsre.match(dirpath + f)])

        yield ('', [], oids)

class filewithprogress(object):
    """a file-like object that supports __len__ and read.

    Useful to provide progress information for how many bytes are read.
    """

    def __init__(self, fp, callback):
        self._fp = fp
        self._callback = callback # func(readsize)
        fp.seek(0, os.SEEK_END)
        self._len = fp.tell()
        fp.seek(0)

    def __len__(self):
        return self._len

    def read(self, size):
        if self._fp is None:
            return b''
        data = self._fp.read(size)
        if data:
            if self._callback:
                self._callback(len(data))
        else:
            self._fp.close()
            self._fp = None
        return data

class local(object):
    """Local blobstore for large file contents.

    This blobstore is used both as a cache and as a staging area for large blobs
    to be uploaded to the remote blobstore.
    """

    def __init__(self, repo):
        fullpath = repo.svfs.join('lfs/objects')
        self.vfs = lfsvfs(fullpath)
        usercache = lfutil._usercachedir(repo.ui, 'lfs')
        self.cachevfs = lfsvfs(usercache)
        self.ui = repo.ui

    def open(self, oid):
        """Open a read-only file descriptor to the named blob, in either the
        usercache or the local store."""
        # The usercache is the most likely place to hold the file.  Commit will
        # write to both it and the local store, as will anything that downloads
        # the blobs.  However, things like clone without an update won't
        # populate the local store.  For an init + push of a local clone,
        # the usercache is the only place it _could_ be.  If not present, the
        # missing file msg here will indicate the local repo, not the usercache.
        if self.cachevfs.exists(oid):
            return self.cachevfs(oid, 'rb')

        return self.vfs(oid, 'rb')

    def download(self, oid, src):
        """Read the blob from the remote source in chunks, verify the content,
        and write to this local blobstore."""
        sha256 = hashlib.sha256()

        with self.vfs(oid, 'wb', atomictemp=True) as fp:
            for chunk in util.filechunkiter(src, size=1048576):
                fp.write(chunk)
                sha256.update(chunk)

            realoid = sha256.hexdigest()
            if realoid != oid:
                raise error.Abort(_('corrupt remote lfs object: %s') % oid)

        # XXX: should we verify the content of the cache, and hardlink back to
        # the local store on success, but truncate, write and link on failure?
        if not self.cachevfs.exists(oid):
            self.ui.note(_('lfs: adding %s to the usercache\n') % oid)
            lfutil.link(self.vfs.join(oid), self.cachevfs.join(oid))

    def write(self, oid, data):
        """Write blob to local blobstore.

        This should only be called from the filelog during a commit or similar.
        As such, there is no need to verify the data.  Imports from a remote
        store must use ``download()`` instead."""
        with self.vfs(oid, 'wb', atomictemp=True) as fp:
            fp.write(data)

        # XXX: should we verify the content of the cache, and hardlink back to
        # the local store on success, but truncate, write and link on failure?
        if not self.cachevfs.exists(oid):
            self.ui.note(_('lfs: adding %s to the usercache\n') % oid)
            lfutil.link(self.vfs.join(oid), self.cachevfs.join(oid))

    def read(self, oid, verify=True):
        """Read blob from local blobstore."""
        if not self.vfs.exists(oid):
            blob = self._read(self.cachevfs, oid, verify)

            # Even if revlog will verify the content, it needs to be verified
            # now before making the hardlink to avoid propagating corrupt blobs.
            # Don't abort if corruption is detected, because `hg verify` will
            # give more useful info about the corruption- simply don't add the
            # hardlink.
            if verify or hashlib.sha256(blob).hexdigest() == oid:
                self.ui.note(_('lfs: found %s in the usercache\n') % oid)
                lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid))
        else:
            self.ui.note(_('lfs: found %s in the local lfs store\n') % oid)
            blob = self._read(self.vfs, oid, verify)
        return blob

    def _read(self, vfs, oid, verify):
        """Read blob (after verifying) from the given store"""
        blob = vfs.read(oid)
        if verify:
            _verify(oid, blob)
        return blob

    def has(self, oid):
        """Returns True if the local blobstore contains the requested blob,
        False otherwise."""
        return self.cachevfs.exists(oid) or self.vfs.exists(oid)

class _gitlfsremote(object):

    def __init__(self, repo, url):
        ui = repo.ui
        self.ui = ui
        baseurl, authinfo = url.authinfo()
        self.baseurl = baseurl.rstrip('/')
        useragent = repo.ui.config('experimental', 'lfs.user-agent')
        if not useragent:
            useragent = 'git-lfs/2.3.4 (Mercurial %s)' % util.version()
        self.urlopener = urlmod.opener(ui, authinfo, useragent)
        self.retry = ui.configint('lfs', 'retry')

    def writebatch(self, pointers, fromstore):
        """Batch upload from local to remote blobstore."""
        self._batch(pointers, fromstore, 'upload')

    def readbatch(self, pointers, tostore):
        """Batch download from remote to local blostore."""
        self._batch(pointers, tostore, 'download')

    def _batchrequest(self, pointers, action):
        """Get metadata about objects pointed by pointers for given action

        Return decoded JSON object like {'objects': [{'oid': '', 'size': 1}]}
        See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
        """
        objects = [{'oid': p.oid(), 'size': p.size()} for p in pointers]
        requestdata = json.dumps({
            'objects': objects,
            'operation': action,
        })
        batchreq = util.urlreq.request('%s/objects/batch' % self.baseurl,
                                       data=requestdata)
        batchreq.add_header('Accept', 'application/vnd.git-lfs+json')
        batchreq.add_header('Content-Type', 'application/vnd.git-lfs+json')
        try:
            rawjson = self.urlopener.open(batchreq).read()
        except util.urlerr.httperror as ex:
            raise LfsRemoteError(_('LFS HTTP error: %s (action=%s)')
                                 % (ex, action))
        try:
            response = json.loads(rawjson)
        except ValueError:
            raise LfsRemoteError(_('LFS server returns invalid JSON: %s')
                                 % rawjson)
        return response

    def _checkforservererror(self, pointers, responses, action):
        """Scans errors from objects

        Raises LfsRemoteError if any objects have an error"""
        for response in responses:
            # The server should return 404 when objects cannot be found. Some
            # server implementation (ex. lfs-test-server)  does not set "error"
            # but just removes "download" from "actions". Treat that case
            # as the same as 404 error.
            notfound = (response.get('error', {}).get('code') == 404
                        or (action == 'download'
                            and action not in response.get('actions', [])))
            if notfound:
                ptrmap = {p.oid(): p for p in pointers}
                p = ptrmap.get(response['oid'], None)
                if p:
                    filename = getattr(p, 'filename', 'unknown')
                    raise LfsRemoteError(
                        _(('LFS server error. Remote object '
                          'for "%s" not found: %r')) % (filename, response))
                else:
                    raise LfsRemoteError(
                        _('LFS server error. Unsolicited response for oid %s')
                        % response['oid'])
            if 'error' in response:
                raise LfsRemoteError(_('LFS server error: %r') % response)

    def _extractobjects(self, response, pointers, action):
        """extract objects from response of the batch API

        response: parsed JSON object returned by batch API
        return response['objects'] filtered by action
        raise if any object has an error
        """
        # Scan errors from objects - fail early
        objects = response.get('objects', [])
        self._checkforservererror(pointers, objects, action)

        # Filter objects with given action. Practically, this skips uploading
        # objects which exist in the server.
        filteredobjects = [o for o in objects if action in o.get('actions', [])]

        return filteredobjects

    def _basictransfer(self, obj, action, localstore):
        """Download or upload a single object using basic transfer protocol

        obj: dict, an object description returned by batch API
        action: string, one of ['upload', 'download']
        localstore: blobstore.local

        See https://github.com/git-lfs/git-lfs/blob/master/docs/api/\
        basic-transfers.md
        """
        oid = str(obj['oid'])

        href = str(obj['actions'][action].get('href'))
        headers = obj['actions'][action].get('header', {}).items()

        request = util.urlreq.request(href)
        if action == 'upload':
            # If uploading blobs, read data from local blobstore.
            with localstore.open(oid) as fp:
                _verifyfile(oid, fp)
            request.data = filewithprogress(localstore.open(oid), None)
            request.get_method = lambda: 'PUT'

        for k, v in headers:
            request.add_header(k, v)

        response = b''
        try:
            req = self.urlopener.open(request)
            if action == 'download':
                # If downloading blobs, store downloaded data to local blobstore
                localstore.download(oid, req)
            else:
                while True:
                    data = req.read(1048576)
                    if not data:
                        break
                    response += data
                if response:
                    self.ui.debug('lfs %s response: %s' % (action, response))
        except util.urlerr.httperror as ex:
            if self.ui.debugflag:
                self.ui.debug('%s: %s\n' % (oid, ex.read()))
            raise LfsRemoteError(_('HTTP error: %s (oid=%s, action=%s)')
                                 % (ex, oid, action))

    def _batch(self, pointers, localstore, action):
        if action not in ['upload', 'download']:
            raise error.ProgrammingError('invalid Git-LFS action: %s' % action)

        response = self._batchrequest(pointers, action)
        objects = self._extractobjects(response, pointers, action)
        total = sum(x.get('size', 0) for x in objects)
        sizes = {}
        for obj in objects:
            sizes[obj.get('oid')] = obj.get('size', 0)
        topic = {'upload': _('lfs uploading'),
                 'download': _('lfs downloading')}[action]
        if len(objects) > 1:
            self.ui.note(_('lfs: need to transfer %d objects (%s)\n')
                         % (len(objects), util.bytecount(total)))
        self.ui.progress(topic, 0, total=total)
        def transfer(chunk):
            for obj in chunk:
                objsize = obj.get('size', 0)
                if self.ui.verbose:
                    if action == 'download':
                        msg = _('lfs: downloading %s (%s)\n')
                    elif action == 'upload':
                        msg = _('lfs: uploading %s (%s)\n')
                    self.ui.note(msg % (obj.get('oid'),
                                 util.bytecount(objsize)))
                retry = self.retry
                while True:
                    try:
                        self._basictransfer(obj, action, localstore)
                        yield 1, obj.get('oid')
                        break
                    except socket.error as ex:
                        if retry > 0:
                            self.ui.note(
                                _('lfs: failed: %r (remaining retry %d)\n')
                                % (ex, retry))
                            retry -= 1
                            continue
                        raise

        # Until https multiplexing gets sorted out
        if self.ui.configbool('experimental', 'lfs.worker-enable'):
            oids = worker.worker(self.ui, 0.1, transfer, (),
                                 sorted(objects, key=lambda o: o.get('oid')))
        else:
            oids = transfer(sorted(objects, key=lambda o: o.get('oid')))

        processed = 0
        for _one, oid in oids:
            processed += sizes[oid]
            self.ui.progress(topic, processed, total=total)
            self.ui.note(_('lfs: processed: %s\n') % oid)
        self.ui.progress(topic, pos=None, total=total)

    def __del__(self):
        # copied from mercurial/httppeer.py
        urlopener = getattr(self, 'urlopener', None)
        if urlopener:
            for h in urlopener.handlers:
                h.close()
                getattr(h, "close_all", lambda : None)()

class _dummyremote(object):
    """Dummy store storing blobs to temp directory."""

    def __init__(self, repo, url):
        fullpath = repo.vfs.join('lfs', url.path)
        self.vfs = lfsvfs(fullpath)

    def writebatch(self, pointers, fromstore):
        for p in pointers:
            content = fromstore.read(p.oid(), verify=True)
            with self.vfs(p.oid(), 'wb', atomictemp=True) as fp:
                fp.write(content)

    def readbatch(self, pointers, tostore):
        for p in pointers:
            with self.vfs(p.oid(), 'rb') as fp:
                tostore.download(p.oid(), fp)

class _nullremote(object):
    """Null store storing blobs to /dev/null."""

    def __init__(self, repo, url):
        pass

    def writebatch(self, pointers, fromstore):
        pass

    def readbatch(self, pointers, tostore):
        pass

class _promptremote(object):
    """Prompt user to set lfs.url when accessed."""

    def __init__(self, repo, url):
        pass

    def writebatch(self, pointers, fromstore, ui=None):
        self._prompt()

    def readbatch(self, pointers, tostore, ui=None):
        self._prompt()

    def _prompt(self):
        raise error.Abort(_('lfs.url needs to be configured'))

_storemap = {
    'https': _gitlfsremote,
    'http': _gitlfsremote,
    'file': _dummyremote,
    'null': _nullremote,
    None: _promptremote,
}

def _verify(oid, content):
    realoid = hashlib.sha256(content).hexdigest()
    if realoid != oid:
        raise error.Abort(_('detected corrupt lfs object: %s') % oid,
                          hint=_('run hg verify'))

def _verifyfile(oid, fp):
    sha256 = hashlib.sha256()
    while True:
        data = fp.read(1024 * 1024)
        if not data:
            break
        sha256.update(data)
    realoid = sha256.hexdigest()
    if realoid != oid:
        raise error.Abort(_('detected corrupt lfs object: %s') % oid,
                          hint=_('run hg verify'))

def remote(repo):
    """remotestore factory. return a store in _storemap depending on config"""
    url = util.url(repo.ui.config('lfs', 'url') or '')
    scheme = url.scheme
    if scheme not in _storemap:
        raise error.Abort(_('lfs: unknown url scheme: %s') % scheme)
    return _storemap[scheme](repo, url)

class LfsRemoteError(error.RevlogError):
    pass


chemin = "C:/python/prenom.txt"
chemin_clean = "C:/python/prenom_clean_correction.txt"

with open(chemin, "r") as f:
    lines = f.read().splitlines()

prenoms = []
for line in lines:
    prenoms.extend(line.split())

prenoms_final = [prenom.strip(",. ") for prenom in prenoms]

with open(chemin_clean, "w") as f:
    f.write("\n".join(sorted(prenoms_final)))


import pandas as pd
import glob
import numpy as np
import os

col_names = ['date','shop','item', 'unit', 'value']

month ='02'

files = []
list_of_files = glob.glob(r'\\lhrnetapp03cifs.enterprisenet.org\rfeprodapp05\InputBackupFiles\CH\Import_M\Monthly-2019-M'
                          r'M-0{month}\*'.format(month=month))

latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
# latest_files.append(latest_file)
for file in glob.glob(latest_file+r'\IMPO_RA32*'.format(month=month)):
    print(file)

    df = pd.read_csv(file, header=None, sep=';')
    # print(df.info())
    files.append(df)

if len(files) >1:
    full = pd.concat(files)
    dates = full.date.unique()
else:
    full = files[0]

# quit()

full[11] = full[11].apply(lambda x: pd.to_numeric(x, errors='coerce'))
full[10] = full[10].astype(float)
# Q=0 OR (Q<0 AND V>0) OR (Q>0 AND V<0)
print(full.info())
full=full[full[10] != 0]
full=full[~((full[10] > 0)&(full[11] < 0))]
full=full[~((full[10] <0)&(full[11] > 0))]
# ujemne=full[~((full.unit >0)&(full.value > 0))]
# full = full.groupby(['date','shop','item']).aggregate({'unit':np.sum, 'value':np.sum})
full=full[full[10] >0]

print(full[11].sum())


import networkx as nx, matplotlib.pyplot as plt, numpy as np, copy
import MarkovChain as SMC
from Randomized import *
from time import time

Pps = 0.4  # float(input('Ingrese la probabilidad de que un dispositivo protegido pase a ser susceptible: '))
Psp = 0.3  # float(input('Ingrese la probabilidad de que un dispositivo susceptible pase a ser protegido: '))
Psc = 0.5  # float(input('Ingrese la probabilidad de que un dispositivo susceptible pase a ser comprometido: '))
Pcp = 0.2  # float(input('Ingrese la probabilidad de que un dispositivo comprometido pase a ser protegido: '))
Pci = 0.1  # float(input('Ingrese la probabilidad de que un dispositivo comprometido pase a ser irrecuperable: '))

prec = 5 # int(input('Ingrese el número de decimales a manejar: '))
t_lim = 100 # int(input('Ingrese el número máximo de momentos a estudiar: '))
base_MT = [[1 - Pps, Pps, 0, 0], [Psp, 1 - Psp - Psc, Psc, 0], [Pcp, 0, 1 - Pcp - Pci, Pci], [0, 0, 0, 1]]
NetGraph, NetDevices, states = None, {}, ['Protegido', 'Susceptible', 'Comprometido', 'Irrecuperable']
HeatMap, gen_distr, N = [], [], 0

def setNonDefaults(Probs):
    (Pps, Psp, Psc, Pcp, Pci) = Probs
    base_MT = [[1 - Pps, Pps, 0, 0], [Psp, 1 - Psp - Psc, Psc, 0], [Pcp, 0, 1 - Pcp - Pci, Pci], [0, 0, 0, 1]]
    return Psp, Psc, base_MT

def createNode(i, fs, nset, MT, adjust):
    vi = [0, 0, 0, 0]
    vi[states.index(fs)] = 1
    if adjust:
        NetDevices[i]['factual_state'] = fs
        NetDevices[i]['init_vector'] = np.array(vi)
        NetDevices[i]['trans_matrix'] = copy.deepcopy(np.array(MT))
        for n in nset:
            if (n not in NetDevices) or (i not in NetDevices[n]['neighbors']) and (len(NetDevices[n]['neighbors']) < 4):
                NetDevices[i]['neighbors'].append(n)
                NetDevices[n]['neighbors'].append(i)
    else:
        NetDevices[i] = {
            'factual_state': fs,
            'init_vector': np.array(vi),
            'trans_matrix': copy.deepcopy(np.array(MT)),
            'neighbors': nset }

def setNeighborFactor(u, NetDevices, Psp, Psc):
    nset, count = NetDevices[u]['neighbors'], 0
    if len(nset) == 0:
        NetDevices[u]['trans_matrix'][1][1] = 1 - Psp - Psc
        NetDevices[u]['trans_matrix'][1][2] = Psc
    else:
        for n in nset:
            if NetDevices[n]['factual_state'] in states[2:]: count += 1
        factor = (Psc + (count / len(nset))) / 2
        NetDevices[u]['trans_matrix'][1][1] = np.round_(1 - Psp - factor, prec)
        NetDevices[u]['trans_matrix'][1][2] = np.round_(factor, prec)

def setFactualState(j, NetDevices):
    ref = states.index(NetDevices[j]['factual_state'])
    comp = np.argmax(NetDevices[j]['init_vector'])
    if NetDevices[j]['trans_matrix'][ref][comp] == 0:
        if ref == 3: comp = ref
        elif ref == 2 and comp == 1:
            if NetDevices[j]['init_vector'][0] == 0: comp = 3
            else: comp = 0
        elif NetDevices[j]['init_vector'][ref + 1] == 0: comp = 0
        else: comp = ref + 1
    return states[comp]

def manualBuildNetwork(N, MT):
    base_MT = MT; edges = []
    nodes = [(x+1) for x in range(N)]
    for y in nodes:
        fs = ''
        while fs not in states:
            fs = input('Ingrese el estado del nodo '+str(y)+' (Protegido, Susceptible, Comprometido o Irrecuperable): ')
        n_chain = input('Ingrese los vecinos del nodo ' + str(y) + ' separados por comas: ').split(',')
        neighbors = [int(n) for n in n_chain]
        createNode(y, fs, neighbors, base_MT, False)
        for n in neighbors: edges.append([y, n])
    return graphNetwork(nodes, edges)

def UIBuildNetwork(Nstates, Nedges, MT):
    nodes, edges = [(x+1) for x in range(len(Nedges))], []
    for y in nodes:
        fs = Nstates[y-1]
        n_chain = Nedges[y-1].split(',')
        neighbors = [int(n) for n in n_chain]
        createNode(y, fs, neighbors, MT, False)
        for n in neighbors: edges.append([y, n])
    return nodes, edges, NetDevices

def autoBuildNetwork(N, topology, MT):
    base_MT = MT; edges, adjust = [], False
    nodes = [(x+1) for x in range(N)]
    for y in nodes:
        fs, neighbors = randomFactualState(states), []
        if y == 1:
            for x in range(N):
                NetDevices[x + 1] = {'factual_state': '', 'init_vector': [], 'trans_matrix': [], 'neighbors': []}
        if topology == 'Lineal':
            if y < N: neighbors.append(y + 1)
            if y > 1: neighbors.append(y - 1)
        elif topology == 'Anillo':
            if y < N: neighbors.append(y + 1)
            if y > 1: neighbors.append(y - 1)
            if y in (1, N): neighbors.append(N - y + 1)
        elif topology == 'Estrella':
            if y == 1: neighbors = range(2, N + 1)
            else: neighbors = [1]
        elif topology == 'Cuadricula':
            if y < N: neighbors.append(y + 1)
            if y > 1: neighbors.append(y - 1)
            if y % 2 == 0 and y in range(3, 10): neighbors.append(1)
            if y in (2, 9) and N >= 9: neighbors.append(11 - y)
            if y == 1: neighbors.extend(range(4, np.min([N+1, 8]), 2))
        elif topology == 'Malla':
            prev = len(NetDevices[y]['neighbors'])
            limnodes = np.min([N, 5-prev])
            if limnodes > 1:
                tries, checks, adjust = np.random.randint(1, limnodes), 0, True
                while checks < tries:
                    randneighbor = np.random.randint(1, N+1)
                    if y != randneighbor and randneighbor not in neighbors:
                        neighbors.append(randneighbor)
                        checks += 1
        createNode(y, fs, neighbors, MT, adjust)
        for n in neighbors: edges.append([y, n])
    #graphNetwork(nodes, edges)
    return NetDevices

def graphNetwork(nodes, edges):
    NetGraph = nx.Graph()
    NetGraph.add_nodes_from(nodes)
    nx.set_node_attributes(NetGraph, NetDevices)
    NetGraph.add_edges_from(edges)
    MC = plt.figure(figsize=(8, 6))
    pos = nx.kamada_kawai_layout(NetGraph)
    nx.draw_networkx_nodes(NetGraph, pos, cmap=plt.get_cmap('jet'), node_size=1250, node_color='cyan')
    nx.draw_networkx_labels(NetGraph, pos)
    nx.draw_networkx_edges(NetGraph, pos)
    plt.show()
    return MC

def scanDistribution(N, NetDevices):
    sums = np.array([0, 0, 0, 0])
    for z in range(N): sums[states.index(NetDevices[z + 1]['factual_state'])] += 1
    sums = sums / N
    return sums

def spotNodeStates(N, NetDevices):
    nodestates = np.array([0]*N)
    for z in range(N): nodestates[z] = states.index(NetDevices[z + 1]['factual_state'])
    return nodestates

def performStepAllNodes(N, NetDevices, Psp, Psc):
    report, statereg = '', ''
    #print('Distribution: ' + str(scanDistribution(N)))
    for a in range(1, N + 1):
        #report += str(NetDevices[a]['init_vector']) + ' '
        #statereg += str(NetDevices[a]['factual_state']) + ' '
        setNeighborFactor(a, NetDevices, Psp, Psc)
        #print(NetDevices[a]['init_vector'], NetDevices[a]['trans_matrix'])
        step = np.matmul(NetDevices[a]['init_vector'], NetDevices[a]['trans_matrix'])
        NetDevices[a]['init_vector'] = np.around(step, prec)
        NetDevices[a]['factual_state'] = setFactualState(a, NetDevices)
    #print(report + '\n', statereg)
    return scanDistribution(N, NetDevices)

def paintProgressMC(progress):
    BP = plt.figure()
    plt.xlabel('Time (t)')
    plt.ylabel('Probability (P)')
    for p in progress: plt.plot(p)
    plt.legend(states)
    plt.show()
    return BP

def getPlots(progress, temps, comparetemps, context):
    plt.plot(progress)
    plt.title('Pps = {0}, Psp = {1}, Psc = {2}, Pcp = {3}, Pci = {4} \nInitialization Vector = {5}'
              .format(Pps, Psp, Psc, Pcp, Pci, context))
    plt.legend(states)
    plt.xlabel('Time (t)')
    plt.ylabel('Probability (P)')
    plt.show()
    difftemps = list(map(list, zip(temps, comparetemps)))
    plt.plot(difftemps)
    plt.title('Comparación de tiempos de ejecución conforme avanza el algoritmo')
    plt.legend(['Múltiple', 'Simple'])
    plt.xlabel('Moment (t)')
    plt.ylabel('Execution Time (ms)')
    plt.show()

def retrieveHeatMap(infection, nodes, moments):
    HMNS = plt.figure()
    plt.xlabel('Time (t)')
    plt.ylabel('Nodes')
    plt.imshow(infection, cmap='hot_r', aspect='auto', extent=[1, nodes, moments, 0])
    plt.show()
    infection = []
    return HMNS

def start():
    N = int(input('Ingrese el número de nodos de la red: '))
    NetGraph = manualBuildNetwork(N, base_MT)
    input('Press Enter to continue...')
    num_nodes = len(NetGraph.nodes)
    context = scanDistribution(num_nodes)
    progress, temps, c, executime = [context], [0], 0, 0
    while c < t_lim:
        start_time = time()
        progress.append(performStepAllNodes(num_nodes, NetDevices, Psp, Psc))
        total_time = time() - start_time
        executime += (total_time*1000); c += 1
        temps.append(executime)
    comparetemps = SMC.start(N)
    getPlots(progress, temps, comparetemps, context)
    #paintProgressMC()
    retrieveHeatMap(HeatMap, len(HeatMap), len(HeatMap[0]))
    #means = getMeanTime(matriz_transicion, vector_inverso)
    #for m in range(len(means)): print('Tiempo medio desde el estado', Estados[m]+': ', means[m])

if __name__ == '__main__': start()


# pylint: disable=too-many-locals, duplicate-code
"""Management command that loads locale .po files into database."""

from __future__ import unicode_literals
import json
from os.path import join, isdir
from django.conf import settings

from django.core.management.base import BaseCommand as LoadCommand, CommandError
from django.apps import apps
from babel.messages.pofile import read_po

def setattr_by_json_path(json_object, path, value):
    """Recursive function that sets a string value given a JSON xpath."""
    first_id = path.find("#")
    second_id = path.find("#", first_id + 1)
    first_key = path.find("/")
    second_key = path.find("/", first_key + 1)
    indices = [x for x in [first_id, second_id, first_key, second_key] if x > 0]
    indices.sort()
    indices.append(len(path) + 1)

    if path[0] == "#" and isinstance(json_object, list):
        child_id = path[1:indices[0]]
        path_remainder = path[indices[0]:]
        for sub_object in json_object:
            try:
                if sub_object["id"] == child_id:
                    setattr_by_json_path(sub_object, path_remainder, value)
            except KeyError:
                pass
    elif path[0] == "/" and isinstance(json_object, dict):
        child_key = path[1:indices[0]]
        path_remainder = path[indices[0]:]
        try:
            sub_object = json_object[child_key]
            if isinstance(sub_object, str):
                json_object[child_key] = value
            else:
                setattr_by_json_path(sub_object, path_remainder, value)
        except KeyError:
            pass
    return json_object

class Command(LoadCommand):
    """Management command that loads locale .po files into database."""

    def handle(self, *args, **options):
        """Handle the load_trans command."""
        po_filename = "nav.po"
        locale_path = settings.MODELTRANSLATION_LOCALE_PATH
        if not isdir(locale_path):
            raise CommandError("Locale directory does not exists.")
        for lang in [lang_tup[0] for lang_tup in list(settings.LANGUAGES)]:
            if lang != "en":
                lang_path = join(locale_path, lang)
                if not isdir(lang_path):
                    raise CommandError("Language directory does not exists.")
                po_file = open(join(lang_path, "LC_MESSAGES", po_filename), "r", encoding="utf-8")
                catalog = read_po(po_file)
                po_file.close()
                for message in catalog:
                    if message.string not in [None, "None", ""] and message.auto_comments:
                        for field_id in message.auto_comments:
                            [app, class_name, primary_key, field, json_path] = field_id.split('.')
                            model = apps.get_model(app, class_name)
                            try:
                                obj = model.objects.get(pk=primary_key)
                            except model.DoesNotExist:
                                continue
                            if json_path == "":
                                setattr(obj, field, message.string)
                                obj.save()
                            else:
                                msg_data = getattr(obj, field).raw_data
                                tr_json_path = "%s_%s" % (json_path[:-3], lang)
                                msg_data = setattr_by_json_path(msg_data, tr_json_path, message.string)
                                setattr(obj, field, json.dumps(msg_data))
                                obj.save()


def factorial(n: int) -> int:
    """Return the factorial of n, an exact integer >= 0.

    Args:
       n (int):  n!

    Returns:
       int.  The factorial value::

    >>> factorial(5)
    120
    >>> factorial(0)
    1
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: Only non-negative inputs are expected
    """
    assert isinstance(n, int)

    if n < 0:
        raise ValueError("Only non-negative inputs are expected")

    if n == 0:
        return 1
    return n * factorial(n - 1)

# --------------------------------------------------------------------

if __name__ == "__main__":
    import doctest

    doctest.testmod()


number=5
if type(number) == int:
    print("resultado: ",number*2)
else:
    print("El dato no es numerico")

def mensaje (men):
    print(men)

mensaje("Mi primer Programa")
mensaje("Miu segundo Programa")


import os

import telebot
from dotenv import load_dotenv

import client

load_dotenv()

bot_token = os.getenv('BOT_TOKEN')
admin = os.getenv('TG_ADMIN_ID')

bot = telebot.TeleBot(bot_token)

states_list = ["ADDRESS", "AMOUNT", "CONFIRM"]
states_of_users = {}

@bot.message_handler(commands=['start'])
def start_message(message):
    """
    markup: создаем объект для работы с кнопками (row_width - определяет количество кнопок по ширине)
    создаем три кнопки, типа:KeyboardButton
    отправляем пользователю три кнопки типа:KeyboardButton
    после команды /start.
    """

    try:
        client.create_user({"tg_ID": message.from_user.id,
                           "nick": message.from_user.username})

    except Exception as e:
        return e

    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=3,
        resize_keyboard=True
    )

    btn1 = telebot.types.KeyboardButton('Кошелек')
    btn2 = telebot.types.KeyboardButton('Перевести')
    btn3 = telebot.types.KeyboardButton('История')
    btn4 = telebot.types.KeyboardButton('Админ')

    markup.add(btn1, btn2, btn3, btn4)

    text: str = f'Привет {message.from_user.full_name}, я твой бот-криптокошелек, \n' \
                'у меня ты можешь хранить и отправлять биткоины'

    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(regexp='Кошелек')
def wallet(message):
    wallet = client.get_user_wallet_by_tg_id(message.from_user.id)
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2, resize_keyboard=True)
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)

    text = (f'Ваш баланс: {wallet["balance"]} BTC \n'
            f'Ваш адрес: {wallet["address"]}')
    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(regexp='История транзакций')
def history(message):
    transactions = client.get_user_transactions(
        client.get_user_by_tg_id(message.from_user.id)["id"])

    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)

    text = f'Ваши транзакции: \n{transactions}'
    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(regexp='Перевести')
def transaction(message):
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)
    text = f'Введите адрес кошелька куда хотите перевести: '
    bot.send_message(message.chat.id, text, reply_markup=markup)
    # тут мы даём юзеру состояние при котором ему будет возвращаться следующее
    # сообщение
    states_of_users[message.from_user.id] = {"STATE": "ADDRESS"}

@bot.message_handler(regexp='История')
def history(message):
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)
    transactions = ['1', '2', '3']  # сюда мы загрузим транзакции
    text = f'Ваши транзакции{transactions}'
    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(regexp='Меню')
def menu(message):
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Кошелек')
    btn2 = telebot.types.KeyboardButton('Перевести')
    btn3 = telebot.types.KeyboardButton('История')

    markup.add(btn1, btn2, btn3)

    text = f'Главное меню'
    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(func=lambda message: message.from_user.id ==
                     admin and message.text == 'Админ')
def admin_panel(message):
    if message.from_user.id != admin:
        markup = telebot.types.ReplyKeyboardMarkup(
            row_width=2,
            resize_keyboard=True
        )
        btn1 = telebot.types.KeyboardButton('Меню')
        markup.add(btn1)
        bot.send_message(
            message.chat.id,
            'У вас нет прав администратора.',
            reply_markup=markup)
    else:
        markup = telebot.types.ReplyKeyboardMarkup(
            row_width=2, resize_keyboard=True)
        btn1 = telebot.types.KeyboardButton('Общий баланс')
        btn2 = telebot.types.KeyboardButton('Все юзеры')
        btn3 = telebot.types.KeyboardButton('Данные по юзеру')
        btn4 = telebot.types.KeyboardButton('Удалить юзера')
        markup.add(btn1, btn2, btn3, btn4)

        text = f'Админ-панель'
        bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(func=lambda message: message.from_user.id ==
                     admin and message.text == "Все юзеры")
def show_all_users(message):
    text = f'Юзеры:'
    users = client.get_users()

    inline_markup = telebot.types.InlineKeyboardMarkup()
    for user in users:
        inline_markup.add(telebot.types.InlineKeyboardButton(
            text=f'Юзер: {user["tg_ID"]}',
            callback_data=f'user_{user["tg_ID"]}'
        ))
    bot.send_message(message.chat.id, text, reply_markup=inline_markup)

@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
    query_type = call.data.split('_')[0]
    users = client.get_users()

    if query_type == 'user':
        user_id = call.data.split('_')[1]
        inline_markup = telebot.types.InlineKeyboardMarkup()
        for user in users:
            if str(user['tg_ID']) == user_id:
                inline_markup.add(
                    telebot.types.InlineKeyboardButton(
                        text="Назад",
                        callback_data='users'),
                    telebot.types.InlineKeyboardButton(
                        text="Удалить юзера",
                        callback_data=f'delete_user_{user_id}'))

                bot.edit_message_text(
                    text=f'Данные по юзеру:\n'
                    f'ID: {user["tg_ID"]}\n'
                    f'Ник: {user.get("nick")}\n'
                    f'Баланс: {client.get_user_balance_by_id(user["id"])}',
                    chat_id=call.message.chat.id,
                    message_id=call.message.message_id,
                    reply_markup=inline_markup)
                print(f"Запрошен {user}")
                break

    if query_type == 'users':
        inline_markup = telebot.types.InlineKeyboardMarkup()
        for user in users:
            inline_markup.add(
                telebot.types.InlineKeyboardButton(
                    text=f'Юзер: {user["tg_ID"]}',
                    callback_data=f"user_{user['tg_ID']}"))
        bot.edit_message_text(
            text="Юзеры:",
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            reply_markup=inline_markup)  # прикрепляем нашу разметку к ответному сообщению

    if query_type == 'delete' and call.data.split('_')[1] == 'user':

        user_id = int(call.data.split('_')[2])
        for i, user in enumerate(users):
            if user['tg_ID'] == user_id:
                print(f'Удален Юзер: {users[i]}')
                client.delete_user(users.pop(i)['id'])
        inline_markup = telebot.types.InlineKeyboardMarkup()
        for user in users:
            inline_markup.add(
                telebot.types.InlineKeyboardButton(
                    text=f'Юзер: {user["tg_ID"]}',
                    callback_data=f"user_{user['tg_ID']}"))
        bot.edit_message_text(
            text="Юзеры:",
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            reply_markup=inline_markup
        )

@bot.message_handler(func=lambda message: message.from_user.id ==
                     admin and message.text == "Общий баланс")
def total_balance(message):
    total_bal = client.get_total_balance()
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Меню')
    btn2 = telebot.types.KeyboardButton('Админка')
    markup.add(btn1, btn2)

    text = f'Общий баланс: {total_bal} BTC'
    bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(
    func=lambda message: states_of_users.get(
        message.from_user.id)["STATE"] == 'AMOUNT')
def get_confirmation_of_transaction(message):
    if message.text == "Меню":
        del states_of_users[message.from_user.id]
        menu(message)
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2,
        resize_keyboard=True
    )
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)
    if message.text.isdigit():
        text = f'Вы хотите перевести {message.text} сатоши,\n' \
               f'на биткоин-адрес {states_of_users[message.from_user.id]["ADDRESS"]}: '
        confirm = telebot.types.KeyboardButton('Подтверждаю')
        markup.add(confirm)
        bot.send_message(message.chat.id, text, reply_markup=markup)
        # тут мы даём юзеру состояние при котором ему будет возвращаться
        # следующее сообщение
        states_of_users[message.from_user.id]["STATE"] = "CONFIRM"
        states_of_users[message.from_user.id]["AMOUNT"] = int(message.text)
    else:
        text = f'Вы ввели не число, попробуйте заново: '
        bot.send_message(message.chat.id, text, reply_markup=markup)

@bot.message_handler(
    func=lambda message: states_of_users.get(
        message.from_user.id)["STATE"] == 'CONFIRM')
def get_hash_of_transaction(message):
    if message.text == "Меню":
        del states_of_users[message.from_user.id]
        menu(message)
    elif message.text == "Подтверждаю":
        bot.send_message(
            message.chat.id,
            f" Ваша транзакция: " + str(client.create_transaction(message.from_user.id,
                                                                  states_of_users[message.from_user.id]['ADDRESS'],
                                                                  states_of_users[message.from_user.id]['AMOUNT']))
        )
        del states_of_users[message.from_user.id]
        menu(message)

@bot.message_handler(
    func=lambda message: states_of_users.get(
        message.from_user.id)["STATE"] == 'ADDRESS')
def get_amount_of_transaction(message):
    if message.text == "Меню":
        del states_of_users[message.from_user.id]
        menu(message)
    markup = telebot.types.ReplyKeyboardMarkup(
        row_width=2, resize_keyboard=True)
    btn1 = telebot.types.KeyboardButton('Меню')
    markup.add(btn1)
    text = f'Введите сумму в сатоши, которую хотите перевести: '
    bot.send_message(message.chat.id, text, reply_markup=markup)
    # тут мы даём юзеру состояние при котором ему будет возвращаться следующее
    # сообщение
    states_of_users[message.from_user.id]["STATE"] = "AMOUNT"
    states_of_users[message.from_user.id]["ADDRESS"] = message.text

bot.infinity_polling(timeout=10)


from datetime import datetime
from typing import Optional

from dcs.mission import Mission

from game.weather.atmosphericconditions import AtmosphericConditions
from game.weather.clouds import Clouds
from game.weather.conditions import Conditions
from game.weather.fog import Fog
from game.weather.wind import WindConditions

class EnvironmentGenerator:
    def __init__(
        self, mission: Mission, conditions: Conditions, time: datetime
    ) -> None:
        self.mission = mission
        self.conditions = conditions
        self.time = time

    def set_atmospheric(self, atmospheric: AtmosphericConditions) -> None:
        self.mission.weather.qnh = atmospheric.qnh.mm_hg
        self.mission.weather.season_temperature = atmospheric.temperature_celsius
        self.mission.weather.turbulence_at_ground = int(atmospheric.turbulence_per_10cm)

    def set_clouds(self, clouds: Optional[Clouds]) -> None:
        if clouds is None:
            return
        self.mission.weather.clouds_base = clouds.base
        self.mission.weather.clouds_thickness = clouds.thickness
        self.mission.weather.clouds_density = clouds.density
        self.mission.weather.clouds_iprecptns = clouds.precipitation
        self.mission.weather.clouds_preset = clouds.preset

    def set_fog(self, fog: Optional[Fog]) -> None:
        if fog is None:
            return
        self.mission.weather.fog_visibility = int(fog.visibility.meters)
        self.mission.weather.fog_thickness = fog.thickness

    def set_wind(self, wind: WindConditions) -> None:
        self.mission.weather.wind_at_ground = wind.at_0m
        self.mission.weather.wind_at_2000 = wind.at_2000m
        self.mission.weather.wind_at_8000 = wind.at_8000m

    def generate(self) -> None:
        self.mission.start_time = self.time
        self.set_atmospheric(self.conditions.weather.atmospheric)
        self.set_clouds(self.conditions.weather.clouds)
        self.set_fog(self.conditions.weather.fog)
        self.set_wind(self.conditions.weather.wind)


#!/usr/bin/env python3

"""SERVICE YET TO BE IMPLEMENTED. THIS FILE IS JUST A PLACEHOLDER."""

print("Sorry! This service has not yet been implemented\n(will you be the one to take care of it?\n --- RIGHT NOW THIS FILE IS JUST AN HANDY PLACEHOLDER ---")

exit(0)

#!/usr/bin/env python3
from sys import stderr, stdout, exit, argv
from random import randrange
from time import monotonic

from multilanguage import Env, Lang, TALcolors
from TALinputs import TALinput

# METADATA OF THIS TAL_SERVICE:
problem="problem_name"
service="service_name"
args_list = [
    ('arg1',int),
    ('arg2',str),
    ('arg3',bool),
    ('lang',str),
    ('META_TTY',bool),
]

ENV =Env(problem, service, args_list)
TAc =TALcolors(ENV)
LANG=Lang(ENV, TAc, lambda fstring: eval(f"f'{fstring}'"))
TAc.print(LANG.opening_msg, "green")

# START CODING YOUR SERVICE:

gen_new_s = True
for _ in range(ENV['num_questions']):
  pass


import os
import pathlib

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imsave, imread

def add_noise(noise_type, image):
    if noise_type == "gauss":
        shp = image.shape
        mean = 0
        var = 0.01
        sigma = var ** 0.5
        gauss = np.random.normal(mean, sigma, shp)
        noise = image + gauss
        return noise

    if noise_type == "uniform":
        k = 0.5

        if image.ndim == 2:
            row, col = image.shape
            noise = np.random.rand(row, col)
        else:
            row, col, chan = image.shape
            noise = np.random.rand(row, col, chan)

        noise = image + k * (noise - 0.5)

        return noise

    if noise_type == "s&p":
        sh = image.shape
        s_vs_p = 0.5
        amount = 0.05
        out = np.copy(image)
        num_salt = np.ceil(amount * image.size * s_vs_p)
        coords = [np.random.randint(0, i - 1, int(num_salt)) for i in sh]
        out[coords] = 1

        num_peper = np.ceil(amount * image.size * (1.0 - s_vs_p))
        coords = [np.random.randint(0, i - 1, int(num_peper)) for i in sh]
        out[coords] = 0
        return out

    if noise_type == "poisson":
        PEAK = 20
        noisy = image + np.random.poisson(0.5 * PEAK, image.shape) / PEAK
        return noisy

    if noise_type == "speckle":
        if image.ndim == 2:
            row, col = image.shape
            noise = np.random.randn(row, col)
        else:
            row, col, chan = image.shape
            noise = np.random.randn(row, col, chan)

        noisy = image + image * 0.5 * noise
        return noisy

def read_images_1(img_path):

    row, column = 3, 2
    # Original picture
    fig = plt.figure(img_path)
    plt.axis("off")
    img = imread(img_path)

    fig.add_subplot(row, column, 1, title="Original")
    plt.imshow(img, cmap="gray")
    plt.axis("off")

    fig.add_subplot(row, column, 2, title="Gauss")
    plt.imshow(add_noise("gauss", img), cmap="gray")
    plt.axis("off")

    fig.add_subplot(row, column, 3, title="Uniform")
    plt.imshow(add_noise("uniform", img), cmap="gray")
    plt.axis("off")

    fig.add_subplot(row, column, 4, title="s&p")
    plt.imshow(add_noise("s&p", img), cmap="gray")
    plt.axis("off")

    fig.add_subplot(row, column, 5, title="Poisson")
    plt.imshow(add_noise("poisson", img), cmap="gray")
    plt.axis("off")

    fig.add_subplot(row, column, 6, title="Speckle")
    plt.imshow(add_noise("speckle", img), cmap="gray")
    plt.axis("off")

    plt.show(block=True)

if __name__ == "__main__":
    img_path = os.path.join(pathlib.Path(__file__).parent.parent, "input1", "coins.png")
    read_images_1(img_path)


from random import randint as rand
import pygame
import time

row_max =16
column_max =16
mine_count = 50

square_list = []
square_size = 30
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (0,0,255)
RED = (255,0,0)
pygame.init()
stage = "setup"
check_list = []

screen = pygame.display.set_mode((square_size*column_max, square_size*row_max))
pygame.display.set_caption("Minesweeper")

class square:
    def __init__(self, row, column):
        self.row = row
        self.column = column
        self.mine = False
        self.hidden = True
        self.flag = False
        self.mark_mine = False
        self.mark_safe = False

    def adjacents(self, choice):
        adjacent_list = []
        empty_list = []
        for row_difference in range(-1,2):
            new_row = self.row + row_difference
            for column_difference in range(-1,2):
                new_column = self.column + column_difference
                if (0 <= new_column < column_max) and (0 <= new_row < row_max) and not (column_difference == 0 and row_difference == 0):
                    adjacent_list.append([self.row+row_difference, self.column + column_difference])
        output_list = []
        for item in adjacent_list:
            thing = square_list[item[0]][item[1]]
            output_list.append(thing)
            if thing.hidden and not thing.flag:
                empty_list.append(thing)

        if choice == 0:
            return output_list
        else:
            return empty_list

    def adjacent_mines(self, type):
        num_mines = 0
        num_safe = 0
        num_hidden = 0
        num_flag = 0
        num_blank = 0
        for item in self.adjacents(0):
            if item.mine:
                num_mines += 1
            else:
                num_safe +=1
            if item.hidden:
                num_hidden +=1
                if item.flag:
                    num_flag +=1
                else:
                    num_blank += 1

        if type == 'm':
            return num_mines
        elif type == 's':
            return num_safe
        elif type == "h":
            return num_hidden
        elif type == "f":
            return num_flag
        elif type == "b":
            return num_blank

    def draw_me(self):
        if self.hidden:
            colour = WHITE
            text_colour = BLACK
            text = "F"
        else:
            colour = BLACK
            text_colour = WHITE
            text = str(self.adjacent_mines("m"))
        pygame.draw.rect(screen, colour, (self.column*square_size, self.row*square_size, square_size, square_size))
        if ((not self.hidden) or self.flag) and text != "0":
            font = pygame.font.SysFont(None, square_size)
            screen.blit(font.render(text, True, text_colour), (self.column *square_size + square_size/3, self.row*square_size + square_size/3))

    def reveal(self):
        global reveal_count
        global stage
        global win
        global check_list
        if self.hidden:
            reveal_count += 1
            self.flag = False
            if self.mine:
                stage = "end"
                win = False
                print(self.row, self.column)

            else:
                self.hidden = False
                check_win()

        if self.adjacent_mines("m") == 0:
            for item in self.adjacents(0):
                if item.hidden:
                    item.reveal()

        if self.adjacent_mines("b") > 0:
            check_list.append(self)

    def autocomplete(self):
        worked = False
        if (not self.hidden) and self.adjacent_mines("b") > 0:

            if self.adjacent_mines("b") == self.adjacent_mines("m")-self.adjacent_mines("f"):

                worked = True
                for item in self.adjacents(1):
                    item.flag = True

            elif self.adjacent_mines("m") == self.adjacent_mines("f"):

                worked = True
                for item in self.adjacents(1):
                    item.reveal()

        return worked

for row in range(row_max):
    square_list.append([])
    for column in range(column_max):
        square_object = square(row, column)
        square_list[row].append(square_object)

def setup(chosen_row, chosen_column):
    global reveal_count
    square_list[chosen_row][chosen_column].hidden = False
    reveal_count = 1
    for item in square_list[chosen_row][chosen_column].adjacents(0):
        item.hidden = False
        reveal_count += 1
    for _ in range(mine_count):
        valid = False
        while not valid:
            valid = True
            random_column = rand(0, column_max-1)
            random_row = rand(0, row_max -1)
            if square_list[random_row][random_column].mine or (not square_list[random_row][random_column].hidden):
                valid = False
            else:
                square_list[random_row][random_column].mine = True
                for item in square_list[random_row][random_column].adjacents(0):
                    if item.adjacent_mines('s') == 0:
                        valid = False
                        square_list[random_row][random_column].mine = False
                        break
    for row in square_list:
        for item in row:
            if not item.hidden:
                item.reveal()

def draw_grid():
    for i in range(row_max + 1):
        pygame.draw.line(screen, BLUE, (0, i*square_size), (column_max*square_size, i*square_size))
    for i in range(column_max + 1):
        pygame.draw.line(screen, BLUE, (i*square_size, 0), (i*square_size, row_max*square_size))

def draw_board():
    for row in square_list:
        for item in row:
            item.draw_me()
    draw_grid()

def list_possibilities(num_things, num_spaces):
    if num_things > num_spaces:
        return([])
    elif num_things == 0:
        string = ""
        for _ in range(num_spaces):
            string += "0"
        return([string])
    else:
        output_list = []
        position_list = []
        for _ in range(num_things):
            position_list.append("")

        def recursive(ordinal, smaller):
            nonlocal output_list
            nonlocal position_list

            for current in range(smaller+1, num_spaces -ordinal ):
                position_list[ordinal] = current

                if ordinal == 0:
                    placeholder = []
                    for item in position_list:
                        placeholder.append(item)

                    output_list.append(placeholder)
                else:
                    recursive(ordinal - 1, current)
        recursive(num_things-1, -1)
        return output_list

def wait():
    draw_board()
    pygame.display.update()

def brute(working):
    global check_list
    for square in check_list:
        print(square.row, square.column)
    wait()
    if working:
        print("going")
        working = False
        count = 0
        for i in range(len(check_list)):
            if stage == "play":
                item = check_list[count]
                if item.adjacent_mines("b") > 0:
                    attempt = item.autocomplete()
                    pygame.event.get()

                    if attempt:
                        working = True
                        del check_list[count]
                        wait()
                        check_win()
                    else:
                        count += 1
                else:
                    del check_list[count]

            else:
                break

    else:
        print("stuck")
        wait()
        stuck_v2()
        # thread = threading.Thread(stuck())
        # thread.start()
        # thread.join()

        working = True
        check_win()
    return working

def check_board():
    valid = True
    for row in square_list:
        for item in row:
            if (not item.hidden) and item.adjacent_mines("m") > 0:
                suspicious_count = 0
                for adjacent in item.adjacents(0):
                    if adjacent.flag or adjacent.mark_mine:
                        suspicious_count += 1
                if suspicious_count != item.adjacent_mines("m"):
                    valid = False
                    break
    return valid

def check_win():
    global win
    global stage
    if reveal_count == row_max*column_max - mine_count:
        stage = "end"
        win = True

timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, 1)

def game(option):
    global screen
    global stage
    global win
    global check_list
    win = False
    done = False

    screen.fill(WHITE)
    draw_grid()
    autocomplete_working = True
    stage_done = True

    while not done:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if stage == "setup":
                if option == "c":
                    setup(rand(0, row_max-1), rand(0,column_max-1))
                    stage = "play"
                    draw_board()
                    for row in square_list:
                        for square in row:
                            if not square.hidden and square.adjacent_mines("b") > 0:
                                check_list.append(square)
                    wait()
                    time.sleep(1.5)
                if  event.type == pygame.MOUSEBUTTONDOWN and option == "p":
                    mouse_row = pygame.mouse.get_pos()[1]//square_size
                    mouse_column = pygame.mouse.get_pos()[0]//square_size
                    setup(mouse_row, mouse_column)
                    stage = "play"
                    draw_board()

            elif stage == "play":
                if event.type == pygame.MOUSEBUTTONDOWN and option == "p":
                    mouse_row = pygame.mouse.get_pos()[1]//square_size
                    mouse_column = pygame.mouse.get_pos()[0]//square_size
                    button = event.button
                    if button == 1:
                        if square_list[mouse_row][mouse_column].hidden:
                            square_list[mouse_row][mouse_column].reveal()
                        else:
                            _ = square_list[mouse_row][mouse_column].autocomplete()
                        print(square_possibilities(square_list[mouse_row][mouse_column]))

                        check_win()
                        draw_board()
                    #Left click

                    elif button == 3:
                    #Right click
                        square_list[mouse_row][mouse_column].flag = not square_list[mouse_row][mouse_column].flag
                        draw_board()
                        print(square_possibilities(square_list[mouse_row][mouse_column]))

                elif option == "c" and event.type == timer_event:
                    autocomplete_working = brute(autocomplete_working)

            elif stage == "end":

                if stage_done == True:

                    if win == False:
                        print("lose")
                        # for row in square_list:
                        #     for square in row:
                        #         if square.flag:
                        #             print(square.row, square.column, "flag")

                    else:
                        print("win")
                        if option == "c":
                            for row in square_list:
                                for item in row:
                                    if not item.flag and item.hidden:
                                        item.flag = True
                            wait()
                    stage_done = False
                # # if event.type == pygame.MOUSEBUTTONDOWN:
                # #     done = True
                # # else:
                # if win:
                #     text = "You Win!"
                # else:
                #     text = "You Lose!"
                # screen.fill(BLACK)
                # font = pygame.font.SysFont(None, square_size)
                # screen.blit(font.render(text, True, WHITE), (square_size*column_max/3, square_size*row_max/3))

        pygame.display.update()

def square_possibilities(square):
    spaces = square.adjacent_mines("b")

    temp_list = list_possibilities(square.adjacent_mines("m") - square.adjacent_mines("f"), spaces)
    output_list = []
    for item in temp_list:
        binary_string = ''
        for i in range(spaces):
            if i in item:
                binary_string += "1"
            else:
                binary_string += "0"

        output_list.append(binary_string)
    return output_list

def convert_overlap(indexes, string):
    new_bin = ""
    for index in indexes:
        new_bin += string[index]
    return new_bin
#reduce string to just overlaps

def make_new_bin(overlap_indexes, possibilities):
    output_list = []
    for bin in possibilities:
        new_bin = convert_overlap(overlap_indexes, bin)
        if new_bin not in output_list:
            output_list.append(new_bin)
    return output_list
#make new list of just overlap possibilities
def check_in_list(possibility_list, indexes, overlap_possibilities):
    count = 0
    for i in range(len(possibility_list)):
        if convert_overlap(indexes, possibility_list[count]) not in overlap_possibilities:
            possibility_list.pop(count)
        else:
            count += 1
    return possibility_list
#Cull board_possibilities to possible lists

def stuck_v2():
    global check_list
    num_flags = 0
    for row in square_list:
        for item in row:
            if item.flag:
                num_flags += 1

    board_possibilities = square_possibilities(check_list[0])
    # for item in check_list:
    #     print(item.row, item.column, item.hidden)
    keys = check_list[0].adjacents(1)
    for key in keys:
        print(key.row, key.column, "key")
    # for key in keys:
    #     print("keys", key.row, key.column)
    big_success = False
    for k in range(1,len(check_list)):
        for key in keys:
            print(key.row, key.column, "key")

        item = check_list[k]
        # print(item, item.row, item.column)
        big_overlap_indexes = []
        small_overlap_indexes = []
        item_adjacents = item.adjacents(1)
        # for adjacent in item_adjacents:
        #     # print("adjacents",adjacent.row, adjacent.column )

        item_possibilities = square_possibilities(item)
        print(item_possibilities, item.row, item.column)
        for i in range(len(keys)):
            for k in range(len(item_adjacents)):
                if keys[i] == item_adjacents[k]:
                    big_overlap_indexes.append(i)
                    small_overlap_indexes.append(k)
#Finds which squares overlap

        big_overlap_possibilities = make_new_bin(big_overlap_indexes, board_possibilities)
        print(big_overlap_possibilities, "big overlap possibilities")
        small_overlap_possibilities = make_new_bin(small_overlap_indexes, item_possibilities)
        print(small_overlap_possibilities, "small """)

        overlap_possibilities = small_overlap_possibilities
        for bin in overlap_possibilities:
            if bin not in big_overlap_possibilities:
                overlap_possibilities.remove(bin)

        board_possibilities = check_in_list(board_possibilities, big_overlap_indexes, overlap_possibilities)
        item_possibilities = check_in_list(item_possibilities, small_overlap_indexes, overlap_possibilities)
        pygame.event.get()
        stripped_item_possibilities = []

        for bin in item_possibilities:
            new_bin = ""
            for i in range(len(bin)):
                if i not in small_overlap_indexes:
                    new_bin += bin[i]
            if new_bin not in stripped_item_possibilities:
                stripped_item_possibilities.append(new_bin)
        stripped_item_keys = []
        pygame.event.get()
        for i in range(len(item_adjacents)):
            if i not in small_overlap_indexes:
                stripped_item_keys.append(item_adjacents[i])
        new_board_possibilities = []
        for bin in board_possibilities:
            for item_bin in stripped_item_possibilities:
                potential_mines = 0
                new_bin = bin + item_bin
                check_bin = item_bin

                for i in range(len(big_overlap_indexes)):
                    check_bin = check_bin[:small_overlap_indexes[i]] + bin[big_overlap_indexes[i]] + check_bin[small_overlap_indexes[i]:]
                if check_bin in item_possibilities:
                    for character in new_bin:
                        if character == "1":
                            potential_mines += 1
                    if num_flags + potential_mines <= mine_count:
                        new_board_possibilities.append(new_bin)
                    #Check if there will be too many mines on the board

        # print(board_possibilities)
        # print(big_overlap_indexes)
        # print(item_possibilities)
        # print(small_overlap_indexes)
        board_possibilities = new_board_possibilities
        # print(new_board_possibilities)
        keys += stripped_item_keys
        # for key in keys:
        #     print("keys", key.row, key.column)
        pygame.event.get()

        print(board_possibilities)
        for i in range(len(board_possibilities[0])):
            small_success = True
            number = board_possibilities[0][i]
            for q in range(1, len(board_possibilities)):
                if number != board_possibilities[q][i]:
                    small_success = False
                    break

            if small_success:
                big_success = True
                print("big_success")

                if number == "0":
                    keys[i].reveal()

                elif number == "1":
                    keys[i].flag = True
                wait()
        if big_success:
            for key in keys:
                print(key.row, key.column, "key")
            break

    if not big_success:
        random_num = rand(0, len(keys)-1)
        keys[random_num].reveal()
        print(keys[random_num].row, keys[random_num].column, "random selection")
        wait()
        print("random")

game("c")


import pygame, sys
from pygame.locals import *

class Particle(object):

    #Initalizes the paritcle object (called when it is first created)
    def __init__(self,X,Y,size,deltaX,deltaY,color, displaySurface):
        #surface to display the particle on
        self.displaySurface = displaySurface
        #color to make the particle
        self.color = color
        #how fast it moves on the X axis
        self.deltaX = deltaX
        #how far it moves on the Y axis
        self.deltaY = deltaY
        #create the particle rectangle
        self.rectangle = pygame.Rect(X,Y, size , size)

    #function to draw the particle image on the displaysurface
    def draw(self):
        #draw the particle
        pygame.draw.rect(self.displaySurface,
                         self.color, self.rectangle)
        #move the particle so it is in a
        #new location next time we draw
        self.rectangle.x = self.rectangle.x + self.deltaX
        self.rectangle.y = self.rectangle.y + self.deltaY

    def setColor(self,color):
        #color to make the particle
        self.color = color


import pandas as pd
import argparse
import yaml
import os
import io
import json

def retrieve_params(config):
    with open(config) as yaml_file:
        params= yaml.safe_load(yaml_file)
    return params

def generate_metadata_csv(params):
    excel_file_path = params["data"]["standard_excel_file"]

    df = pd.read_csv(excel_file_path)
    df.columns = [i.strip() for i in df.columns]
    buffer = io.StringIO()
    df.info(buf=buffer, verbose = True, null_counts = False, memory_usage=False)
    s = buffer.getvalue()
    s = s.split("\n")
    del(s[1])
    s = "\n".join(s)
    standard_csv_meta = params["data"]["standard_csv_meta"]
    with open(standard_csv_meta, "a+") as f:
        f.write(s)
        f.write("\n")

def generate_metadata_json(params):
    json_file_path = params["data"]["standard_json_file"]

    with open(json_file_path) as json_file:
        standard_dict = json.load(json_file)

    standard_json_meta = params["data"]["standard_json_meta"]
    keys1 = standard_dict.keys()
    for i in standard_dict["items"]:
        keys2 = i.keys()
        break
    b = standard_dict["items"][0]["snippet"]
    keys3 = b.keys()

    with open(standard_json_meta, "w") as meta:
        meta.write(str(list(keys1)))
        meta.write("\n")
        meta.write(str(list(keys2)))
        meta.write("\n")
        meta.write(str(list(keys3)))

def generate_metadata(config):
    params = retrieve_params(config=config)
    generate_metadata_csv(params)
    generate_metadata_json(params)

if __name__=="__main__":
    args = argparse.ArgumentParser()
    args.add_argument("--config", default="params.yaml")
    parsed_args = args.parse_args()
    generate_metadata(parsed_args.config)


"""
Variables!
"""

length = 20
breadth = 10
area = length * breadth
print(area)

# legal variables

Area = 10
_area = 10
_Area = 10
area_1 = 10
area1 = 10

# python should use snake-case naming

first_name = 'Akhila'
print(first_name)

#python basic: programming challenge: Money left in the bank after subracting all the items from bank_amount

bank_amount = 100
item_one = 25
item_two = 30
item_three = 15
bank_amount = bank_amount - (item_one+item_two+item_three)
print(bank_amount)


from enum import Enum

class ProxyResponseType(Enum):
    proxy = 'proxy'
    file = 'file'
    json = 'json'

    def get_dict(self):
        return self.value

class ProxyResponse(object):
    def __init__(self,
                 request,
                 response,
                 type: ProxyResponseType,
                 status_code: int,
                 headers: dict,
                 body: any):
        self.request = request
        self.response = response
        self.type = type
        self.status_code = status_code
        self.headers = headers
        self.body = body

    def get_dict(self):
        return {
            'type': self.type.value,
            'status_code': self.status_code,
            'headers': self.headers,
            'body': self.body,
        }