from .models import *
from django import forms
from django.contrib.auth.forms import UserCreationForm

class SellerForm(UserCreationForm):
    password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={'class': "form-control form-control-sm"}))
    password2 = forms.CharField(label='Повторіть Пароль', widget=forms.PasswordInput(attrs={'class': "form-control form-control-sm"}))
    hometown_add = forms.BooleanField(label='Розширені можливості', required=False, widget=forms.CheckboxInput(attrs={'class': "form-check-input", 'type': "checkbox", 'role': "switch"}))

    class Meta:
        model = Seller
        fields = ['username', 'first_name', 'last_name', 'phone', 'email', 'password1', 'password2', 'hometown_add']

        labels = {
            'username': "Логін",
            'first_name': "Им'я",
            'last_name': 'Фамілія',
            'email': "Email",
            'phone': 'Номер Телефону',
        }
        help_texts = {'username': ""}

        widgets={
                "username": forms.TextInput(attrs={'class': "form-control form-control-sm ", 'autocomplete': "off"}),
                "first_name": forms.TextInput(attrs={'class': "form-control form-control-sm ", 'autocomplete': "off"}),
                "last_name": forms.TextInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                "phone": forms.NumberInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                "email": forms.TextInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                }

    def save(self, commit=True):
        user = super(SellerForm, self).save(commit=False)
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        user.username = self.cleaned_data['username']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']
        user.phone = self.cleaned_data['phone']
        user.set_password(self.cleaned_data['password2'])
        user.is_active = self.cleaned_data.get('is_active', True)
        user.is_staff = self.cleaned_data.get('is_staff', False)
        hometown_add = self.cleaned_data.get('hometown_add', False)
        if commit:
            user.save()
        if hometown_add:
            seller_group = Group.objects.get(name='hometown')
            user.groups.set([seller_group])
        return user

class Form(forms.ModelForm):
    code_ord = forms.CharField(required=False, label='КОД Продукту',
                               widget=forms.TextInput(attrs={'class': "form-control form-control-sm", 'id': "code_ord"}))
    product = forms.ModelChoiceField(queryset=Product.objects.all(), label='Назва Продукту', required=False,
                                     empty_label="Виберіть назву продукту", widget=forms.Select(attrs={'class': "form-select form-select-sm filter-forms", 'id': "product"}))
    delivery = forms.ChoiceField(label='Доставка', choices=(('pickup', 'САМОВИВІЗ'), ('NP', 'НОВА ПОШТА')),
                                 widget=forms.RadioSelect(attrs={'id': "delivery"}), initial='pickup')

    class Meta:
        model = Order
        fields = ['code_ord', 'product', 'amount', 'sizes', 'delivery', 'name_client', 'phone_client', 'city_client', 'dep_np', 'actual_weight', 'status', 'sum']
        labels = {
            "code_ord": "КОД",
            'product': 'Назва',
            'amount': 'Кількість',
            'sizes': 'Розміри',
            'name_client': 'ПІБ Отримувач',
            'phone_client': 'Телефон Отримувача',
            'city_client': ' Місто Отримувача',
            'dep_np': 'Відділення Нової пошти',
            'actual_weight': 'Фактична Вага',
            'status': 'Статус',
            'sum': "Вартість",
        }
        widgets={
                "sizes": forms.TextInput(attrs={'class': "form-control form-control-sm"}),
                'name_client': forms.TextInput(attrs={'class': "form-control form-control-sm", 'id': "name_client", 'autocomplete': "off"}),
                'phone_client': forms.TextInput(attrs={'class': "form-control form-control-sm", 'id': "phone_client", 'autocomplete': "off"}),
                'city_client': forms.TextInput(attrs={'class': "form-control form-control-sm", 'id': "city_client", 'autocomplete': "off"}),
                'dep_np': forms.TextInput(attrs={'class': "form-control form-control-sm", 'id': "dep_np", 'autocomplete': "off"}),
                'actual_weight': forms.Select(attrs={'class ': "form-select form-select-sm filter-forms", 'id': "id_weight"}),
                'status': forms.Select(attrs={'class': "form-select form-select-sm filter-forms", 'id': "id_status"}),
                'amount': forms.NumberInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                'sum': forms.NumberInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),

                }

    def clean(self):
        cleaned_data = super().clean()
        code_ord = cleaned_data.get("code_ord")
        amount = cleaned_data.get("amount")
        product = cleaned_data.get("product")
        delivery = cleaned_data.get("delivery")
        name_client = cleaned_data.get("name_client")
        phone_client = cleaned_data.get("phone_client")
        city_client = cleaned_data.get("city_client")
        dep_np = cleaned_data.get("dep_np")
        sum = cleaned_data.get("sum")
        if not code_ord and not product:
            raise forms.ValidationError("Вкажіть назву або код продукту")
        elif code_ord and not product:
            try:
                product = Product.objects.get(code=code_ord)
            except Product.DoesNotExist:
                raise forms.ValidationError("Продукт з таким кодом не існує")
            cleaned_data["product"] = product
        elif product and not code_ord:
            cleaned_data["code_ord"] = product.code
        if amount > product.amount:
            raise forms.ValidationError(f"Залишок товару {product.amount}")
            del amount
        elif sum < (product.cost * amount):
            raise forms.ValidationError("Помилка Вартості")
            del sum
        if delivery == "NP":
            if not name_client or not phone_client or not city_client or not dep_np:
                raise forms.ValidationError("Заповніть інформацію для Нової пошти")
        return cleaned_data

    def save(self, commit=True, request=None):
        order = super().save(commit=False)
        if self.cleaned_data['delivery'] == 'NP':
            customer, create = Customer.objects.get_or_create(
                phone=self.cleaned_data['phone_client'],
                name=self.cleaned_data['name_client'],
                address=self.cleaned_data['city_client'],
            )
            order.customer = customer
        else:
            order.customer = order.seller
            order.actual_weight = "САМОВИВІЗ"
            order.status = 'САМОВИВІЗ'
            order.status_code = '0'

        if commit:
            order.save()
        return order

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['product'].queryset = Product.objects.exclude(amount=0)

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        labels = {
            "code": "КОД",
            'name': 'Назва',
            'amount': 'Кількість',
            'cost': 'Ціна за 1 од.',
            'img': "Зображення продукту"
        }
        widgets={
                "code": forms.TextInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                "name": forms.TextInput(attrs={'class': "form-control form-control-sm form-control-wrap text-truncate", 'autocomplete': "off"}),
                "amount": forms.NumberInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                "cost": forms.NumberInput(attrs={'class': "form-control form-control-sm", 'autocomplete': "off"}),
                "img": forms.FileInput(attrs={'class': 'form-control form-control-sm'})
        }


from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, LSTM
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, MinMaxScaler
from sklearn import preprocessing
from sklearn.metrics import accuracy_score, mean_squared_error
import matplotlib.pyplot as plt
import pandas as pd
import math
import numpy as np

# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1): #:time_step=1):
    dataX, dataY = [], []
    for i in range(len(dataset) - look_back - 1): #time_step - 1):
        a = dataset[i:(i + look_back), 0] #time_step), 0]
        dataX.append(a)
        dataY.append(dataset[i + look_back, 0]) #time_step, 0])
    return np.array(dataX), np.array(dataY)

# Fix Random seed for reproductibility
np.random.seed(7)

## Input Data Train dan Data Test Bahasa Isyarat

dataframe = pd.read_csv('datatrainingisyaratnumber.csv', sep=';')
dataset = dataframe.values
dataset = dataset.astype("float32")
#print(dataset)

#print(len(train), len(test))

# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# print(dataset.shape)

# split into train and test sets
train_size = int(len(dataset) * 0.6)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset),:]

# reshape into X=t and Y=t
look_back = 1
#time_step = 23
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
#print(testX.shape), print(testY.shape)
#print(trainX.shape), print(trainY.shape)

# reshape input to be [samples, time steps, features]
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX  = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
#print(trainX,testX)

# # create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))#time_step)))
model.add(Dropout(0.2))
model.add(Dense(23, input_dim=1, activation='relu'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
model.fit(trainX, trainY, epochs=500, batch_size=5, validation_split=0.33)

# # make predictions
a = model.predict(trainX)
#print(a.shape)
b = model.predict(testX)
print(b.shape)

# invert predictions (big problem start here
trainPredict = scaler.inverse_transform(a)
#print(a.shape)

trainY_extended = np.zeros((len(trainY),23))
trainY_extended[:,2]=trainY
#print(trainY_extended[:,2].shape)
trainY = scaler.inverse_transform(trainY_extended)[:,2]

testPredict = scaler.inverse_transform(b)
#print(b.shape)

testY_extended = np.zeros((len(testY),23))
testY_extended[:,2]=testY
testY = scaler.inverse_transform(testY_extended)[:,2]
#print(testY_extended[:,2].shape)

# # calculate root mean squared error
trainScore = math.sqrt(mean_squared_error(trainY[:], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[:], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))

# # shift train predictions for plotting
trainPredictPlot = np.empty_like(dataset)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict

# # shift test predictions for plotting
testPredictPlot = np.empty_like(dataset)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict

# Plot predict train and predict test
predict_train, = plt.plot(trainPredictPlot[:,2])
predict_test,= plt.plot(testPredictPlot[:,2],linestyle='--')
plt.title('Hasil DataProcessing Bahasa Isyarat')
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.legend([predict_train,predict_test], ['training', 'test'], loc='upper right')
plt.show()

# # plot baseline and predictions
serie, = plt.plot(scaler.inverse_transform(dataset)[:,2], linestyle='--')
predict_train,= plt.plot(trainPredictPlot[:,2])
predict_test,= plt.plot(testPredictPlot[:,2])
plt.title('Hasil DataProcessing Bahasa Isyarat')
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.legend([serie,predict_train,predict_test], ['serie','training', 'test'], loc='upper right')
plt.show()

#trainY = np.reshape(trainY, (trainY.shape[0], 1, trainY.shape[1]))
#testY  = np.reshape(testY, (testY.shape[0], 1, testY.shape[1]))
# create empty table with 12 fields
# trainPredict_dataset_like = np.zeros(shape=(len(trainPredict), 23) )
# put the predicted values in the right field
# trainPredict_dataset_like[:,0] = trainPredict[:,0]
# inverse transform and then select the right field
#trainPredict = scaler.inverse_transform(trainPredict_dataset_like)[:,0]
# trainPredict = np.array(trainPredict).reshape(-1,1,)
# print(trainPredict)

# print(trainX, testX)
# print(testX, testY)

# print(traindata.head)

# testdata = pd.read_csv('datatestisyarat.csv', sep=';')
# print(testdata.shape)
# print(testdata.head)

# Convolutional Neural Network
# model = Sequential()
# model.add(Conv1D())


from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from PIL import Image
import os
import torch
import random

# Define a custom dataset class for image enhancement tasks.
class ImageEnhancementDataset(Dataset):
    def __init__(self, input_root_dir, output_root_dir, transform=None, train=True):
        """
        Initialize the Image Enhancement Dataset.

        Args:
            input_root_dir (str): Path to the directory containing input images.
            output_root_dir (str): Path to the directory containing output (target) images.
            transform (callable, optional): Optional image transformations to apply.
            train (bool, optional): Set to True for training data; applies data augmentation.
        """
        self.input_root_dir = input_root_dir
        self.output_root_dir = output_root_dir
        self.transform = transform
        self.train = train

        # List all input and output image file paths
        self.input_image_paths = [os.path.join(input_root_dir, fname) for fname in sorted(os.listdir(input_root_dir))]
        self.output_image_paths = [os.path.join(output_root_dir, fname) for fname in sorted(os.listdir(output_root_dir))]

    def __len__(self):
        """Return the number of samples in the dataset."""
        return len(self.input_image_paths)

    def apply_data_augmentation(self, input_image, output_image, idx):
        """
        Apply data augmentation to input and output images.

        Args:
            input_image (PIL.Image): Input image.
            output_image (PIL.Image): Output (target) image.

        Returns:
            PIL.Image: Augmented input image.
            PIL.Image: Augmented output (target) image.
        """
        input_image = self.transform(input_image)
        output_image = self.transform(output_image)

        if self.train:
            # Apply color jitter to enhance training data
            color_jitter = MyColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1, seed=idx)
            input_image = torch.where(input_image == 0 , input_image, color_jitter(input_image))
            output_image = torch.where(output_image == 0, input_image, color_jitter(output_image))

        return input_image, output_image

    def __getitem__(self, idx):
        """
        Get an item from the dataset by index.

        Args:
            idx (int): Index of the item to retrieve.

        Returns:
            PIL.Image: Augmented input image.
            PIL.Image: Augmented output (target) image.
        """
        input_img_path = self.input_image_paths[idx]
        output_img_path = self.output_image_paths[idx]

        input_image = Image.open(input_img_path).convert('RGB')
        output_image = Image.open(output_img_path).convert('RGB')

        input_image, output_image = self.apply_data_augmentation(input_image, output_image, idx)

        return input_image, output_image

def get_data_loaders(train_input_root_dir, train_output_root_dir, test_input_root_dir, test_output_root_dir, batch_size):
    """
    Create data loaders for training and testing datasets.

    Args:
        train_input_root_dir (str): Path to the directory containing training input images.
        train_output_root_dir (str): Path to the directory containing training output images.
        test_input_root_dir (str): Path to the directory containing testing input images.
        test_output_root_dir (str): Path to the directory containing testing output images.
        batch_size (int): Batch size for data loaders.

    Returns:
        DataLoader: Training data loader.
        DataLoader: Testing data loader.
    """
    transform = transforms.Compose([transforms.ToTensor()])

    train_dataset = ImageEnhancementDataset(train_input_root_dir, train_output_root_dir, transform=transform, train=True)
    test_dataset = ImageEnhancementDataset(test_input_root_dir, test_output_root_dir, transform=transform, train=False)

    train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)

    return train_loader, test_loader

class MyColorJitter(transforms.ColorJitter):
    def __init__(self, brightness, contrast, saturation, hue, seed):
        super().__init__(brightness, contrast, saturation, hue)
        self.seed = seed

    def forward(self, img):
        torch.manual_seed(self.seed)
        random.seed(self.seed)
        return super().forward(img)


import pandas_datareader as dtr
import matplotlib.pyplot as plt
import pandas as pd
import yfinance as yf
import numpy as np
import tensorflow as tf

#from keras_model import load_data
import streamlit as st

start='2012-01-01'
end= '2022-12-30'

st.title("Stock Price Predictor ")

user_input = st.text_input("Enter stock ticker", "AAPL")

# data = dtr.DataReader(user_input,'yahoo', start, end)
data = yf.download('AAPL',start,end)

# visulasizations

st.subheader("Closing price V/S Time ")
fig = plt.figure(figsize=(12,6))
plt.title("Close price history", fontsize=18)
plt.xlabel('Time', fontsize = 14)
plt.ylabel('Price', fontsize = 14)
plt.plot(data.Close)
st.pyplot(fig)

st.subheader("Closing price With 100MA and 200MA V/S Time ")

ma200 = data.Close.rolling(200).mean()
ma100 = data.Close.rolling(100).mean()

fig = plt.figure(figsize=(12,6))

plt.plot(data.Close)
plt.plot(ma100, 'r' , label= "100MA")
plt.plot(ma200, 'g', label= '200MA')
plt.title("Close price with MA100 and MA200", fontsize=18)
plt.xlabel('Day_elapsed', fontsize = 14)
plt.ylabel('Price', fontsize = 14)
plt.legend()
st.pyplot(fig)

# Spliting data into training and test set

data_train = pd.DataFrame(data.Close[0:int(len(data)* .7)])
data_test = pd.DataFrame(data.Close[int(len(data)* .7):len(data)])

# Doing feature scaling as we will apply LSTM

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
train_data = scaler.fit_transform(data_train)

# load model
model = tf.keras.load_model('share_model.h5')

# Testing part
past_100_days= data_train.tail(100)
final_data_test = past_100_days.append(data_test , ignore_index = True)
test_data = scaler.transform(final_data_test)
x_test = []
y_test = []
for i in range(100,test_data.shape[0]):
  x_test.append(test_data[i-100:i])
  y_test.append(test_data[i,0])

x_test , y_test = np.array(x_test), np.array(y_test)
predictions= model.predict(x_test)
predictions = scaler.inverse_transform(predictions)

# plot the data
st.subheader("Prediction V/S Original ")
fig2= plt.figure(figsize=(12,6))
plt.plot(y_test,  'b', label='Original_price')
plt.plot(predictions, 'r', label='predicted_price')
plt.xlabel('day')
plt.ylabel('price')
plt.legend()
st.pyplot(fig2)


import os
import re
import shutil
import socket

import intake
import pandas as pd
import pytest
import s3fs

from intake_esm import config
from intake_esm.storage import StorageResource, _ensure_file_access, _filter_query_results

CIRCLE_CI_CHECK = os.environ.get('CIRCLECI', False)
if CIRCLE_CI_CHECK:
    profile_name = None

else:
    profile_name = 'intake-esm-tester'

storage_options = {'anon': False, 'profile_name': profile_name}

here = os.path.abspath(os.path.dirname(__file__))

regex = re.compile(r'cheyenne|casper')
hostname = socket.gethostname()
match = regex.search(hostname)

try:
    TMPDIR = os.environ['TMPDIR']
except:
    TMPDIR = './tests/tmpdir'

def test_storage_input_file():
    input_file = os.path.join(here, 'input-filelist-test.txt')
    urlpath = input_file
    type_ = 'input-file'
    exclude_dirs = ['*/avoid-this-dir/*']
    file_extension = '.nc'

    SR = StorageResource(urlpath, type_, exclude_dirs, file_extension)
    assert isinstance(SR, StorageResource)
    files = SR.filelist
    assert isinstance(files, list)
    assert len(files) == 4

@pytest.mark.skipif(
    not match, reason='does not run outside of Cheyenne login nodes or Casper nodes'
)
def test_storage_hsi():
    urlpath = '/CCSM/csm/CESM-CAM5-BGC-LE/ocn/proc/tseries/daily/SST'
    loc_type = 'hsi'
    exclude_dirs = []
    file_extension = '.nc'
    SR = StorageResource(urlpath, loc_type, exclude_dirs, file_extension)

    files = SR.filelist
    assert isinstance(files, list)
    assert len(files) != 0

def test_storage_aws_s3():
    fs = s3fs.S3FileSystem(**storage_options)
    SR = StorageResource(
        urlpath='s3://ncar-cesm-lens/lnd/monthly/',
        loc_type='aws-s3',
        exclude_patterns=[],
        file_extension='.zarr',
        fs=fs,
    )
    stores = SR.filelist
    assert len(stores) != 0

def test_storage_aws_s3_failure():
    with pytest.raises(ValueError):
        _ = StorageResource(
            urlpath='s3://ncar-cesm-lens/lnd/monthly/',
            loc_type='aws-s3',
            exclude_patterns=[],
            file_extension='.zarr',
            fs=None,
        )

def test_file_transfer_symlink():
    data_cache_dir = f'{TMPDIR}/intake-esm-tests/transferred-data'
    with config.set(
        {'database-directory': './tests/test_collections', 'data-cache-directory': data_cache_dir}
    ):
        collection_input_definition = os.path.join(here, 'copy-to-cache-collection-input.yml')
        col = intake.open_esm_metadatastore(
            collection_input_definition=collection_input_definition, overwrite_existing=True
        )

        cat = col.search(variable=['STF_O2', 'SHF'])

        query_results = _ensure_file_access(cat.query_results)
        local_urlpaths = query_results['file_fullpath'].tolist()
        assert isinstance(local_urlpaths, list)
        assert len(local_urlpaths) > 0

        shutil.rmtree(data_cache_dir)

@pytest.mark.skipif(
    not match, reason='does not run outside of Cheyenne login nodes or Casper nodes'
)
def test_file_transfer_hsi():
    data_cache_dir = f'{TMPDIR}/intake-esm-tests/transferred-data'
    with config.set(
        {'database-directory': './tests/test_collections', 'data-cache-directory': data_cache_dir}
    ):
        collection_input_definition = os.path.join(
            here, 'ensure-file-hsi-transfer-collection-input.yml'
        )
        col = intake.open_esm_metadatastore(
            collection_input_definition=collection_input_definition, overwrite_existing=True
        )

        cat = col.search(variable=['SST'])

        query_results = _ensure_file_access(cat.query_results)
        local_urlpaths = query_results['file_fullpath'].tolist()
        assert isinstance(local_urlpaths, list)
        assert len(local_urlpaths) > 0

        shutil.rmtree(data_cache_dir)

def test_filter_query_results():
    resource_type = ['posix', 'hsi', 'hsi']
    files = [
        'g.e11_LENS.GECOIAF.T62_g16.009.pop.h.ECOSYS_XKW.024901-031612.nc',
        'g.e11_LENS.GECOIAF.T62_g16.009.pop.h.ECOSYS_XKW.024901-031612.nc',
        'g.e11_LENS.GECOIAF.T62_g16.009.pop.h.SST.024901-031612.nc',
    ]
    direct_access = [True, False, False]
    df = pd.DataFrame(
        {'resource_type': resource_type, 'file_basename': files, 'direct_access': direct_access}
    )

    query_results = _filter_query_results(df, file_basename_column_name='file_basename')
    assert len(query_results) == 2


#   Copyright 2021 Mario Guzzi
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
'''
Created on Oct. 22, 2021

@author: Mario Guzzi
'''

from collections import defaultdict

class quadCoeff:
    def __init__(self):
        return

    # For constraint to achieve an exact value
    def getEqual(self,v):
        q = 2.0
        l = 1.0 - 2.0*v
        c = v ** 2.0
        return list([q,l,c])

    # For constraint to achieve at least one
    # Todo: Solve an equation to create an AtLeastX
    def getAtLeastOne(self):
        q = 2.0
        l = -3.0
        c = 0.0
        return list([q,l,c])

    # For Cubic to Qubo constraints where an Ancillary must match a target
    def getBothOrNothing(self):
        q = -2.0
        l = +1.0
        c =  1.0
        return list([q,l,c])

    def getXOR(self):
        q =  2.0
        l = -1.0
        c = +1.0
        return list([q,l,c])

#======================================================================================================================================
# highOrderExpression class :
# Given a weight, an array of variable ids representing a product of these variables and the next available variable id
# to choose from for creating additional variables, return a Qubo representing the reduced product to a quadratic model.
#
# Usage:
#
# W = 10000          # Intended weight
# P = 1              # Penalty weight for substituted pairs
# Vars = [1,2,3,4,5] # List of binary variable ids
#
# e = highOrderExpression(W,Vars)
#
# e.print()                      : Print the current state of the expression
# e.elaborate()                  : Elaborate the expression as a sum of terms with variable names
# e.reduceExpression(P=P,Y=6)    : Reduce a high order expression to a Quadratic order apply y1=x1x2 and adding the constraint terms
#    P : Penalty to apply for the substitution constraint
#    Y : The next variable id to use when adding new variables (Note: No high value variables to Y must be currently in use)
# e.qubo()                       : Return a Qubo (upper triangle) for the current expression if the order is < 3
# e.newvars                      : List of new variables needing to be created in a model using this expression
#
# Example using above parameters:
#
# e.print():
# Expression terms ========================
# 0: {'vars': [1, 2, 3, 4, 5], 'W': 10000}
#
# e.elaborate():
# ( 10000 )x1x2x3x4x5
#
# e.reduceExpression(P=1,Y=6)
# e.elaborate():
# ( 1 )x1x2 + ( -2 )x1x6 + ( -2 )x2x6 + ( 3 )x6 +
#             ( 1 )x3x4 + ( -2 )x3x7 + ( -2 )x4x7 + ( 3 )x7 +
#             ( 1 )x5x6 + ( -2 )x5x8 + ( -2 )x6x8 + ( 3 )x8 + ( 10000 )x7x8
#
# e.newvars :
# New variables [6, 7, 8]
#
# e.qubo() :
# defaultdict(<class 'float'>, {(0, 1): 1.0, (0, 5): -2.0, (1, 5): -2.0, (5, 5): 3.0, (2, 3): 1.0, (2, 6): -2.0, (3, 6): -2.0, (6, 6): 3.0, (4, 5): 1.0, (4, 7): -2.0, (5, 7): -2.0, (7, 7): 3.0, (6, 7): 10000.0})
#
#====================================================================================================================================

class highOrderExpression:
    # Hold one expression term : W x [ v1 x v2 x v3 x ... x vn ]
    class oneterm:
        def __init__(self,W,variables):
            self.vars = variables
            self.W = W
        def getOrder(self):
            return(len(self.vars))

    # Initialize an binary weighed expression
    # variables = list of variable ids
    # W = weight to apply to the product of these variables
    #
    def __init__(self, W=1, variables=None, subs={}):
        '''
        Create a sum of binary variable product expression with an optional first term

        :param W: Variable weight
        :param variables: Variable ids
        :param subs: Substituted variables when converting k-local to 2-local
        '''

        self.order = 0
        self.terms = []
        self.newvars = []
        #print("received these substitutions:", subs )
        self.substitutions = subs

        if ( variables is not None):
            term=self.oneterm(W,variables)
            if ( term is not None ):
                self.terms.append(term)
                self.order = max(self.order,term.getOrder()) # Adjust the order of the expression

    # Calculate expression order
    # Find the highest order expression and memorize the order
    def getExpressionOrder(self):
        self.order = 0
        for t in self.terms:
            if ( t is not None):
                self.order = max(self.order,t.getOrder())
        return(self.order)

    # Add a term with penalty P and coefficient C to the expression
    # P is the penalty weight to place on the variable reduction constraint
    # C is the coefficient intended for the original expression
    def add(self,x,P,C):
        #print("Adding this term:",x,P*C)
        self.terms.append(self.oneterm(P*C,x))
        return(self)

    def trim(self):
        self.terms = [t for t in self.terms if t is not None]

    # Invert binary variable: (x) -> (1-x)

    def inv_var(self,w,array,target):
        res = []
        ext = [a for a in array if a != target]
        res.append((1*w,ext))
        res.append((-1*w,array))
        return res

    # Invert terms for a target variable:
    # ex: targ = y,  xyzt => x(1-y)zt => xzt - xyzt

    def inv_terms(self,terms,target):
        res = []

        for (w,v) in [t for t in terms]:
            # if the term has a target, process inversion
            # otherwise, keep term as is
            #print("Looking for",target,"in",v)
            if ( target in v):
                res.extend(self.inv_var(w,v,target))
            else:
                res.extend((w,v))

            #print("New list is", res)

        return res

    # Invert an entire expression:
    # x1x2x3x4 => (1-x1)(1-x2)(1-x3)(1-x4) => (1-x2)(1-x3)(1-x4) - (1-x2)(1-x3)(1-x4)x1 => ... until only sum of product terms remain
    def inv_exp(self,wgt,variables):
        terms = [(wgt,variables)]
        for v in variables:
            terms = self.inv_terms(terms,v)
        return terms

    # Print the list of expressions.
    # Note: Zero expressions come from substituting one expression to another
    def print(self):
        print("Expression terms ========================")
        for i,t in enumerate(self.terms):
            print(i,end=': ')
            if ( t is None):
                print("Zero Term")
            else:
                print(t.__dict__)

    def elaborate(self):
        result = ""
        first=True
        for t in self.terms:
            if ( t is not None):
                if ( first ):
                    first = False
                else:
                    result = result + ' + '
                    #print(' + ',end='')
                result = result + "(" + str(t.W)+")"
                #print("(",t.W,")", end='')
                for v in t.vars:
                    result = result + "x{}".format(v)
                    #print("x%s" %(v),end='')
        return result
        #print("")

    # Reduction to Quadratic
    # Applying variable substitution method introducing ancilla variables
    #
    # x0x1x2 ==> y0=x0x1 ==> P(x0x1 -2x0y0 -2x1y0 +3y0) + y0x2
    # Thus Wx0x1x2 = P(x0x1 -2x0y0 -2x1y0 +3y0) + Wy0x2
    #
    # Note: Remember to (consider to) add an ancilla constraint to make y0=x0x1
    #

    def reduceCubicTerm(self, P, x, y, W):

        # Generate the following terms from x and y
        # P(x0x1 -2x0y0 -2x1y0 +3y0) + Wy0x2     Note: x2 may be an array of n remaining terms requiring further reduction
        self.add([x[0],x[1]], P,  1)
        self.add([x[0],y[0]], P, -2)
        self.add([x[1],y[0]], P, -2)
        self.add([y[0]],      P, +3)
        #self.add(x[2:]+[y[0]], W, 1) # Add the remaining term with the substituted variable
        self.add([y[0]]+x[2:], W, 1) # Add the remaining term with the substituted variable
        #return(exp)

    def varkey(self,variables):
        key = ""
        for v in variables:
            key = key + "x" + str(v)
        return(key)

    # Invert binary variables in all terms
    # Note: Most useful when inverting the one initial term.

    def invertBinary(self, P=1, Y=100):
        newterms = []
        #print("Reducing expression order", self.order)
        for i,t in enumerate(self.terms):
            # Invert the term, add returned new terms
            newterms.extend(self.inv_exp(P*t.W, t.vars))
            self.terms[i]=None

        # Move new terms into expression
        for (w,a) in newterms:
            self.add(a, 1, w)
        self.trim()
        return(Y)

    # Reduce HighOrder term.
    # If order > 3, perform y0=x0x1 substitution and recur to reduce the rest further
    # if order == 3,

    def reduceHighOrder(self,term,Y,P=1):
        # Terms within quadratic order remain as is
        if ( term.getOrder() <= 2 ):
            self.add(term.vars, 1, term.W)
            return(Y)

        # Find out if we have reduced this term
        # before. If we have, obtain the substitution
        # variables. If not, create a new one

        key = self.varkey(term.vars[0:2])

        if ( key in self.substitutions ):
            y = [self.substitutions[key]]
            #print("Reusing reduction: ", key + " =>" + str(y[0]) )
        else:
            # Higher order term needs to be reduced
            # Add a new variable
            y = [Y,] # new Y variable added
            Y += 1   # position for next variable
            self.newvars.extend(y)
            self.substitutions[key] = y[0]
            #print("added new variable to the list: ", self.newvars)
            #print("next var will be: ", Y )

            # NOTE: Impose this penalty only once at creation of the substitution.
            #       Do not repeat each time it is used so this must be in the
            #       "else" portion of the subs lookup
            # Impose a penalty term P(x0x1 -2x0y0 -2x1y0 +3y0)
            self.reduceCubicTerm(P, term.vars, y, term.W)

        # Return the next variable position
        return(Y)

    # Working our way from the start of the terms array
    # down to the end, replace each term having N >= 3 variables
    # with a reduced equivalent series, bring the expression down to a Quadratic version

    def reduceExpression(self, P=1, Y=100):
        while ( self.getExpressionOrder() >= 3):
            #print("Reducing expression order", self.order)
            for i,t in enumerate(self.terms):
                if ( t is not None):
                    if ( t.getOrder() > 2 ):
                        #print("Reducing:",t.__dict__)
                        #exp = self.reduceCubicTerm(P,t.vars,[Y],t.W)
                        Y = self.reduceHighOrder(t,Y,P=P)
                        self.terms[i]=None
                        #self.print()
        self.trim()
        return(Y)

    # create a Qubo / Upper triangle method for the current expression
    # Will only return a Qubo for order 2 or less expressions
    # Variable ids are assumed as 1 origin and placed in Qubo using 0 origin

    def qubo(self):
        if ( self.getExpressionOrder()>2): return None
        Q = defaultdict(float)
        for t in self.terms:
            if ( t is not None ):

                # Linear Qii terms
                if ( len(t.vars) == 1 ):
                    i = t.vars[0]
                    if ( not (i,i) in Q ):
                        Q[(i,i)] = 0.0
                    Q[(i,i)] += t.W
                    #print("Q%d%d=%d" % (i,i,Q[(i,i)]))

                # Quadratic Qij terms
                if ( len(t.vars) == 2 ):
                    (i,j) = tuple(sorted([t.vars[0], t.vars[1]]))
                    if ( not (i,j) in Q ):
                        Q[(i,j)] = 0.0
                    Q[(i,j)] += t.W
                    #print("Q%d%d=%d" % (i,j,Q[(i,j)]))
        return (Q)

    def applyQubo(self,Q):
        if ( self.getExpressionOrder()<3 ):
            for t in self.terms:
                if ( t is not None ):

                    # Linear Qii terms
                    if ( len(t.vars) == 1 ):
                        i = t.vars[0]
                        if ( not (i,i) in Q ):
                            Q[(i,i)] = 0.0
                        Q[(i,i)] += t.W
                        #print("Q%d%d=%d" % (i,i,Q[(i,i)]))

                    # Quadratic Qij terms
                    if ( len(t.vars) == 2 ):
                        (i,j) = tuple(sorted([t.vars[0], t.vars[1]]))
                        if ( not (i,j) in Q ):
                            Q[(i,j)] = 0.0
                        Q[(i,j)] += t.W
                        #print("Q%d%d=%d" % (i,j,Q[(i,j)]))
        else:
            print("Warning: Attempting to apply unreduced higher order expression to a Qubo")


import cv2
import numpy as np

def Convert2BinaryImage(img, threshold, mode=0):
    height = img.shape[0]
    width = img.shape[1]
    #convert grayscale into binary image, threshold is 128
    value = 255
    if mode == 1:
        value = 1
    for row in range(height):
        for col in range(width):
            pix = img[row][col]
            if pix >= threshold:
                img[row][col] = value
            else:
                img[row][col] = 0
    return img

def DownSampling(img, size):
    (height, width) = size
    ratio_x = int(img.shape[1] / width)
    ratio_y = int(img.shape[0] / height)
    result = np.ones((height, width))
    for row in range(height):
        for col in range(width):
            result[row][col] = img[row*ratio_y][col*ratio_x]
    return result

def H(b, c, d, e):
    if b == c and (d != b or e != b):
        return 'q'
    if b == c and d == b and e == b:
        return 'r'
    if b != c:
        return 's'

def YokoiConnNum(img):
    height, width = img.shape
    ans = np.zeros((height, width))
    print(height, width)
    for row in range(height):
        for col in range(width):
            ans[row][col] = -1
            if img[row][col] == 0:
                continue
            neighbors = [0] * 9
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if row+i >= 0 and row+i < height and col+j >= 0 and col+j < width:
                        if img[row+i][col+j] != 0:
                            neighbors[(i+1)*3+j+1] = 1
            a1 = H(neighbors[4], neighbors[5], neighbors[2], neighbors[1])
            a2 = H(neighbors[4], neighbors[1], neighbors[0], neighbors[3])
            a3 = H(neighbors[4], neighbors[3], neighbors[6], neighbors[7])
            a4 = H(neighbors[4], neighbors[7], neighbors[8], neighbors[5])
            A = [a1, a2, a3, a4]
            nq = A.count('q')
            nr = A.count('r')
            if nr == 4:
                ans[row][col] = 5
            else:
                ans[row][col] = nq

    return ans

if __name__ == '__main__':

    filename = 'lena.bmp'
    img = cv2.imread(filename, 0)
    img = Convert2BinaryImage(img, 128)
    small_img = DownSampling(img, (64, 64))
    #cv2.imwrite('img.bmp', small_img)
    ans = YokoiConnNum(small_img)

    f = open('yokoi.txt', 'w')
    for line in ans:
        for ch in line:
            if ch == -1:
                f.write(' ')
            else:
                f.write(str(ch))
        f.write('\n')
    f.close()


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

from pyfeedbacker.app.controller import base

import sys

class Controller(base.BaseController):
    def __init__(self, submission):
        """Controller for deleting the outcomes for a submission."""
        super().__init__()

        self.submission      = submission

    def start(self):
        deleted = False

        try:
            del self.model.feedbacks[self.submission]
            deleted = True
        except KeyError:
            sys.stderr.write(
                f'No feedback for submission "{self.submission}".\n')
        try:
            del self.model.outcomes[self.submission]
            deleted = True
        except KeyError:
            sys.stderr.write(
                f'No outcomes for submission "{self.submission}".\n')

        if deleted:
            self.model.save()
            print(f'Submission {self.submission} deleted.')


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

# 使用 asyncio 实现Hello world

import asyncio

@asyncio.coroutine
# 把一个generator 标记为 coroutine 类型 然后扔到 EventLoop 执行
def hello():
	print ('Hello world')
	# 异步调用 asyncio.sleep(1)
	r = yield from asyncio.sleep(1)
	# asyncio.sleep() 也是一个 coroutine
	# 执行时线程不会等待该操作 而是直接中断 并执行下一个消息循环
	# 把此句看作为 耗时 一秒的操作 即可

	print ('Hello again')

# 获取 EventLoop
loop = asyncio.get_event_loop()
# 直接获取一个 EventLoop 引用

# 执行 coroute
loop.run_until_complete(hello())
# 把要执行的协程扔到 EventLoop中执行  实现异步IO

loop.close()


token = ''
token_ai = ''

arr_faculty = ["ИКН", "ЭкоТех", "ИНМиН", "ГИ", "ЭУПП", "ИБО", "ИНОБР"]
arr_directions = {"ИКН": ["ИВТ", "ПМ", "БИ"], "ЭкоТех": ["КИ", "ПВОК", "ПМИО", "СПМИП"], "ИНМиН": ["Ф", "НИН"],
                  "ГИ": ["ЭИЭ", "ГД", "ФПГИНП", "М", "ТМИО", "ТБ", "ЭИЭ"], "ЭУПП": ["ЭИУ", "ТГ"],
                  "ИБО": ["МИМ", "ФИА", "ЭРСС", "ЭТ", "М"], "ИНОБР": ["МЧМ", "МЦМ", "ЛПЧЦМ", "ОМД", "ПМКМП", "ИСТ", "ЭУНП"]}
arr_degree = {"Бакалавр": ["1", "2", "3", "4"], "Магистр": ["1", "2"], "Специалист": ["1", "2", "3", "4", "5"]}

arr_hobby = {"🎨Творчество🎨": ["Фотографии", "Видеосъёмка", "Музыка", "Рукоделие", "Рисование", "Танцы"],
             "🎬Хобби🎬": ["Компьютерные игры", "Кино и сериалы", "Книги", "Кулинария"],
             "⚽Спорт⚽": ["Футбол", "Баскетбол", "Волейбол", "Хоккей", "Фитнес", "Йога"],
             "📚Учёба📚": ["Математика", "Физика", "Программирование", "Вычислительные машины", "Английский"]
             }
arr_varia = {"Домашние животные": ["Кошка", "Собака", "Хомяк", "Рыбка"],
             "Любимая еда": ["Пельмени", "Пицца", "Шаурма", "Сладости"],
             "Любимые мемы": ["Мем 1", "Мем 2", "Мем 3", "Мем 4"]}
arr_search = ["Подготовка к сессии", "Поиск по интересам", "Поиск по родному городу", "Поиск компании для прогулки"]
arr_place = ['Парк', "Кино", "Музей", "Театр", "Cпортивные мероприятия"]

if __name__ == '__main__':
    for i in arr_hobby:
        print(i)
        print(*arr_hobby[i], sep="\n")


import tasks
import csv
import shutil
import os

from tasks import long_task
from flask import Flask, render_template, request, jsonify, Response, url_for
from utils import items_to_csv

# ---------------------------- #
#           GLOBAL             #
# ---------------------------- #

app = Flask(__name__)
app.secret_key = "EuropeanaOnTheFly"

RESULT = None

# ---------------------------- #
#           VIEWS              #
# ---------------------------- #

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/runTask", methods=['POST'])
def longtask():
    if request.method == 'POST':
        usr_data = request.json
        usr_data.update({'root': app.root_path})

        # Execute background task
        task = tasks.long_task.delay(usr_data=request.json)

        print('Background task just started')
        print(usr_data)

        return jsonify({}), 202, {'Location': url_for('taskstatus',
                                                      task_id=task.id)}

    else:
        render_template('index.html')

@app.route('/status/<task_id>')
def taskstatus(task_id):
    task = long_task.AsyncResult(task_id)

    # Background task at work
    if task.state == 'working':
        print('RECEIVED STATE : working')
        response = {
            'state': task.state,
            'info': task.info
        }

    # Background task is done
    elif task.state == 'SUCCESS':

        print('RECEIVED STATE : SUCCESS')
        result = task.info['info']

        # The api call returned something
        if result['query_status'] is True:
            print('No data found in query result')
            # No results found after api call
            if result['data'] is None:
                response = {
                    'state': 'empty',
                    'dir': result['dir']
                }

            # Data available after api call
            else:
                print('data available in query result')
                print('SENDING TASK')
                print(result['dir'])
                print(os.listdir('{}/public/'.format(app.root_path)))

                if not os.path.isdir('{}/public/{}/'.format(app.root_path, result['dir'])):
                    os.mkdir('{}/public/{}/'.format(app.root_path, result['dir']))
                    items_to_csv(result['data'],
                                 '{}/public/{}/output.csv'.format(app.root_path, result['dir']))

                response = {
                    'state': 'loaded',
                    'data': result['data'],
                    'dir': result['dir']
                }

        # There was an error during api call
        else:
            response = {
                'state': 'error',
                'dir': result['dir'],
                'error': result['error']
            }

    # Something went wrong the the background task
    else:
        print('unseen query state :', task.state)
        response = {
            'state': 'error',
            'dir': '',
            'error': 'Problème lors de la gestion de la requête'
        }

    return jsonify(response)

@app.route('/display/<dir_name>', methods=['GET', 'POST'])
def display(dir_name):

    # Read csv to display
    f_path = app.root_path + '/public/' + dir_name + '/output.csv'
    try:
        with open(f_path) as f:
            items = [i for i in csv.DictReader(f)]
    except FileNotFoundError:
        print(f_path)
        print(os.listdir('{}/public/'.format(app.root_path)))

    # Create download urls
    csv_url = '/download-csv/' + dir_name
    json_url = '/download-json/' + dir_name
    xml_url = '/download-xml/' + dir_name

    # Render template
    return render_template('display.html',
                           items=items, dir=dir_name,
                           json=json_url, csv=csv_url, xml=xml_url,
                           len=len(items))

@app.route('/cleaning/<dir_name>', methods=['GET', 'POST'])
def clean(dir_name):
    print('Cleaning demand received')
    if request.method == 'POST':
        try:
            dir_path = app.root_path + '/public/' + dir_name
            shutil.rmtree(dir_path)
            print(dir_name, ' has been removed !')
        except Exception as e:
            print('An error occured during dir cleaning : ')
            print(e)
    return '', 204

# ---------------------------- #
#         DOWLOAD VIEWS        #
# ---------------------------- #

@app.route('/download-csv/<dir_name>', methods=['GET', 'POST'])
def download_csv(dir_name):
    print('demande de téléchargement pour :', dir_name)
    file_path = app.root_path + '/public/' + dir_name + '/output.csv'
    with open(file_path) as f:
        data = f.read()
    return Response(
        data,
        mimetype="text/csv",
        headers={"Content-disposition":
                 "attachment; filename=europeana_data.csv"})

@app.route('/download-json/<dir_name>', methods=['GET', 'POST'])
def download_json(dir_name):
    print('demande de téléchargement pour :', dir_name)
    file_path = app.root_path + '/public/' + dir_name + '/output.json'
    with open(file_path) as f:
        data = f.read()
    return Response(
        data,
        mimetype="text/json",
        headers={"Content-disposition":
                 "attachment; filename=europeana_data.json"})

@app.route('/download-xml/<dir_name>', methods=['GET', 'POST'])
def download_xml(dir_name):
    print('demande de téléchargement pour :', dir_name)
    file_path = app.root_path + '/public/' + dir_name + '/output.xml'
    with open(file_path) as f:
        data = f.read()
    return Response(
        data,
        mimetype="text/xml",
        headers={"Content-disposition":
                 "attachment; filename=europeana_data.xml"})

# @app.errorhandler(Exception)
# def handle_error(e):
#     code = 500
#     if isinstance(e, HTTPException):
#         code = e.code
#     return render_template('error.html')

# ---------------------------- #
#           MAIN               #
# ---------------------------- #

if __name__ == "__main__":

    app.run(debug=True)


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

"""The setup script."""

from setuptools import find_packages, setup

with open("requirements.txt") as f:
    reqs = f.read().splitlines()

description = """Benchmark of the data augmentation libraries"""

setup(
    author="Aleksei Tiulpin",
    author_email="aleksei.tiulpin@oulu.fi",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Science/Research",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Operating System :: MacOS",
        "Operating System :: POSIX :: Linux",
    ],
    description="Benchmark of different data augmentation libraries",
    install_requires=reqs,
    license="MIT license",
    long_description=description,
    include_package_data=True,
    keywords="data augmentations, deeep learning",
    name="augbench",
    packages=find_packages(include=["augbench"]),
    setup_requires=(),
    url="https://github.com/mipt-oulu/solt/benchmark",
    version="0.1.9",
    zip_safe=False,
)


import typing

import s2sphere  # type: ignore

def create_latlng(lat: float, lng: float) -> s2sphere.LatLng:
    """Create a LatLng object from float values

    :param lat: latitude
    :type lat: float
    :param lng: longitude
    :type lng: float
    :return: LatLng object
    :rtype: s2sphere.LatLng
    """
    return s2sphere.LatLng.from_degrees(lat, lng)

def parse_latlng(s: str) -> s2sphere.LatLng:
    """Parse a string with comma separated latitude,longitude values and create a LatLng object from float values

    :param s: string with latitude,longitude values
    :type s: str
    :return: LatLng object
    :rtype: s2sphere.LatLng
    :raises ValueError: raises a value error if the format is wrong
    """
    a = s.split(",")
    if len(a) != 2:
        raise ValueError(f'Cannot parse coordinates string "{s}" (not a comma-separated lat/lng pair)')

    try:
        lat = float(a[0].strip())
        lng = float(a[1].strip())
    except ValueError as e:
        raise ValueError(f'Cannot parse coordinates string "{s}" (non-numeric lat/lng values)') from e

    if lat < -90 or lat > 90 or lng < -180 or lng > 180:
        raise ValueError(f'Cannot parse coordinates string "{s}" (out of bounds lat/lng values)')

    return create_latlng(lat, lng)

def parse_latlngs(s: str) -> typing.List[s2sphere.LatLng]:
    """Parse a string with multiple comma separated latitude,longitude values and create a list of LatLng objects

    :param s: string with multiple latitude,longitude values separated with empty space
    :type s: str
    :return: list of LatLng objects
    :rtype: typing.List[s2sphere.LatLng]
    """
    res = []
    for c in s.split():
        c = c.strip()
        if len(c) > 0:
            res.append(parse_latlng(c))
    return res

def parse_latlngs2rect(s: str) -> s2sphere.LatLngRect:
    """Parse a string with two comma separated latitude,longitude values and
    create a LatLngRect object

    :param s: string with two latitude,longitude values separated with empty space
    :type s: str
    :return: LatLngRect from LatLng pair
    :rtype: s2sphere.LatLngRect
    :raises ValueError: exactly two lat/lng pairs must be given as argument
    """
    latlngs = parse_latlngs(s)
    if len(latlngs) != 2:
        raise ValueError(f'Cannot parse coordinates string "{s}" (requires exactly two lat/lng pairs)')

    return s2sphere.LatLngRect.from_point_pair(latlngs[0], latlngs[1])


# -*- coding: utf-8 -*-
# @Time    : 2023/4/18 上午8:08
# @Author  : Su Yang
# @File    : agent.py
# @Software: PyCharm
# @Comment : base class of the agent class
import uuid

from jarvis.memory import get_memory, Memory

class Agent(object):
    def __init__(self,
                 ai_name: str = 'Jarvis',
                 memory: Memory = get_memory(),
                 history: list = None,
                 prompt='你是一个私人的AI助手'):
        if history is None:
            history = []
        self.ai_name = ai_name
        self.memory = memory
        self.history = history
        self.prompt = prompt
        self.id = str(uuid.uuid4())

    def clear_history(self):
        self.history.clear()


T = int(input())

for tc in range(1, T+1):
    N, M = map(int, input().split()) # 화덕 크기 N, 피자 수 M
    q = [] # 큐
    M_list = list(map(int, input().split()))

    # 화덕에 N개의 피자 넣기
    idx = 0
    while idx < N:
        q.append([M_list[idx]//2, idx]) # 큐에 [처음치즈양//2, 피자번호-1]로 담긴다.
        idx += 1

    # 화덕 돌리기
    while q: # 화덕에 피자가 있으면 반복
        temp = q.pop(0)
        if temp[0] != 0: # 꺼낸 피자 치즈양이 0이 아니면 //2 해서 다시 넣는다.
            temp[0] = temp[0]//2
            q.append(temp)
        else: # 꺼낸 피자가 0일 때 M_list에 남는 피자가 있으면 넣고, 아니면 0을 넣는다.
            if idx == M:
                pass
            else:
                q.append([M_list[idx]//2, idx])
                idx += 1

    print(f'#{tc} {temp[1]+1}') # 마지막 반복될때의 temp가 마지막 피자를 의미


'''fetch ec2 public ips'''
import boto3

ec2 = boto3.resource('ec2')

def main():
    filters=[{
        'Name': 'instance-state-name',
        'Values': ['running']}]
    instances = ec2.instances.filter(Filters=filters)

    instance_ips = []
    for instance in instances:
        has_fabric_tag = False
        for tags in instance.tags:
            if tags['Value'] == 'fabric':
                has_fabric_tag = True

        if has_fabric_tag == False:
            continue

        for tags in instance.tags:
            if tags['Key'] == 'Type':
                instance_host = tags['Value']

        ip = instance.public_ip_address
        print('[' + instance_host +']')
        print(ip)
        print()

        instance_ips.append(instance.public_ip_address)

    print('[all]')
    for ip in instance_ips:
        print(ip)

if __name__ == '__main__':
    main()


import multiprocessing

workers = multiprocessing.cpu_count() * 2 + 1
bind = '0.0.0.0:18000'
proc_name = 'tsf_gunicorn'
pidfile = '/tmp/tsf_gunicorn.pid'
logfile = '/tmp/tsf_gunicorn.log'
worker_class = 'gevent'
debug = True
daemon = True


import os
import traceback

from flask import jsonify, request
from flask.views import MethodView
from werkzeug.exceptions import HTTPException
from werkzeug.utils import secure_filename

from waiter.azure_sdk import FlaskBlobServiceClient, FlaskCosmosClient
from waiter.utils import create_app
from waiter.api_schemas import APIStatus, APIError, APISchema, PersistImageRequest, ImageFile
from waiter.config import ApplicationConfig
from waiter.image_persistor import ImagePersistor
from waiter.image_retriever import ImageRetriver

class APIException(HTTPException):
    code = 400

app = create_app(__name__, config=ApplicationConfig())

blob_service = FlaskBlobServiceClient.init_app(app)
cosmos = FlaskCosmosClient.init_app(app)

@app.errorhandler(Exception)
def handle_api_exception(e):
    if isinstance(e, HTTPException):
        error = APIError(
            message=e.name,
            description=e.description,
            status_code=e.code,
            inner_error=traceback.format_exception_only(type(e), e)
        )
        status_code = e.code
    else:
        try:
            name = e.name
            description = e.description
            status_code = 500
        except Exception as esc:
            name = "Unknown Exception"
            description = "Server Encountered an Error Processing your request. Please try again after some time"
            status_code = 500
        error = APIError(
            message=name,
            description=description,
            status_code=status_code,
            inner_error=traceback.format_exception_only(type(e), e)
        )
    response = APISchema(
        status=APIStatus.FAILED,
        errors=[error],
        status_code=status_code
    )
    return jsonify(response.to_json()), response.status_code

class ImageAPI(MethodView):

    def get(self):
        # query image properties from cosmos
        try:
            images = ImageRetriver.get_image(db=cosmos)
            app.logger.info("Found %d images" % len(images))
            response = APISchema(
                status=APIStatus.SUCCESS,
                data=images
            )
        except Exception as exc:
            error = APIError(
                message="Failed to fetch image",
                description=str(exc)
            )
            response = APISchema(
                status=APIStatus.FAILED,
                errors=[error]
            )

        return jsonify(response.to_json()), response.status_code

    def post(self):
        # get image data
        # save image in cosmos
        # upload file to azure storage
        image = request.files.get("image", None)
        if image is None:
            raise APIException("Could not find image file to upload")
        filename = secure_filename(image.filename)
        image_file = ImageFile(
            local=True,
            filename=filename,
            path=os.path.join(app.config["IMAGE_UPLOADS"], filename)
        )
        # save image locally
        app.logger.info(f"Saving {image_file}")
        image.save(image_file.path)
        persist_req = PersistImageRequest(
            file=image_file
        )
        app.logger.info(f"Uploading {image_file}  to blob store")

        image_persistor = ImagePersistor(blob_service=blob_service, db=cosmos)
        try:
            image_persistor.persist_image(persist_req)
            response = APISchema(status=APIStatus.SUCCESS, status_code=201)
        except Exception as exc:

            error = APIError(
                status_code=500,
                message="Failed to save image",
                description=str(exc)
            )
            response = APISchema(status=APIStatus.FAILED, errors=[error], status_code=500)

        return jsonify(response.to_json()), response.status_code

app.add_url_rule('/images/', view_func=ImageAPI.as_view('images'))

if __name__ == "__main__":
    app.run(port=5000, host="0.0.0.0")


# Branch Sums

"""
Write a function that takes in a Binary Tree and returns a list of its branch sums ordered from leftmost branch sum to rightmost branch sum.

A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree branch is a path of nodes in a tree that starts at the root node and ends at any leaf node.

Each BinaryTree node has an integer value, a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null.

Sample Input
tree =             1    <-- root
                 /   \
                2     3
               / \   / \
              4   5 6   7
             / \   \
            8   9  10

Sample Output
[15, 16, 18, 10, 11] // 15 = 1 + 2 + 4 + 8, 16 = 1 + 2 + 4 + 9, 18 = 1 + 2 + 5 + 10, 10 = 1 + 3 + 6, 11 = 1 + 3 + 7

"""

# This is the class of the input root. Do not edit it.
class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def branchSums(root):
    sums = []
    calculateBranchSums(root, 0, sums)
    return sums

# Time: O(n) | Space: O(n)
def calculateBranchSums(node, runningSum, sums):
    if node is None:
        return
    newRunningSum = runningSum + node.value
    if node.left is None and node.right is None:
        sums.append(newRunningSum)
    else:
        if node.left is not None:
            calculateBranchSums(node.left, newRunningSum, sums)
        if node.right is not None:
            calculateBranchSums(node.right, newRunningSum, sums)


import http.client
import random
import re
import string

class Handler:
    def __init__(self, scenario):
        self.host = str
        self.set = str
        self.uri = str
        self.method = str
        self.body = ''
        self.scenario = scenario.splitlines()

    def handle_file(self):
        for line in self.scenario:
            if re.match('Set:.*', line, re.I):
                self.check_post_body()
                self.set = re.match('Set:.?(.*)', line, re.I).group(1)
            elif re.match('Host:.*', line, re.I):
                self.check_post_body()
                self.host = re.match('Host:.?(.*)', line, re.I).group(1)
            elif re.match('(GET) (/.*)', line, re.I):
                self.check_post_body()
                self.method, self.uri = re.match('(GET) (/.*)', line, re.I).group(1, 2)
                self.start_uri_test()
            elif re.match('(POST) (/.*)', line, re.I):
                self.method, self.uri = re.match('(POST) (/.*)', line, re.I).group(1, 2)
                self.check_post_body(start=True)
            elif self.body:
                self.body += line + '\n'

    def check_post_body(self, start=False):
        if self.body:
            self.start_test_with_body()
            self.body = ''
        elif start:
            self.body += '\n'

    def start_test_with_body(self):
        print(self.set)
        print(self.body)

    def start_uri_test(self):
        print(self.set, self.method, self.uri)


import numpy as np
import matplotlib.pyplot as plt
from scipy import special

def vcol(v):
    return v.reshape(v.size,1)
def vrow(v):
    return v.reshape(1,v.size)

def confMat(predLabels,labels,nClasses):
    confMat = np.zeros((nClasses, nClasses))
    #preCor = [(predLabels[i], LTE[i]) for i in range(predLabels.shape[0])]
    for i in range(nClasses):
        predH = predLabels == i
        for j in range(nClasses):
            corrH = labels == j
            confMat[i, j] = np.dot(predH.astype(int), corrH.astype(int).T)
    return confMat

def predictLabels(p1,Cfn,Cfp,llr):
    t = -np.log(p1 * Cfn / ((1 - p1) * Cfp))
    predLabels = llr > t

    return predLabels
def computeBayesRisk(p1,Cfn,Cfp,M):
    FPR=M[1,0]/(M[0,0]+M[1,0])
    FNR=M[0,1]/(M[0,1]+M[1,1])
    DCF=p1*Cfn*FNR+(1-p1)*Cfp*FPR

    return DCF

def computeMinDCF(p1,Cfn,Cfp,llr,labels):
    Bnorm = min(p1 * Cfn, (1 - p1) * Cfp)
    pred_t = [llr > t for t in sorted(llr)]
    M_t = [confMat(pred_t[i], labels, nClasses) for i in range(len(llr))]
    DCF_t = [computeBayesRisk(p1, Cfn, Cfp, M_t[i]) for i in range(len(llr))]
    normDCF_t = np.array(DCF_t) / Bnorm

    return min(normDCF_t)
def computeNormDCF(p1,Cfn,Cfp,llr,labels):
    Bnorm = min(p1 * Cfn, (1 - p1) * Cfp)

    predLabels = predictLabels(p1, Cfn, Cfp, llr)
    confM1 = confMat(predLabels, labels, nClasses)
    DCF = computeBayesRisk(p1, Cfn, Cfp, confM1)
    normDCF = DCF / Bnorm

    return confM1,DCF,normDCF

def computeDCFmulticlass(ll_multiclass,labels_multiclass,pi,C,):
    normCost = np.min(np.dot(C, pi))

    SJoint = ll_multiclass + np.log(pi)
    SMarginal = special.logsumexp(SJoint, axis=0)
    SPost = SJoint - SMarginal
    costVect = np.dot(C, np.exp(SPost))
    predLabels = np.argmin(costVect, axis=0)

    M = confMat(predLabels, labels_multiclass, 3)

    R = M / np.sum(M, axis=0)

    DCF = np.dot(pi.T, np.sum(R * C, axis=0))

    return M,DCF,DCF/normCost

if __name__=='__main__':
    llr_infpar=np.load('Data/commedia_llr_infpar.npy')
    labels_infpar=np.load('Data/commedia_labels_infpar.npy')

    nClasses=2
    p1=0.5
    Cfn=1
    Cfp=1
    Bnorm=min(p1*Cfn,(1-p1)*Cfp)

    confM1,DCF,normDCF1=computeNormDCF(0.5,1,1,llr_infpar,labels_infpar)
    print('Confusion matrix pi1: %.2f Cfn: %d Cfp: %d :\n'%(p1,Cfn,Cfp),confM1)
    print('Bayes risk: ', DCF,' normalized: ',normDCF1)

    confM2, DCF, normDCF2 = computeNormDCF(0.8, 1, 1, llr_infpar, labels_infpar)
    print('Confusion matrix pi1: %.2f Cfn: %d Cfp: %d :\n' % (p1, Cfn, Cfp), confM2)
    print('Bayes risk: ', DCF,' normalized: ',normDCF2)

    confM3, DCF, normDCF3 = computeNormDCF(0.5, 10, 1, llr_infpar, labels_infpar)
    print('Confusion matrix pi1: %.2f Cfn: %d Cfp: %d :\n' % (p1, Cfn, Cfp), confM3)
    print('Bayes risk: ',DCF,' normalized: ',normDCF3)

    p1=0.8
    Cfn=1
    Cfp=10
    confM4, DCF, normDCF4 = computeNormDCF(0.8, 1, 10, llr_infpar, labels_infpar)
    print('Confusion matrix pi1: %.2f Cfn: %d Cfp: %d :\n' % (p1, Cfn, Cfp), confM4)
    print('Bayes risk: ', DCF,' normalized: ',normDCF4)

    minDCF1=computeMinDCF(0.5,1,1,llr_infpar,labels_infpar)
    print('min DCF: ', minDCF1)
    minDCF2 = computeMinDCF(0.8, 1, 1, llr_infpar, labels_infpar)
    print('min DCF: ', minDCF2)
    minDCF3 = computeMinDCF(0.5, 10, 1, llr_infpar, labels_infpar)
    print('min DCF: ', minDCF3)
    minDCF4 = computeMinDCF(0.8, 1, 10, llr_infpar, labels_infpar)
    print('min DCF: ', minDCF4)

    #ROC plot
    pred_t = [llr_infpar > t for t in sorted(llr_infpar)]
    M_t = [confMat(pred_t[i], labels_infpar, nClasses) for i in range(len(llr_infpar))]
    FPR_t=[M_t[i][1,0]/(M_t[i][1,0]+M_t[i][0,0]) for i in range(len(llr_infpar))]
    TPR_t=[1-(M_t[i][0,1]/(M_t[i][0,1]+M_t[i][1,1])) for i in range(len(llr_infpar))]

    fig=plt.figure()
    plt.plot(FPR_t,TPR_t)
    plt.xlabel('FPR')
    plt.ylabel('TPR')
    plt.show()

    effPriorLogOdds = np.linspace(-3, 3,21)
    piVet=1/(1+np.exp(-effPriorLogOdds))

    normDCF_p= [computeNormDCF(piVet[i], 1, 1, llr_infpar, labels_infpar)[2] for i in range(len(piVet))]
    """
    Bnorm = [min(piVet[i], (1 - piVet[i])) for i in range(len(piVet))]
    pred_p = [predictLabels(piVet[i], 1, 1, llr_infpar) for i in range(len(piVet))]
    confM_p = [confMat(pred_p[i], labels_infpar, nClasses) for i in range(len(piVet))]
    DCF_p = [computeBayesRisk(piVet[i], 1, 1, confM_p[i]) for i in range(len(piVet))]
    normDCF_p = [DCF_p[i] / Bnorm[i] for i in range(len(piVet))]
    """
    minDCF_p=[computeMinDCF(piVet[i],1,1,llr_infpar,labels_infpar) for i in range(len(piVet))]

    plt.figure()
    plt.plot(effPriorLogOdds,normDCF_p,label='DCF (ε=0.001)',color='r')
    plt.plot(effPriorLogOdds,minDCF_p,label='min DCF (ε=0.001)',color='b')
    plt.ylim([0,1.1])
    plt.xlim([-3,3])
    plt.xlabel('prior log odds')
    plt.ylabel('DCF value')

    llr_infpar_eps1=np.load('Data/commedia_llr_infpar_eps1.npy')

    normDCF_p_eps1 = [computeNormDCF(piVet[i], 1, 1, llr_infpar_eps1, labels_infpar)[2] for i in range(len(piVet))]
    minDCF_p_eps1 = [computeMinDCF(piVet[i], 1, 1, llr_infpar_eps1, labels_infpar) for i in range(len(piVet))]

    plt.plot(effPriorLogOdds,normDCF_p_eps1,label='DCF (ε=1)',color='y')
    plt.plot(effPriorLogOdds,minDCF_p_eps1,label='min DCF (ε=1)',color='g')
    plt.legend()
    plt.show()

    #MULTICLASS

    ll_multiclass=np.load('Data/commedia_ll.npy')
    labels_multiclass=np.load('Data/commedia_labels.npy')

    C=np.array([[0,1,2],[1,0,1],[2,1,0]])
    pi=vcol(np.array([0.3,0.4,0.3]))

    M,DCF,normDCF=computeDCFmulticlass(ll_multiclass,labels_multiclass,pi,C)

    print('M=\n',M,'DCF_u multiclass: ',DCF,' DCF: ',normDCF)

    ll_multiclass_eps1=np.load('Data/commedia_ll_eps1.npy')

    M_1,DCF_1,normDCF_1=computeDCFmulticlass(ll_multiclass_eps1,labels_multiclass,pi,C)

    print('M=\n',M_1,'DCF_u multiclass (eps=1.0): ', DCF_1, ' DCF (eps=1.0): ', normDCF_1)

    pi=np.array([[1./3.],[1./3.],[1./3.]])
    C=1-np.eye(3)
    M, DCF, normDCF = computeDCFmulticlass(ll_multiclass, labels_multiclass, pi, C)
    M_1, DCF_1, normDCF_1 = computeDCFmulticlass(ll_multiclass_eps1, labels_multiclass, pi, C)

    print('M=\n', M, 'DCF_u multiclass (eps=1.0): ', DCF, ' DCF (eps=1.0): ', normDCF)
    print('M=\n', M_1, 'DCF_u multiclass (eps=1.0): ', DCF_1, ' DCF (eps=1.0): ', normDCF_1)


ROW = 0
COL = 1

class Solution:
    def matrixSumQueries(self, n: int, queries: list[list[int]]) -> int:
        remaining_rows = set(range(n))
        remaining_cols = set(range(n))

        total = 0
        for type,index,val in reversed(queries):
            if type == ROW:
                if index in remaining_rows:
                    total += val * len(remaining_cols)
                    remaining_rows.remove(index)
            else:
                if index in remaining_cols:
                    total += val * len(remaining_rows)
                    remaining_cols.remove(index)

        return total


from tkinter import *

def getvals():
    print("Submittinf form")
    with open("records.txt","a") as f:
        f.write(f"'{namevalue.get()}', '{phonevalue.get()}', '{genderentry.get()}', ' {emergencyvalue.get()}', '{paymentmodevalue.get()}'\n")

root= Tk()
root.geometry("500x300")
root.title("Form")

Label(root,text= "Welcome to Pycharm travels", font="comicsansms 18 bold", pady=15).grid(row=0, column=3)

name = Label(root, text="Name")
phone = Label(root, text="Phone number")
gender = Label(root, text="Gender")
emergency = Label(root, text="Emergency Contact")
paymentmode = Label(root, text= "Payment mode")

name.grid(row=1, column=1)
phone.grid(row=2, column=1)
gender.grid(row=3, column=1)
emergency.grid(row=4, column=1)
paymentmode.grid(row=5, column=1)

namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentmodevalue = StringVar()
foodservice= IntVar()

nameentry = Entry(root, textvariable = namevalue)
phoneentry = Entry(root, textvariable = phonevalue)
genderentry = Entry(root, textvariable = gendervalue)
emergencyentry = Entry(root, textvariable =emergencyvalue)
paymentmodeentry = Entry(root, textvariable = paymentmodevalue)

nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
emergencyentry.grid(row=4, column=3)
paymentmodeentry.grid(row=5, column=3)

foodservices= Checkbutton(text="want to prebook your meals?",variable=foodservice)
foodservices.grid(row=6, column=3)

Button(root, text="SUBMIT", fg="red", command=getvals, borderwidth=5, relief=SUNKEN).grid(row=7, column=3, padx=5)

root.mainloop()


from __future__ import division
from __future__ import print_function

# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import collections
import json
import testing_config  # Must be imported before the module under test.

import flask
import mock
import werkzeug.exceptions  # Flask HTTP stuff.

from google.appengine.api import mail

import settings
from internals import models
from internals import sendemail

class OutboundEmailHandlerTest(testing_config.CustomTestCase):

  def setUp(self):
    self.handler = sendemail.OutboundEmailHandler()
    self.request_path = '/tasks/outbound-email'

    self.to = 'user@example.com'
    self.subject = 'test subject'
    self.html = '<b>body</b>'
    self.sender = ('Chromestatus <admin@%s.appspotmail.com>' %
                   settings.APP_ID)

  @mock.patch('settings.SEND_EMAIL', True)
  @mock.patch('settings.SEND_ALL_EMAIL_TO', None)
  @mock.patch('google.appengine.api.mail.EmailMessage')
  def test_post__prod(self, mock_emailmessage_constructor):
    """On cr-status, we send emails to real users."""
    params = {
        'to': self.to,
        'subject': self.subject,
        'html': self.html,
        }
    with sendemail.app.test_request_context(self.request_path, json=params):
      actual_response = self.handler.process_post_data()

    mock_emailmessage_constructor.assert_called_once_with(
        sender=self.sender, to=self.to, subject=self.subject,
        html=self.html)
    mock_message = mock_emailmessage_constructor.return_value
    mock_message.check_initialized.assert_called_once_with()
    mock_message.send.assert_called_once_with()
    self.assertEqual({'message': 'Done'}, actual_response)

  @mock.patch('settings.SEND_EMAIL', True)
  @mock.patch('google.appengine.api.mail.EmailMessage')
  def test_post__staging(self, mock_emailmessage_constructor):
    """On cr-status-staging, we send emails to an archive."""
    params = {
        'to': self.to,
        'subject': self.subject,
        'html': self.html,
        }
    with sendemail.app.test_request_context(self.request_path, json=params):
      actual_response = self.handler.process_post_data()

    expected_to = 'cr-status-staging-emails+user+example.com@google.com'
    mock_emailmessage_constructor.assert_called_once_with(
        sender=self.sender, to=expected_to, subject=self.subject,
        html=self.html)
    mock_message = mock_emailmessage_constructor.return_value
    mock_message.check_initialized.assert_called_once_with()
    mock_message.send.assert_called_once_with()
    self.assertEqual({'message': 'Done'}, actual_response)

  @mock.patch('settings.SEND_EMAIL', False)
  @mock.patch('google.appengine.api.mail.EmailMessage')
  def test_post__local(self, mock_emailmessage_constructor):
    """When running locally, we don't actually send emails."""
    params = {
        'to': self.to,
        'subject': self.subject,
        'html': self.html,
        }
    with sendemail.app.test_request_context(self.request_path, json=params):
      actual_response = self.handler.process_post_data()

    expected_to = 'cr-status-staging-emails+user+example.com@google.com'
    mock_emailmessage_constructor.assert_called_once_with(
        sender=self.sender, to=expected_to, subject=self.subject,
        html=self.html)
    mock_message = mock_emailmessage_constructor.return_value
    mock_message.check_initialized.assert_called_once_with()
    mock_message.send.assert_not_called()
    self.assertEqual({'message': 'Done'}, actual_response)

class BouncedEmailHandlerTest(testing_config.CustomTestCase):

  def setUp(self):
    self.handler = sendemail.BouncedEmailHandler()
    self.sender = ('Chromestatus <admin@%s.appspotmail.com>' %
                   settings.APP_ID)
    self.expected_to = settings.BOUNCE_ESCALATION_ADDR

  @mock.patch('internals.sendemail.BouncedEmailHandler.receive')
  def test_process_post_data(self, mock_receive):
    with sendemail.app.test_request_context('/_ah/bounce'):
      actual_json = self.handler.process_post_data()

    self.assertEqual({'message': 'Done'}, actual_json)
    mock_receive.assert_called_once()

  @mock.patch('settings.SEND_EMAIL', True)
  @mock.patch('google.appengine.api.mail.EmailMessage')
  def test_receive__user_has_prefs(self, mock_emailmessage_constructor):
    """When we get a bounce, we update the UserPrefs for that user."""
    starrer_3_pref = models.UserPref(
        email='starrer_3@example.com',
        notify_as_starrer=False)
    starrer_3_pref.put()

    bounce_message = testing_config.Blank(
        original={'to': 'starrer_3@example.com',
                  'from': 'sender',
                  'subject': 'subject',
                  'text': 'body'})

    self.handler.receive(bounce_message)

    updated_pref = models.UserPref.get_by_id(starrer_3_pref.key.integer_id())
    self.assertEqual('starrer_3@example.com', updated_pref.email)
    self.assertTrue(updated_pref.bounced)
    self.assertFalse(updated_pref.notify_as_starrer)
    expected_subject = "Mail to 'starrer_3@example.com' bounced"
    mock_emailmessage_constructor.assert_called_once_with(
        sender=self.sender, to=self.expected_to, subject=expected_subject,
        body=mock.ANY)
    mock_message = mock_emailmessage_constructor.return_value
    mock_message.check_initialized.assert_called_once_with()
    mock_message.send.assert_called()

  @mock.patch('settings.SEND_EMAIL', True)
  @mock.patch('google.appengine.api.mail.EmailMessage')
  def test_receive__create_prefs(self, mock_emailmessage_constructor):
    """When we get a bounce, we create the UserPrefs for that user."""
    # Note, no existing UserPref for starrer_4.

    bounce_message = testing_config.Blank(
        original={'to': 'starrer_4@example.com',
                  'from': 'sender',
                  'subject': 'subject',
                  'text': 'body'})

    self.handler.receive(bounce_message)

    prefs_list = models.UserPref.get_prefs_for_emails(
        ['starrer_4@example.com'])
    updated_pref = prefs_list[0]
    self.assertEqual('starrer_4@example.com', updated_pref.email)
    self.assertTrue(updated_pref.bounced)
    self.assertTrue(updated_pref.notify_as_starrer)
    expected_subject = "Mail to 'starrer_4@example.com' bounced"
    mock_emailmessage_constructor.assert_called_once_with(
        sender=self.sender, to=self.expected_to, subject=expected_subject,
        body=mock.ANY)
    mock_message = mock_emailmessage_constructor.return_value
    mock_message.check_initialized.assert_called_once_with()
    mock_message.send.assert_called()


import os
import cv2
import sys
import random
import math
import re
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import skimage
import glob
from mrcnn import utils
from mrcnn import visualize
from mrcnn.visualize import display_images
import mrcnn.model as modellib
from mrcnn.model import log
import tensorflow as tf
sys.path.insert(1, r'C:\Users\andrew\Desktop\home\uni\vision2\ARI3129-Advanced-Vision\maskrcnn-road\samples\custom')
import custom

# Root directory of the project
ROOT_DIR = os.getcwd()

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library

# CHANGE THIS PATH
custom_WEIGHTS_PATH = r'C:\Users\andrew\Desktop\home\uni\vision2\ARI3129-Advanced-Vision\maskrcnn-road\mask_rcnn_object_0080.h5'

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

config = custom.CustomConfig()
custom_DIR = os.path.join(ROOT_DIR, "dataset")

class InferenceConfig(config.__class__):
    # Run detection on one image at a time
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()
config.display()

# Inspect the model in training or inference modes
# values: 'inference' or 'training'
# TODO: code for 'training' test mode not ready yet
TEST_MODE = "inference"

def get_ax(rows=1, cols=1, size=16):
    """Return a Matplotlib Axes array to be used in
    all visualizations in the notebook. Provide a
    central point to control graph sizes.

    Adjust the size attribute to control how big to render images
    """
    _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))
    return ax

# Load test dataset
dataset = custom.CustomDataset()
dataset.load_custom(custom_DIR, "test")

# Must call before using the dataset
dataset.prepare()

print("Images: {}\nClasses: {}".format(len(dataset.image_ids), dataset.class_names))

model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR,
                              config=config)

# Load weights
print("Loading weights ", custom_WEIGHTS_PATH)
model.load_weights(custom_WEIGHTS_PATH, by_name=True)

# Compute VOC-Style mAP @ IoU=0.5
# Running on 10 images. Increase for better accuracy.
image_ids = np.random.choice(dataset.image_ids, len(dataset.image_ids))

# Instanciate arrays to create our metrics
APs = []
precisions_arr = []
recalls_arr = []
overlaps_arr = []
class_ids_arr = []
scores_arr = []

for id in dataset.image_ids:
    # Load image and ground truth data
    image, image_meta, gt_class_id, gt_bbox, gt_mask =\
        modellib.load_image_gt(dataset, config,
                               image_ids[id], use_mini_mask=False)
    molded_images = np.expand_dims(modellib.mold_image(image, config), 0)
    # Run object detection
    results = model.detect([image], verbose=0)
    r = results[0]

    # Compute AP
    AP, precisions, recalls, overlaps =\
        utils.compute_ap(gt_bbox, gt_class_id, gt_mask,
                         r["rois"], r["class_ids"], r["scores"], r['masks'], 1)
    # Append AP to AP array
    APs.append(AP)

    # Append precisions
    for precision in precisions:
        precisions_arr.append(precision)

    # Append recalls
    for recall in recalls:
        recalls_arr.append(recall)

    # Append overlaps
    for overlap in overlaps:
        overlaps_arr.append(overlap)

    # Append class_ids
    for class_id in r["class_ids"]:
        class_ids_arr.append(class_id)

    # Append scores
    for score in r["scores"]:
        scores_arr.append(score)

print("mAP: ", np.mean(APs))
# car: 0.6228839671702139


import pymysql
from pymysql import Error
from .constants import GET_DATABASES_QUERY, CREATE_DATABASE_QUERY, DB_USER, DB_HOST

# MySQL Connection Configuration .. I have set it locally to no pw but you could just add the pw here for your mysql deployment
config = {
    'user': DB_USER,
    'host': DB_HOST
}

def connect_to_database():
    try:
        conn = pymysql.connect(**config)
        if conn.open:
            print('Connected to MySQL server')
            # Check if the database exists
            cursor = conn.cursor()
            cursor.execute(GET_DATABASES_QUERY)
            database_exists = cursor.fetchone()
            if not database_exists:
                # Create the database
                cursor.execute(CREATE_DATABASE_QUERY)
                print('Created new database')
            # Connect to the database
            config['database'] = 'flask_task'
            conn = pymysql.connect(**config)
            if conn.open:
                print('Connected to MySQL database')
                # Check if the database is empty
                cursor = conn.cursor()
                cursor.execute("SHOW TABLES")
                if not cursor.fetchall():
                    # Execute the schema SQL statements
                    with open('db/schema.sql', 'r') as f:
                        sql_statements = f.read()
                        cursor = conn.cursor()
                        statements = sql_statements.split(';')
                        for statement in statements:
                            if statement.strip() != '':
                                cursor.execute(statement)
                                while cursor.nextset():
                                    pass
                        print('Schema SQL statements executed successfully')
            return conn
    except Error as e:
        print(f'Error connecting to MySQL database: {e}')


import requests

from bs4 import BeautifulSoup

# Examples
# index = 1
# url = "https://www.grammarly.com/blog/articles/"

index = int(input())
url = input()

r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

subtitles = soup.find_all('h2')
print(subtitles[index].text)

Topics/BeautifulSoup  working with HTML/Get the Subtitles/main.py


from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.common.keys import Keys
from behave import given, when, then

SEARCH_INPUT = (By.ID, 'twotabsearchtextbox')
SEARCH_SUBMIT = (By.XPATH, "//input[@value ='Go']")
RESLTS_INFO_TEXT = (By.CSS_SELECTOR, ".a-color-state.a-text-bold")

@given('Open Amazon page')
def open_amazon(context):
    context.driver.get('https://www.amazon.com/')

@when('Input {search_word} into search field')
def input_search(context, search_word):
    search = context.driver.find_element(*SEARCH_INPUT)
    search.clear()
    search.send_keys(search_word)
    sleep(4)

@when('Click to search')
def click_search_icon(context):
    context.driver.find_element(*SEARCH_SUBMIT).click()
    sleep(2)

@then('Product results for {search_word} are shown')
def verify_found_results_text(context, search_word):
    search_result_header = context.driver.find_element(*RESLTS_INFO_TEXT).text
    assert 'Dress' in search_result_header, f"Incorrect header: {search_result_header}"


import simple_draw as sd

def draw_bunches(start_point, angle, length, color):
    if length < 15:
        color = sd.COLOR_GREEN
    if length < 3:
        return
    v1 = sd.get_vector(start_point=start_point, angle=angle, length=length, width=1)
    v1.draw(color)
    angle1 = (angle - 30) * (1 + (sd.random_number(-2, 2) / 100))
    angle2 = (angle + 30) * (1 + (sd.random_number(-2, 2) / 100))
    next_point = v1.end_point
    next_length = length * 0.75 * (1 + (sd.random_number(-2, 2) / 100))
    draw_bunches(start_point=next_point, angle=angle1, length=next_length, color=color)
    draw_bunches(start_point=next_point, angle=angle2, length=next_length, color=color)

def tree():
    tree_clear = sd.get_point(700, 0)
    sd.square(tree_clear, side=550, color=sd.background_color, width=0)
    root_point = sd.get_point(900, 30)
    color = sd.COLOR_DARK_YELLOW
    draw_bunches(start_point=root_point, angle=90, length=80, color=color)

def tree2():
    root_point = sd.get_point(1100, 00)
    color = sd.COLOR_DARK_RED
    draw_bunches(start_point=root_point, angle=90, length=50, color=color)


# from torch.utils.data import DataLoader, TensorDataset, Dataset
import pandas as pd
import numpy as np
import torch

def normalize(*datasets, scale_factor=10000, low_range=1, high_range=99):
    datasets_list = list(datasets)
    for i in range(len(datasets_list)):
        datasets_list[i] = torch.Tensor(datasets_list[i])
        datasets_list[i] = datasets_list[i] / torch.sum(datasets_list[i], dim=0, keepdim=True) * scale_factor
        datasets_list[i] = torch.log2(datasets_list[i] + 1)

        # Filter genes by expression level
        expr = torch.sum(datasets_list[i], dim=1)
        expr_low = torch.kthvalue(expr, int(len(expr) * low_range / 100)).values
        expr_high = torch.kthvalue(expr, int(len(expr) * high_range / 100)).values
        expr_mask = (expr >= expr_low) & (expr <= expr_high)
        datasets_list[i] = datasets_list[i][expr_mask, :]

        # Filter genes by coefficient of variation
        mean = torch.mean(datasets_list[i], dim=1, keepdim=True)
        std = torch.std(datasets_list[i], dim=1, keepdim=True)
        cv = std / (mean + 1e-10)
        # cv = torch.squeeze(cv)
        cv = cv.squeeze(-1)
        cv_low = torch.kthvalue(cv, int(len(cv) * low_range / 100)).values
        cv_high = torch.kthvalue(cv,int(len(cv) * high_range / 100)).values
        cv_mask = (cv >= cv_low) & (cv <= cv_high)
        datasets_list[i] = datasets_list[i][cv_mask, :]
    if len(datasets_list) == 1:
        return datasets_list[0]
    return datasets_list

#
# data = np.random.rand(20000, 10000)
#
# tensor = torch.from_numpy(data).float().cuda()
#

device = torch.device("cuda:0" if (torch.cuda.is_available()) else "cpu")

dataset1 = pd.read_hdf('G:/actinn_dataset/tma_10x_cleaned.h5', key="dge")
# label1 = pd.read_csv('G:/actinn_dataset/tma_10x_cleaned_label.txt', header=None, sep='\t')
dataset1 = dataset1.iloc[:,:9000]
dataset1 = np.array(dataset1.values, dtype=np.float32)

tensor = torch.from_numpy(dataset1).float().to(device)

# 假设这里使用的是一个名为normalize的预处理函数
for i in range(10000):
    print(f"第 {i + 1} 次计算:")
    a = normalize(tensor)
    # tensor = tensor.to('GPU')
    print(a)
#
# class MyDataset(Dataset):
#     def __init__(self, dataset, label, train=True, percentage:float = 0.8, transform=False):
#         self.dataset = dataset
#         self.label = label
#         self.if_train = train
#         self.percentage = percentage
#         self.transform = transform
#         self.dataset_len = dataset.shape[1]
#
#         if 0 <= self.percentage <= 1:
#             if self.if_train:
#                 self.sample_num = list(range(int(self.dataset_len * percentage)))  # 用前800个样本作为训练集
#             else:
#                 self.sample_num = list(
#                     range(int(self.dataset_len * (1 - percentage)), self.dataset_len))  # 用后200个样本作为测试集
#         else:
#             raise ValueError("percentage范围: [0,1]")
#
#     def __len__(self):
#         return len(self.sample_num)
#
#     def __getitem__(self, index):
#         sample = self.dataset[:, self.sample_num[index]]
#         label = self.label[self.sample_num[index]]
#
#         if self.transform:
#             n = int(np.sqrt(len(sample)))  # 计算方形矩阵边长
#             w = n
#             h = n
#             if w * h == len(sample):
#                 sample = sample.reshape(w, h)  # 转为方形矩阵
#             else:
#                 while w * (h + 1) < len(sample):
#                     h += 1
#                 sample = np.pad(sample, (0, w * (h + 1) - len(sample)), mode='constant', constant_values=0)  # 填充0
#                 sample = sample.reshape(w, h + 1)  # 转为方形矩阵
#                 sample = sample.reshape(1, *sample.shape)
#         return torch.Tensor(sample)  # , torch.Tensor(label)
#
#
# # Define normalization function
# def normalize(x):
#     mean = torch.mean(x, dim=0)
#     std = torch.std(x, dim=0)
#     return (x - mean) / std
#
#
# # Load data from HDF5 file
# dataset1 = pd.read_hdf('G:/test_data/train_set.h5', key="dge")
# label1 = pd.read_csv('G:/test_data/train_label.txt', header=None, sep='\t')
#
#
# dataset1 = np.array(dataset1.values, dtype=np.float32)
#
# # Convert data to PyTorch tensors and move to GPU
# # train_set = torch.from_numpy(dataset1.values).float().to('cuda')
# train_set = torch.tensor(dataset1)
# train_set = train_set.to('cuda:0')
#
# # Normalize data
# train_set = normalize(train_set)
#
# # Create TensorDataset from PyTorch tensor
# dataset = TensorDataset(train_set)
#
# # Create DataLoader and move to GPU
# batch_size = 256
# data_set = MyDataset(dataset, percentage=1)
# dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, pin_memory=False)
#
# # Define model architecture
# model = torch.nn.Sequential(
#     torch.nn.Linear(100, 50),
#     torch.nn.ReLU(),
#     torch.nn.Linear(50, 25),
#     torch.nn.ReLU(),
#     torch.nn.Linear(25, 6),
# )
#
# # Define loss function and optimizer
# criterion = torch.nn.CrossEntropyLoss().to('cuda')
#
# optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.001)
#
# # Train model
# for epoch in range(10):
#     for data in dataloader:
#         # Forward pass
#         y_pred = model(data)
#
#         # Compute loss
#         # loss = criterion(y_pred, y_batch)
#
#         # Backward pass and optimization
#         # optimizer.zero_grad()
#         # # loss.backward()
#         # optimizer.step()
#
#     # Print progress
#     # print(f'Epoch {epoch + 1}, loss = {loss.item():.4f}')

# import h5py
# import torch
# from torch.utils.data import DataLoader, TensorDataset
#
#
# # Define normalization function

# def normalize(x):
#     mean = torch.mean(x, dim=0)
#     std = torch.std(x, dim=0)
#     return (x - mean) / std

#
#
# # Load data from HDF5 file
# with h5py.File('data.h5', 'r') as f:
#     x_train = f['x_train'][()]
#     y_train = f['y_train'][()]
#
# # Convert data to PyTorch tensors and move to GPU
# x_train = torch.from_numpy(x_train).float().to('cuda')
# y_train = torch.from_numpy(y_train).long().to('cuda')
#
# # Normalize data
# x_train = normalize(x_train)
#
# # Create TensorDataset from PyTorch tensor
# dataset = TensorDataset(x_train, y_train)
#
# # Create DataLoader and move to GPU
# batch_size = 32
# dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, pin_memory=True)
#
# # Define model architecture
# model = torch.nn.Sequential(
#     torch.nn.Linear(10, 50),
#     torch.nn.ReLU(),
#     torch.nn.Linear(50, 2),
# )
#
# # Define loss function and optimizer
# criterion = torch.nn.CrossEntropyLoss()
# optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
#
# # Train model
# for epoch in range(10):
#     for x_batch, y_batch in dataloader:
#         # Forward pass
#         y_pred = model(x_batch)
#
#         # Compute loss
#         loss = criterion(y_pred, y_batch)
#
#         # Backward pass and optimization
#         optimizer.zero_grad()
#         loss.backward()
#         optimizer.step()
#
#     # Print progress
#     print(f'Epoch {epoch + 1}, loss = {loss.item():.4f}')


import torch
import numpy as np

def make_monitor_fn():
    def evaluate_fn(model):
        param_norm = torch.norm(torch.stack([torch.norm(param) for param in model.parameters()]))
        return [param_norm]
    return evaluate_fn

def make_evaluate_fn(dataloader, device, eval_type="accuracy", n_classes=0, loss_fn=None):
    if eval_type == "accuracy":
        def evaluate_fn(model):
            with torch.autograd.no_grad():
                n_data = 0
                n_correct = 0
                loss = 0
                for data, label in dataloader:
                    data = data.to(device)
                    label = label.to(device)
                    f_data = model(data)
                    loss += loss_fn(f_data, label).item() * data.shape[0]
                    pred = f_data.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
                    n_correct += pred.eq(label.view_as(pred)).sum().item()
                    n_data += data.shape[0]
            return [np.true_divide(n_correct, n_data), np.true_divide(loss, n_data)]
    elif eval_type == "class_wise_accuracy":
        def evaluate_fn(model):
            correct_hist = torch.zeros(n_classes).to(device)
            label_hist = torch.zeros(n_classes).to(device)
            for data, label in dataloader:
                data = data.to(device)
                label = label.to(device)
                label_hist += torch.histc(label, n_classes, max=n_classes)
                f_data = model(data)
                pred = f_data.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
                correct_index = pred.eq(label.view_as(pred)).squeeze()
                label_correct = label[correct_index]
                correct_hist += torch.histc(label_correct, n_classes, max=n_classes)

            correct_rate_hist = correct_hist / label_hist
            return [correct_rate_hist.cpu().numpy()]
    else:
        raise NotImplementedError

    return evaluate_fn


from  ctypes import CDLL, c_longdouble, c_double,c_void_p,c_char_p

from sys import path as sysPath
from os import path as osPath

sysPath.append(osPath.join(osPath.dirname(__file__), '../../'))

from misc_dir.path import rootDir
from misc_dir.type import cdouble

void_p=c_void_p
char_p=c_char_p

#load the library
CosmoLib = CDLL(rootDir+'/lib/libCosmo.so')

CppFunc=CosmoLib.heff,CosmoLib.geff,CosmoLib.dgeffdT,CosmoLib.dheffdT,CosmoLib.dh,CosmoLib.rhoR,CosmoLib.Hubble,CosmoLib.s

for i,f in enumerate (CppFunc):
    f.argtypes = cdouble, void_p
    f.restype = cdouble
###############################################

CosmoLib.INIT.argtypes=char_p, cdouble, cdouble
CosmoLib.INIT.restype=void_p

CosmoLib.DEL.argtypes= void_p,
CosmoLib.DEL.restype = None

CosmoLib.getT0.argtypes =None
CosmoLib.getT0.restype =cdouble
CosmoLib.geth_hub.argtypes =None
CosmoLib.geth_hub.restype =cdouble
CosmoLib.getrho_crit.argtypes =None
CosmoLib.getrho_crit.restype =cdouble
CosmoLib.getrelicDM.argtypes =None
CosmoLib.getrelicDM.restype =cdouble
CosmoLib.getMP.argtypes =None
CosmoLib.getMP.restype =cdouble

# CMB temperature today in GeV
T0=CosmoLib.getT0()
# critical density today in GeV^4
rho_crit=CosmoLib.getrho_crit()
# dimensionless hubble parameter
h_hub=CosmoLib.geth_hub()
# central value of Omega h^2 according to Planck
relicDM_obs=CosmoLib.getrelicDM()
# Planck mass in GeV
mP=CosmoLib.getMP()

class Cosmo:
    '''Class that contains various cosmological parameters and functions.
    The available functions are:
    heff, geff, dgeffdT, dheffdT, dh, rhoR, Hubble, s.
    All are functions of the temperature (in GeV), and correspond to the standard comsological scenario.
    The available variables are:
    T0: CMB temperature today in GeV
    rho_crit: critical density today in GeV^4
    h_hub: dimensionless hubble parameter
    relicDM_obs: central value of Omega h^2 according to Planck
    mP: Planck mass in GeV
    '''
    def __init__(self, cosmo_PATH, minT=0, maxT=mP):
        '''
        The constructor:
        cosmo_PATH: Relative path to a file that contains T [GeV] h_eff g_eff, with increasing T.
        minT: Minimum interpolation temperature (in GeV)(default 0)
        maxT: Maximum interpolation temperature (in GeV) (default 1.22e19 GeV)
        Beyond the interpolation limits, the h_eff and g_eff are taken to be constant.
        '''
        _file_=char_p(bytes(cosmo_PATH, encoding='utf-8'))
        self.voidCosmo=CosmoLib.INIT(_file_,minT,maxT)

        # CMB temperature today in GeV
        self.T0=T0
        # critical density today in GeV^4
        self.rho_crit=rho_crit
        # dimensionless hubble parameter
        self.h_hub=rho_crit
        # central value of Omega h^2 according to Planck
        self.relicDM_obs=relicDM_obs
        # Planck mass in GeV
        self.mP=mP

    def __del__(self):
        CosmoLib.DEL(self.voidCosmo)

    def pointer(self):
        return self.voidCosmo

    def heff(self,T):
        '''h_eff at temperature T [GeV]'''
        return CosmoLib.heff(T,self.voidCosmo)

    def geff(self,T):
        '''g_eff at temperature T [GeV] '''
        return CosmoLib.geff(T,self.voidCosmo)

    def dgeffdT(self,T):
        '''\\dfrac{dg_eff}{dT} at temperature T [GeV]'''
        return CosmoLib.dgeffdT(T,self.voidCosmo)

    def dheffdT(self,T):
        '''\\dfrac{dh_eff}{dT} at temperature T [GeV]'''
        return CosmoLib.dheffdT(T,self.voidCosmo)

    def dh(self,T):
        '''\\delta_h(T)=1+1/3 \frac{d log h_eff}{d log T} at temperature T [GeV]'''
        return CosmoLib.dh(T,self.voidCosmo)

    def rhoR(self,T):
        '''energy density of the plasma at temperature T [GeV]'''
        return CosmoLib.rhoR(T,self.voidCosmo)

    def Hubble(self,T):
        '''H at temperature T [GeV]'''
        return CosmoLib.Hubble(T,self.voidCosmo)

    def s(self,T):
        '''s (entropy density of the plasma) at temperature T [GeV]'''
        return CosmoLib.s(T,self.voidCosmo)

if __name__=="__main__":
    pass