from numpy import *
from scipy.linalg import *
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
# given constants

radius0= 43164000
G= 6.67300e-11
M= 5.9722e24
m=10
con=G * M / radius0

#equations relating r, r' and r"
# Mach keine Matrix multiplikation, ein Grauss fuer den Rechner O(n^2), besser ist folgendes:
def f(y):
	dydt = hstack((y[2:4],-M*G/norm(y[0:2])**3 * y[0:2]))
	return dydt

#explicit Euler Method
def eE(f, y0, T, N, flag=False):
	""" f     -> is the function that returns the derivative of the argument
		y0    -> is the starting value
		T     -> is the time in Days to be evaluated
		Steps -> is the time step taken for one evaluation point in seconds
		flag  -> False returns all the points evaluated
		 	  -> True  returns only the last point evaluated
	"""

	T = T *60*60*24    #changing the units of days to seconds for the interval
	t,h = linspace(T[0], T[1], N+1, retstep=True)
	y = zeros(( 4 , size(t) ))
	y[:, 0]= y0 # r sieht fuer mich zu sehr nach Radius aus ^

	for i in xrange(N):
		y[:, i+1]= y[:, i]+ h* f(y[:,i])

	if flag==True:
		return y[:,-1]
	else:
		return t, y # Auch die Zeit zurueckgeben

#implicit Euler Method
def iE(f, y0, T, N, flag=False):
	""" f     -> is the function that returns the derivative of the argument
		y0    -> is the starting value
		T     -> is the time in Days to be evaluated
		Steps -> is the time step taken for one evaluation point in seconds
		flag  -> False returns all the points evaluated
		 	  -> True  returns only the last point evaluated
	"""
	T= T *60*60*24    #changing the units of days to seconds for the interval
	t,h =linspace(T[0], T[1], N+1, retstep=True)
	r=zeros(( 4 , size(t) ))
	r[:, 0]= y0
	for i in xrange(N):
		func= lambda alph: alph - h* f(alph) - r[:,i]
		r[:, i+1]= fsolve(func, r[:,i])

	if flag==True:
		return r[:,-1]
	else:
		return t, r

# implicit mid-point method
def iM(f, y0, T, N, flag=False):
	""" f     -> is the function that returns the derivative of the argument
		y0    -> is the starting value
		T     -> is the time in Days to be evaluated
		Steps -> is the time step taken for one evaluation point in seconds
		flag  -> False returns all the points evaluated
		 	  -> True  returns only the last point evaluated
	"""
	T= T *60*60*24    #changing the units of days to seconds for the interval
	t,h =linspace(T[0], T[1], N+1, retstep=True)
	r=zeros(( 4 , size(t) ))
	r[:, 0]= y0
	for i in xrange(N):
		func= lambda alph: alph - h * f(alph/2 + r[:,i]/2) - r[:,i]
		r[:, i+1]= fsolve(func, r[:,i])

	if flag==True:
		return r[:,-1]
	else:
		return t, r

def SV(y0, T, N, G=6.67300*1e-11, M=5.9722*1e24):
	v0 = y0[2:4].copy()
	y0 = y0[0:2].copy()
	T = T * 60 * 60 * 24   # changing units from days to seconds just like above
	d = size(y0)
	t, h = linspace(T[0],T[1],N+1, retstep=True)

	y = zeros((d, size(t)))
	v = zeros((d, size(t)))
	y[:,0] = y0
	v[:,0] = v0

	f = lambda r: - M*G/norm(r)**3 * r

	for i in xrange(int(N)):
		y[:,i+1] = y[:,i] + h * v[:,i] + h**2 * f(y[:,i]) / 2 # Boeser Fehler
		v[:,i+1] = v[:,i] + h * (f(y[:,i]) + f(y[:,i+1])) / 2

	return t, vstack((y,v))

def Energy(y, m=10, G=6.67300*1e-11, M=5.9722*1e24):
	E_kin = m * sum(abs(y[2:4,::])**2, axis=0) / 2
	E_pot = - G * m * M / sum(abs(y[0:2,::])**2, axis=0)**(1./2)
	E_tot = E_kin + E_pot
	return (E_kin, E_pot, E_tot)

# starting value
y0 = array([ radius0, 0, 0, sqrt(con)])
T = [0,5]  # Days to be evaluated  @@to be consitent with the above three programmes otherwise in the plot it is hard to see (ie: very short)
N = 10000 # Number of intervals to be evaluated   @@more points to get rid of the discontinuity of the Energy gain and loss

# implementing the functions

# explicit Euler
t_EE, y_EE = eE(f, y0, T, N)
# implicit Euler
t_IE, y_IE = iE(f,y0,T,N)
# implicit Midpoint
t_IM, y_IM = iM(f,y0,T,N)
# Stroemer-Verlet
t_SV, y_SV = SV(y0, T, N)

#print Energy(y_SV)

plt.figure()
plt.plot(t_EE, Energy(y_EE)[2],'g-', label='total Energy EE')
plt.plot(t_IE, Energy(y_IE)[2],'b-', label='total Energy IE')
plt.plot(t_IM, Energy(y_IM)[2],'y-', label='total Energy IM')
plt.plot(t_SV, Energy(y_SV)[2],'r-', label='total Energy SV')
plt.title(r"Energy")
plt.legend()
plt.show()


'''
Main module of the game
'''

import os
import sys

import pygame
from constant import *
from helper import load_font
from level import Level
from pygame.locals import *
from tile import Tile

class Game:
    '''
    Main class of the game
    '''

    def __init__(self) -> None:
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        self.level = Level(LEVEL[0], self.screen)

    def run(self) -> None:
        '''
        Main loop of the game
        '''
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if self.level.gameover or self.level.gamefinish:
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_SPACE:
                            self.loading_screen()
                            self.level = Level(LEVEL[0], self.screen)

            self.screen.fill(PRIMARY)

            if self.level.gameover:
                self.gameover_screen()
            elif self.level.gamefinish:
                self.gamefinish_screen()
            else:
                self.level.run()

            pygame.display.update()
            self.clock.tick(FRAME)

    def gameover_screen(self) -> None:
        '''
        Game over screen
        '''
        self.screen.fill(PRIMARY)

        # create text
        font = load_font(50)
        text = font.render('Game Over', True, (255, 255, 255))
        text_rect = text.get_rect()
        text_rect.center = (WIDTH / 2, HEIGHT / 2)

        # create text space to restart
        font = load_font(30)
        text_space = font.render('Press Space to Restart', True, (255, 255, 255))
        text_space_rect = text_space.get_rect()
        text_space_rect.center = (WIDTH / 2, HEIGHT / 2 + 50)

        # draw text
        self.screen.blit(text, text_rect)
        self.screen.blit(text_space, text_space_rect)

    def loading_screen(self) -> None:
        '''
        Loading screen
        '''
        self.screen.fill(PRIMARY)

        # create text
        font = load_font(50)
        text = font.render('Loading...', True, (255, 255, 255))
        text_rect = text.get_rect()
        text_rect.center = (WIDTH / 2, HEIGHT / 2)

        # draw text
        self.screen.blit(text, text_rect)
        pygame.display.update()

    def gamefinish_screen(self) -> None:
        '''
        Game finish screen
        '''
        self.screen.fill(PRIMARY)

        # create text
        font = load_font(50)
        text = font.render('You Win', True, (255, 255, 255))
        text_rect = text.get_rect()
        text_rect.center = (WIDTH / 2, HEIGHT / 2)

        # create text space to restart
        font = load_font(30)
        text_space = font.render('Press Space to Restart', True, (255, 255, 255))
        text_space_rect = text_space.get_rect()
        text_space_rect.center = (WIDTH / 2, HEIGHT / 2 + 50)

        # draw text
        self.screen.blit(text, text_rect)
        self.screen.blit(text_space, text_space_rect)

def main() -> None:
    '''
    Main function to start the game
    '''
    # initialize pygame
    pygame.init()
    pygame.display.set_caption('Platformer Game')

    # run game
    game = Game()
    game.run()
    return

if __name__ == '__main__':
    # set directory and run game
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    main()


#coding=utf8
import numpy as np
# c,v=np.load('data.csv',delimiter=',',usecols=(6,7),unpack=True)
vector=np.array([1,3,5,7,9])
print("生成一维向量vector=\n",vector)
matrix=np.array([
    [1,3,5],
    [2,4,6],
    [7,8,9]
])
print("生成二维矩阵matrix=\n",matrix)

second_colum=matrix[:,1]
print("第二列second_colum为：",second_colum)

print(matrix[1:3,0:2])
#判断矩阵里面是否含有某个值,以下方式返回一个布尔值的矩阵matrix==3
is_has_value_three=matrix==3
print(is_has_value_three)

#逻辑运算与或(&、|)


import calendar
import json
import uuid

import requests

from django.conf import settings
from django.urls import reverse
from django.utils import timezone

from ads.utils import get_kwd_usd_rate
from core.utils import build_client_absolute_url

__all__ = (
    'get_payment_info',
    'KNet',
    'months',
    'years',
)

def get_payment_info(payment):
    return {
        'business': settings.PAYPAL_RECEIVER_EMAIL,
        'amount': payment.cost * get_kwd_usd_rate(),
        'item_name': payment.ad.title,
        'currency_code': 'USD',
        'invoice': f'{payment.pk}-{uuid.uuid4()}',
        'notify_url': build_client_absolute_url(reverse('paypal-ipn')),
        'return': build_client_absolute_url(reverse('payments:success')),
        'cancel_return': build_client_absolute_url(reverse('payments:error')),
        'custom': payment.pk,
    }

class KNet(object):

    def __init__(self):
        self.headers = {
            'content-type': 'application/json',
            'Authorization': f'Bearer {settings.KNET_API_KEY}'
        }
        self.token_url = 'https://api.tap.company/v2/tokens'
        self.charge_url = 'https://api.tap.company/v2/charges'

    def create_token(self, card_info):
        payload = {
            'card': card_info
        }
        response = requests.post(self.token_url, json.dumps(payload), headers=self.headers)
        return response.json()

    def charge(self, payment, user, token=None):
        country_code, _, phone_number = user.phone_number.partition('-')

        currency_code = payment.currency
        if not token:
            token = 'src_kw.knet'
            currency_code = 'KWD'

        payload = {
            'amount': payment.cost,
            'currency': currency_code,
            'customer': {
                'first_name': user.first_name,
                'last_name': user.last_name,
                'email': user.email,
                'phone': {
                    'country_code': country_code,
                    'number': phone_number,
                }
            },
            'source': {
                'id': token,
            },
            'redirect': {
                'url': build_client_absolute_url(reverse('payments:proceed')),
            }
        }

        response = requests.post(self.charge_url, json.dumps(payload), headers=self.headers)
        return response.json()

    def retrieve_charge(self, charge_id):
        retrieve_charge_url = f'{self.charge_url}/{charge_id}'
        response = requests.get(retrieve_charge_url, headers=self.headers)
        return response.json()

def months():
    return [(f'0{key}'[-2:], value) for key, value in enumerate(calendar.month_name) if value]

def years():
    current_year = timezone.now().year
    return [(str(year)[2:], year) for year in range(current_year, current_year + 10)]


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

# Common Python library imports
# Pip package imports
from flask_security import current_user
from geoalchemy2 import Geometry

# Internal package imports
from backend.database import (
    Column,
    Model,
    String,
    Integer,
    Float,
    Date,
    relationship,
    association_proxy,
    foreign_key
)

class SoilType(Model):
    title = Column(String(64), nullable=False)
    yield_modifier = Column(Float())

    __repr_props__ = ('id', 'title', 'yield_modifier')


import torch
from torch import nn
import json
import random
import numpy as np
from tqdm import tqdm
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dataList = json.load(open('./gj2.json', encoding='utf-8'))

# 设置训练生成轨迹点的个数范围
fawei = [30, 150]

maxNum = fawei[1]+1

def getmax(data):
    maxX = 0
    maxY = 0

    for i in range(len(data)-maxNum):
        fd = []
        for f in range(maxNum):
            fd.append([data[i+f]['x'], data[i+f]['y']])
        fd = np.array(fd)

        maxXDx = np.max(fd[:,0])
        maxXDy = np.max(fd[:, 1])

        minXDx = np.min(fd[:,0])
        minXDy = np.min(fd[:, 1])
        maxXDx = maxXDx- minXDx
        maxXDy = maxXDy- minXDy

        if maxXDx > maxX:
            maxX = maxXDx
        if maxXDy > maxY:
            maxY = maxXDy
    return maxX, maxY

allMx, allMy = getmax(dataList)
print("最大xy",allMx, allMy)
with open('./gjsetting.txt', 'w', encoding='utf-8') as f:
    f.write(json.dumps({"x":int(allMx), "y":int(allMy)}))

def getDian(data):
    cd = len(data)
    # data += [[0,0]]*(maxNum-cd)
    data = np.array(data, dtype=np.double)
    mx = np.min(data[:,0])
    my = np.min(data[:,1])
    data[:cd,0] = ((data[:cd,0] - mx)/ allMx)
    data[:cd, 1] = ((data[:cd,1] - my)/ allMy)
    return data.tolist()

class modelGj(nn.Module):
    def __init__(self):
        super().__init__()
        self.lstmEncode = nn.LSTM(2,50,num_layers=2, batch_first=True, bidirectional=True)

        self.linDecode = nn.Sequential(
            nn.Linear(100, 50),
            nn.Linear(50, 50),
            nn.Linear(50,2),
        )

        self.sig = nn.Sigmoid()

    def forward(self,x):
        x = x.clone()

        j = []
        st = 1
        buc = 2
        step = x.shape[1] // buc
        for _ in range(x.shape[1]//step):
            j.append(st-1)
            x[:,st:(st+step),:] = 0
            st = st+step+1
            if st+ step >= x.shape[1]:
                break
        if x.shape[1]//step < x.shape[1]/step:
            j.append(x.shape[1]-1)
            x[:, st:-1, :] = 0

        x2, (_,l) = self.lstmEncode(x)
        alld = self.linDecode(x2)

        xd = alld[:,:,0]
        yd = alld[:,:,1]

        xd = self.sig(xd)
        yd = self.sig(yd)
        return xd, yd, j

class dataLoad(Dataset):
    def __init__(self, data):
        super().__init__()
        self.length = len(data) - maxNum
        self.dataList = data

    def __getitem__(self, item):
        data = []
        for i in range(item,item+ random.randint(fawei[0], fawei[1])):
            data.append([self.dataList[i]['x'], self.dataList[i]['y']])
        d = getDian(data)
        data = d

        return torch.tensor(data,dtype=torch.float32).to(device)
    def __len__(self):
        return self.length

class myLoss(nn.Module):

    def __init__(self):
        super().__init__()
        self.bzloss = nn.MSELoss()
    def forward(self,outx, outy, tar, j):
        # xy坐标差距 使预测点的位置更加准确
        ls = torch.mean(torch.abs(outx - tar[:,:,0]))
        ls2 = torch.mean(torch.abs(outy - tar[:,:,1]))

        # 特点位置点的xy差距 使模型预测的结果需要更加接近这些点
        sls = torch.mean(torch.abs(outx[:, j] - tar[:, j, 0]))
        sls2 = torch.mean(torch.abs(outy[:, j] - tar[:, j, 1]))

        # xy坐标方差差距 使预测点的分布更加准确
        fanc = torch.abs(torch.var(outx) - torch.var(tar[:,:,0])) +torch.abs(torch.var(outy) - torch.var(tar[:,:,1]))
        loss = (ls+ls2 + 0.8*fanc + (sls+sls2) * 8)*10
        return loss, fanc, ls+ls2, sls+sls2

dm = dataLoad(dataList)

# 训练多少epoch
epochs = 200
try:
    model = torch.load('./modelyzm.pth')
except:
    model = modelGj()
model.to(device)

# 定义损失函数和优化器
criterion = myLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
max_xl=4000
for epoch in range(epochs):
    dataTrain = DataLoader(dm, shuffle=True, batch_size=1)

    dataTrain = tqdm(dataTrain)
    allloss = 0
    max_xlk=0
    flsall = 0
    lsall = 0
    psall=0
    for index,(gj) in enumerate(dataTrain):
        outx, outy, j = model(gj)
        loss, fls, ls, ps = criterion(outx, outy, gj, j)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        allloss += loss.item()
        flsall += fls.item()
        lsall += ls.item()
        psall += ps.item()

        dataTrain.set_description(desc="epoch {}, loss {}, fanloss {}, lsloss {}, psloss {}".format(epoch, allloss/(index+1), flsall/(index+1),lsall/(index+1),psall/(index+1)))
        max_xlk = allloss/(index+1)

    if max_xl > max_xlk:
        torch.save(model, './modelyzm.pth')
        max_xl = max_xlk


import json
import pickle
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field

from starter.ml.data import process_data

cat_features = [
    "workclass",
    "education",
    "marital-status",
    "occupation",
    "relationship",
    "race",
    "sex",
    "native-country",
]

# Load the trained model and encoder
model_filepath = "model/random_forest_model.pkl"
encoder_filepath = "model/encoder.pkl"

with open(model_filepath, "rb") as file:
    model = pickle.load(file)

with open(encoder_filepath, "rb") as file:
    encoder = pickle.load(file)

# Instantiate the app
app = FastAPI()

class Data(BaseModel):
    age: int = Field(example=39)
    workclass: str = Field(example="State-gov")
    fnlgt: int = Field(example=77516)
    education: str = Field(example="Bachelors")
    education_num: int = Field(alias="education-num", example=13)
    marital_status: str = Field(alias="marital-status", example="Never-married")
    occupation: str = Field(example="Adm-clerical")
    relationship: str = Field(example="Not-in-family")
    race: str = Field(example="White")
    sex: str = Field(example="Male")
    capital_gain: int = Field(alias="capital-gain", example=2174)
    capital_loss: int = Field(alias="capital-loss", example=0)
    hours_per_week: int = Field(alias="hours-per-week", example=40)
    native_country: str = Field(alias="native-country", example="United-States")

    class Config:
        allow_population_by_field_name = True

# GET on greeting
@app.get("/")
async def welcome_intent():
    return {"greeting": "Welcome to my Model!"}

# POST for model inference
@app.post("/inference")
async def inference(data: Data):
    # Converting input data into Pandas DataFrame
    input_df = pd.json_normalize([jsonable_encoder(data)])

    X, _, _, _ = process_data(
        input_df, categorical_features=cat_features, label=None, training=False, encoder=encoder, lb=None
    )

    # Getting the prediction from the Random Forest Model
    pred = model.predict(X)
    if pred.tolist()[0] == 0:
        pred_label = "<=50K"
    else:
        pred_label = ">50K"

    return {"Prediction": pred_label}


import io
from os import listdir
from os.path import isfile, join

import numpy as np

def get_dataset(path):
    '''
    :param path: Path to the directory
    :return: Parallel dataset of sentences.
    '''
    onlyfiles = list_of_files(path)
    return load_from_files(onlyfiles, path)

def list_of_files(path):
    '''
    :param path: Path of the directory
    :return: A list containing all the names of the files inside Path
    '''
    list_files = []
    for f in listdir(path):
        if isfile(join(path, f)) and f[:-3] not in list_files:
            list_files.append(f[:-3])

    return list_files

def file_len(fname):
    '''
    :param fname: Path to the file
    :return: Number of lines in the file
    '''
    with io.open(fname, encoding="utf-8") as f:
        for i, l in enumerate(f):
            pass
    return i + 1

def get_size(onlyfiles, path):
    '''
    :param onlyfiles:  List of files inside the directory.
    :param path: Path to the directory.
    :return: Total of sentences present in the dataset
    '''
    i = 0
    for file in onlyfiles:
        i += file_len(path + "/" + file + ".L1")

    return i

def load_from_files(onlyfiles, path):
    '''
    :param onlyfiles:  List of files inside the directory.
    :param path: Path to the directory.
    :return: Parallel dataset of sentences.
    '''
    dataset_size = get_size(onlyfiles, path)
    dataset = np.empty((dataset_size, 2), dtype=np.object)

    base = 0
    for file in onlyfiles:
        print("Loading " + file)
        f_en = io.open(path + "/" + file + ".L1", encoding="utf-8")
        f_de = io.open(path + "/" + file + ".L2", encoding="utf-8")

        offset = 0
        for line in f_en:
            line = line.replace('\n', '')
            dataset[base + offset][0] = line
            offset += 1

        offset = 0
        for line in f_de:
            line = line.replace('\n', '')
            dataset[base + offset][1] = line
            offset += 1

        base += offset

    return dataset


import codecs
import datetime
import hashlib
import uuid
from io import BytesIO
from typing import Any, Dict, List, Tuple

import textdistance
from django.contrib.auth.models import User
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db.models import Q

from image_labelling.exceptions import (
    ImageAlreadyExists,
    ImageDosentExist,
    LabelDoesntExist,
    UnauthorizedAction,
)
from image_labelling.models import Image, Label
from image_labelling.settings import TEMP_FILE_STORAGE_PATH, StatusMapper

class ImageHandler:
    """The image handler class is responsible for storing file to filesystem
    and creating a db entry for the same"""

    def __init__(self, file: InMemoryUploadedFile, user: User) -> None:

        self._filename: str = file.name
        self._format: str = file.name.split(".")[-1]
        self._bytes_obj: BytesIO = file.read()
        self._sha: str = hashlib.sha256(self._bytes_obj).hexdigest()
        self._uuid: uuid.uuid4 = uuid.uuid4()
        self._user: User = user

    def _write_image_fs(self) -> None:
        """Wirtes image file in form of bytes to file system."""

        with open(
            "{}/{}.{}".format(TEMP_FILE_STORAGE_PATH, str(self._uuid), self._format),
            "wb+",
        ) as f:
            f.write(self._bytes_obj)

    def _verify_image_object_present(self) -> bool:
        """This method verifies if a image is present in the database or not."""

        try:
            image = Image.objects.get(integrity=self._sha)
            if image.status == 0:
                return False
            return True
        except Image.DoesNotExist:
            return False

    def _create_db_object(self):
        """Creates a image data entry in the database."""

        Image.objects.create(
            id=self._uuid, format=self._format, integrity=self._sha, user=self._user
        )

    def _check_inactive(self) -> bool:
        """This method checks if an image is marked as inactive or not."""

        try:
            image = Image.objects.get(integrity=self._sha)
            if image.status == 0:
                return True
        except Image.DoesNotExist:
            return False

    def store(self):
        """The main method responible to store a image in filesystem and database."""

        if self._verify_image_object_present():

            raise ImageAlreadyExists(
                "Image with name {} already exists and has a matching hash({}) with other image in database.".format(
                    self._filename, self._sha
                )
            )

        if self._check_inactive():
            image = Image.objects.get(integrity=self._sha)
            image.status = 1
            image.save()
        else:
            self._write_image_fs()
            self._create_db_object()

def delete_image(user: User, image_id: str) -> None:
    """This function is responsibe for deleting image ie deactiving the image from database."""
    try:
        image = Image.objects.get(id=image_id)

        if user != image.user:
            raise UnauthorizedAction(
                "Not permitted to delete image uploaded by user: {}".format(
                    user.username
                )
            )

        image.status = 0
        image.save()
        query_set = Label.objects.filter(image_id=image_id)

        for v in query_set:
            v.status = 0
            v.save()

    except Image.DoesNotExist:
        pass

def list_images(
    start_idx: int,
    end_idx: int,
    start_date: datetime.datetime,
    end_date: datetime.datetime,
    status: str,
) -> List[Dict[str, str]]:
    """This function is responsible for listing all images in given index range or given date range"""

    status = getattr(StatusMapper, status).value

    if not start_date and not end_date:
        if status is None:
            image_queryset = Image.objects.all().order_by("uploaded_on")
        else:
            image_queryset = Image.objects.filter(status=status).order_by("uploaded_on")
    else:
        if status is None:
            image_queryset = Image.objects.filter(
                uploaded_on__range=[start_date, end_date]
            )
        else:
            image_queryset = Image.objects.filter(
                uploaded_on__range=[start_date, end_date], status=status
            )

    if ((start_idx or start_idx == 0) and (end_idx or end_idx == 0)) and (
        not start_date and not end_date
    ):

        image_queryset = image_queryset[start_idx:end_idx]

    image_information = list()

    for image_obj in image_queryset:

        image_information.append(
            {
                "created_by": image_obj.user.username,
                "id": image_obj.id,
                "uploaded_on": image_obj.uploaded_on,
                "format": image_obj.format,
            }
        )

    return image_information

def get_image_obj(image_id: str) -> bool:
    """This function returns and image orm object given image id."""

    try:
        image = Image.objects.get(id=image_id)
        if image.status == 0:
            return None
        return image
    except Image.DoesNotExist:
        return None

def get_image_path(image_id) -> Tuple[str, str]:
    """This function returns image path for where the image is stored in file system."""

    image = get_image_obj(image_id)

    if not image:
        raise ImageDosentExist("Image with id {} doesn't exist".format(image_id))

    file_path = "{}/{}.{}".format(TEMP_FILE_STORAGE_PATH, str(image.id), image.format)
    content_type = "image/{}".format(image.format)

    return file_path, content_type

class LabelsManager:
    """This class is responsible for management of labels"""

    def __init__(self, user: User, image_id: uuid.uuid4) -> None:

        self._image = get_image_obj(image_id)

        if not self._image or self._image.status == 0:
            raise ImageDosentExist("Image with id {} doesn't exist".format(image_id))

        self._user = user
        self._image_id = image_id

    def _get_queryset_if_label_exists(self, label_value: str) -> Label:
        """ "Returns a label object register by the user for an image with give label value"""

        try:
            label = Label.objects.get(
                user_id=self._user.id, image_id=self._image_id, label=label_value
            )
            return label
        except Label.DoesNotExist:
            return None

    def _update_existing_label(self, label_obj, coordinates: Dict[str, float]) -> None:
        """This method updates the existing label or cordinates of it."""

        x1 = coordinates["x1"]
        x2 = coordinates["x2"]
        y1 = coordinates["y1"]
        y2 = coordinates["y2"]

        if (
            label_obj.x1 != x1
            or label_obj.x2 != x2
            or label_obj.y1 != y1
            or label_obj.y2 != y2
        ):
            label_obj.x1 = x1
            label_obj.x2 = x2
            label_obj.y1 = y1
            label_obj.y2 = y2

            label_obj.save()
        elif label_obj.status == 0:
            label_obj.status = 1

            label_obj.save()

    def _insert_new_label(
        self, coordinates: Dict[str, float], label_value: str
    ) -> None:
        """This function inserts a new label for an image."""

        id = uuid.uuid4()
        x1 = coordinates["x1"]
        x2 = coordinates["x2"]
        y1 = coordinates["y1"]
        y2 = coordinates["y2"]

        label = Label.objects.create(
            id=id,
            image_id=self._image,
            user_id=self._user,
            x1=x1,
            y1=y1,
            x2=x2,
            y2=y2,
            label=label_value,
        )

    def store(self, coordinates: Dict[str, float], label: str) -> None:
        """This method is responsible to perform all computations requried for storing labels."""

        label_obj = self._get_queryset_if_label_exists(label)

        if label_obj:
            self._update_existing_label(label_obj, coordinates)
        else:
            self._insert_new_label(coordinates, label)

    def delete(self, label_id: str) -> None:
        """ "This method is responsible for deactiving active labels."""

        try:
            label_obj = Label.objects.get(
                user_id=self._user.id,
                image_id=self._image_id,
                id=label_id,
            )
            label_obj.status = 0
            label_obj.save()
            return None
        except Label.DoesNotExist:
            raise LabelDoesntExist(
                "label: {} doesn't exists for user: {}".format(
                    label_id, self._user.username
                )
            )

def list_labels(start_date, end_date, status) -> List[Dict[str, str]]:
    """This function is responsible for listing labels in given date range."""

    status = getattr(StatusMapper, status).value

    if start_date and end_date:
        if status is None:
            label_queryset = Label.objects.filter(
                updated_at__range=[start_date, end_date]
            )
        else:
            label_queryset = Label.objects.filter(
                updated_at__range=[start_date, end_date], status=status
            )
    else:
        if status is None:
            label_queryset = Label.objects.all().order_by("updated_at")
        else:
            label_queryset = Label.objects.filter(status=status).order_by("updated_at")

    label_information = dict()

    for label_obj in label_queryset:

        dict_key = (
            label_obj.image_id.id,
            label_obj.image_id.format,
            label_obj.image_id.uploaded_on,
            label_obj.image_id.user.username,
            label_obj.image_id.status,
        )

        if dict_key not in label_information:
            label_information[dict_key] = []

        label_information[dict_key].append(
            {
                "created_by": label_obj.user_id.username,
                "id": label_obj.id,
                "created_at": label_obj.created_at,
                "updated_at": label_obj.updated_at,
                "label": label_obj.label,
                "coordinates": {
                    "x1": label_obj.x1,
                    "x2": label_obj.x2,
                    "y1": label_obj.y1,
                    "y2": label_obj.y2,
                },
            }
        )

    return [
        {
            "image_id": k[0],
            "image_format": k[1],
            "image_uploaded_on": k[2],
            "image_created_by": k[3],
            "labels": v,
            "image_status": k[4],
        }
        for k, v in label_information.items()
    ]

class LabelSearch:
    """This class is responsible for performing label search given a query parm."""

    @staticmethod
    def text_distance(t1: str, t2: str) -> float:
        """This method is responsible for computing jaccard similarity between two strings"""

        return textdistance.jaccard.normalized_similarity(t1.lower(), t2.lower())

    def __init__(self, query: str) -> None:

        self._query = query

    def _query_set_contains(self):
        """Returns queryset after performing icontains"""

        return Label.objects.filter(label__icontains=self._query, status=1)

    def _query_set_search(self):
        """Returns querysert after performing serach for given query."""

        return Label.objects.filter(label__search=self._query, status=1)

    def search(self) -> Dict[str, Any]:
        """Method that computes search and returns the search result."""

        query_set = list(self._query_set_contains()) + list(self._query_set_search())

        search_list = set(
            [(v, LabelSearch.text_distance(self._query, v.label)) for v in query_set]
        )
        search_list = sorted(search_list, key=lambda x: x[1], reverse=True)

        return [
            {
                "image_id": v.image_id.id,
                "image_format": v.image_id.format,
                "image_uploaded_on": v.image_id.uploaded_on,
                "image_uploaded_by": v.image_id.user.username,
                "label_id": v.id,
                "label_created_at": v.created_at,
                "label_updated_at": v.updated_at,
                "labeled_by": v.user_id.username,
                "label": v.label,
                "coordinates": {
                    "x1": v.x1,
                    "y1": v.y1,
                    "x2": v.x2,
                    "y2": v.y2,
                },
                "similarity": similarity,
            }
            for v, similarity in search_list
            if (similarity > 0.5 and v.status == 1)
        ]

def get_labels_by_image_id(image_id: uuid.uuid4) -> Dict[str, Any]:
    """This function is responsible for getting labels given image id"""

    query_set = Label.objects.filter(image_id=image_id, status=1).order_by("updated_at")

    return [
        {
            "created_by": v.user_id.username,
            "id": v.id,
            "created_at": v.created_at,
            "updated_at": v.updated_at,
            "label": v.label,
            "coordinates": {"x1": v.x1, "y1": v.y1, "x2": v.x2, "y2": v.y2},
        }
        for v in query_set
    ]

def get_image_metadata(image_id: uuid.uuid4) -> Dict[str, Any]:
    """This function is responsible for retriving image metadata given image id."""

    try:
        image = Image.objects.get(id=image_id)
        if image.status == 0:
            ImageDosentExist("Image with id: {} doesn't exist.".format(image_id))
        return {
            "uploaded_by": image.user.username,
            "uploaded_on": image.uploaded_on,
            "sha": image.integrity,
            "format": image.format,
        }
    except Image.DoesNotExist:
        raise ImageDosentExist("Image with id: {} doesn't exist.".format(image_id))


#!/usr/bin/python
"""
Create a very simple initrd.
[inode1][file_data1][inode2][file_data2] ...

Usage:
    initrd_gen.py <directory_name>
"""
import os
import struct
import ctypes
import itertools
from docopt import docopt

INITRD_DIR = '/home/sourcer/mike_os/grub/boot/'
INITRD_NAME = 'initrd.img'
INITRD_PATH = os.path.join(INITRD_DIR, INITRD_NAME)
NAME_SIZE = 20
GARBAGE_VALUE = 'U'
PAGE_SIZE = 4096

def inode_to_raw(name, offset, size):

    name = ctypes.create_string_buffer(name, NAME_SIZE).raw
    size = struct.pack('I', size)
    offset = struct.pack('I', offset)
    return ''.join([offset, size, name])

def dir_iter(directory_name):
    for current_dir, sub_dirs, files_in_dir \
                                        in os.walk(directory_name):
        for file_path in files_in_dir:
            yield os.path.abspath(os.path.join(current_dir, file_path))

def accumulate(iterator):
    total = 0
    for item in iterator:
        total += item
        yield total

def create_initrd(directory_name):
    files = []
    offset = 0

    with open(INITRD_PATH, 'w+') as initrd:
        files_paths = list(dir_iter(directory_name))

        files_sizes = [os.stat(file_name)[6]
                       for file_name in files_paths]
        files_offsets = list(files_sizes)
        files_offsets.insert(0, 0)
        files_offsets.pop(len(files_offsets) - 1)
        files_offsets = accumulate(files_offsets)
        files_names = [os.path.basename(file_path)
                       for file_path in files_paths]

        inodes_table = \
                [inode_to_raw(name,
                              offset,
                              size)
                 for name, offset, size in itertools.izip(files_names,
                                                          files_offsets,
                                                          files_sizes)]
        initrd.write(struct.pack('I', len(files_paths)))
        initrd.write(''.join(inodes_table))

        for file_path in files_paths:
            with open(file_path, 'rb') as file_obj:
                initrd.write(file_obj.read())

    # If not aligned to 4K, align it
    size = os.stat(initrd.name)[6]
    if size % 4096 != 0:

        aligned_size = (size & ~(PAGE_SIZE - 1))
        if aligned_size < size:
            aligned_size += PAGE_SIZE

        with open(INITRD_PATH, 'a+') as initrd:
            initrd.write(GARBAGE_VALUE * (aligned_size - size))

def main(directory_name):
    if not os.path.isdir(directory_name):
        raise TypeError("Expected a directory")

    create_initrd(os.path.abspath(directory_name))

if __name__ == "__main__":
    arguments = docopt(__doc__)
    main(arguments['<directory_name>'])


#!/usr/bin/env python
# Read a FASTA file and output the C/G percentage for each entry

import os
import sys
from csv import writer

sys.path.append("%s/lib/python" % os.environ['LAB_HOME'])
from util.cl import parse

def cg_pct(seq, outfile, window_size=100, decimal=False):
    with open(outfile, "w") as out:
        w = writer(out, delimiter="\t")
        seqlen = len(seq)
        for i in xrange(0, seqlen, window_size):
            end = min(i + window_size, seqlen)
            if i == end:
                break
            win = seq[i:end].upper()
            gc = float(sum(1 for char in win if char in ("C","G"))) / (end - i + 1)
            if not decimal:
                gc = int(round(gc * 100))
            w.writerow((i,end,gc))

def main(argv=None):
    def add_opts(parser):
        parser.add_argument("-d", "--decimal", action="store_true", default=False)
        parser.add_argument("-w", "--window_size", default=100, type=int)
        parser.add_argument("infile", type='readable_file')
        parser.add_argument("outfile", type='writeable_file')

    ns = parse(add_opts, args=argv)

    with open(ns.infile, 'rU') as inp:
        seq = inp.read().replace("\n","")

    cg_pct(seq, ns.outfile, ns.window_size, ns.decimal)

if __name__ == '__main__':
    main()


import numpy as np
import xlrd

import scipy.stats as sp
import matplotlib.pyplot as plt
import math

def calc_MGD(p,q,y):
    temp = 0
    X = np.empty([q,q])
    ymod = np.zeros(shape=(1,q))
    for j in range(0,q):
        for i in range(0,q):
            temp = 0
            for  s in range(0,49):
                temp += (p[i][s] *p[j][s])
            X[i][j] = temp

    for u in range(0,q):
        temp = 0
        for  s in range(0,49):
             temp+= y[s]*p[u][s]
        ymod[0][u] = temp
    ymod2 = np.transpose(ymod)

    beta = np.linalg.solve(X,ymod2)

    sigma11 = 0
    sigma21 = 0
    for s in range(0,49):
      sigma11 = 0
      for i in range(0,q):
          sigma11+= beta[i][0]*p[i][s]
      sigma21+=(sigma11-y[s])**2
    sigmasqr =sigma21/49

    theta = 0

    for s in range(0,49):
        sigma11= 0
        for i in range(0,q):
            sigma11+= beta[i][0]*p[i][s]
        theta +=-0.5*(math.log(2*math.pi*sigmasqr))-((0.5 *((sigma11-y[s])**2))/sigmasqr)

    return theta


import json
import datetime
import random
import re

import requests
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt

import setting
from order.models import Checkout, ShippingAddress
from paymentgateway.models import GatewayCredentials, PaymentTransactions
from setting.models import StoreInformation

@csrf_exempt
def index(request):
    if request.method == 'GET':
        try:
            store = StoreInformation.objects.get(deleted=False)
        except Exception as e:
            print(e)
            return HttpResponse('Store does not exist')

        success_url = f"{settings.HOST_URL}/paymentgateway/bykea_success_request"
        failure_url = f"{settings.HOST_URL}/paymentgateway/bykea_failure_request"
        order_place_url = f"{settings.HOST_URL}/order/place_order"
        complete_url = f"{settings.STOREFRONT_URL}/thankyou"
        bykea_base_url = "https://invoice.bykea.cash"

        checkout_id = request.GET.get('checkout_id')
        if not checkout_id:
            return redirect(failure_url)
        else:
            checkout = Checkout.objects.filter(checkout_id=checkout_id).first()

        # order amount
        amount = f"{float(checkout.subtotal_price) + float(checkout.total_shipping)}"

        current_date = datetime.datetime.now()
        transaction_number = (str(random.randint(1000, 1000000)) + '-' + current_date.strftime("%Y-%m-%dT%H-%M-%S")). \
            replace('-', '')

        try:
            gateway_credentials = GatewayCredentials.objects.filter(gateway_name='HBL', is_active=True).first()
            if not gateway_credentials:
                return redirect(failure_url)

            if gateway_credentials.test_mode:
                    secret_key = gateway_credentials.credentials["test"]["secret_key"],
                    profile_id = gateway_credentials.credentials["test"]["profile_id"],
                    access_key = gateway_credentials.credentials["test"]["access_key"],

            else:
                    secret_key = gateway_credentials.credentials["live"]["secret_key"],
                    profile_id = gateway_credentials.credentials["live"]["profile_id"],
                    access_key = gateway_credentials.credentials["live"]["access_key"]

            customer = ShippingAddress.objects.filter(checkout__checkout_id=checkout_id).first()

            customer_phone = customer.phone.replace(" ", "")

            try:
                phone_validation = re.match(r'/^(0)-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$', customer_phone)
                if phone_validation is None:
                    customer_phone = ""
            except Exception as e:
                print(e)
                customer_phone = ""

            if customer_phone[:1] == "+" and len(customer_phone) == 13:
                customer_phone = customer_phone[3:]
                customer_phone = "0" + customer_phone
            elif len(customer_phone) == 14 and customer_phone[:4] == "0092":
                customer_phone = customer_phone[4:]
                customer_phone = "0" + customer_phone
            elif len(customer_phone) == 14 and customer_phone[:4] == "0+92":
                customer_phone = customer_phone[4:]
                customer_phone = "0" + customer_phone
            elif len(customer_phone) == 10 and customer_phone[:1] == "3":
                customer_phone = "0" + customer_phone

            payment_transaction = PaymentTransactions.objects.create(
                checkout_id=checkout_id,
                customer_first_name=customer.first_name,
                customer_last_name=customer.last_name,
                callback_url=order_place_url,
                cancel_url=failure_url,
                complete_url=complete_url,
                currency=store.store_currency,
                signature="",
                order_amount=amount,
                txn_ref_no=transaction_number,
                test_mode=gateway_credentials.test_mode
            )
            locale = 'en'
            transaction_type = 'sale'
            reference_number = transaction_number
            amount = amount
            currency = "PKR"
            merchant_defined_data1 = "WC"
            merchant_defined_data2 = "YES"
            merchant_defined_data3 = "Test"
            merchant_defined_data4 = "Default"
            merchant_defined_data5 = "YES"
            merchant_defined_data6 = "Standard"
            merchant_defined_data7 = "NO"
            merchant_defined_data8 = "Pakistan"
            merchant_defined_data20 = "NO"

            payload = {
                'access_key': access_key,
                'transaction_uuid': transaction_number,
                'signed_date_time': current_date,
                'locale': locale,
                'transaction_type': transaction_type,
                'reference_number': reference_number,
                'amount': amount,
                'currency': currency,
                'bill_to_address_city': customer.city,
                'bill_to_address_country': customer.country,
                'bill_to_address_line1': customer.address,
                'bill_to_address_line2': customer.address,
                'bill_to_address_postal_code': customer.postal_code,
                'bill_to_address_state': customer.country,
                'bill_to_company_name': 'KEES',
                'bill_to_email': checkout.email,
                'bill_to_forename': customer.first_name,
                'bill_to_surname': customer.last_name,
                'bill_to_phone': customer_phone,
                'ship_to_address_city': customer.city,
                'ship_to_address_country': customer.country,
                'ship_to_address_line1': customer.address,
                'ship_to_address_postal_code': customer.postal_code,
                'ship_to_address_state': customer.address,
                'ship_to_forename': customer.first_name,
                'ship_to_phone': customer_phone,
                'ship_to_surname': customer.last_name,
                'ship_to_email': customer.email,
                'customer_ip_address': 'test ip',
                'line_item_count': '1',
                'consumer_id': reference_number,
                'merchant_defined_data1': merchant_defined_data1,
                'merchant_defined_data2': merchant_defined_data2,
                'merchant_defined_data3': merchant_defined_data3,
                'merchant_defined_data4': merchant_defined_data4,
                'merchant_defined_data5': merchant_defined_data5,
                'merchant_defined_data6': merchant_defined_data6,
                'merchant_defined_data7': merchant_defined_data7,
                'merchant_defined_data8': merchant_defined_data8,
                'merchant_defined_data20': merchant_defined_data20,
                'unsigned_field_names': "",
            }
        except Exception as e:
            print(e)
            return redirect(failure_url)
    else:
        return redirect("https://www.google.com")

def success_response(self, request):
    txn_ref_no = self.request.GET.get('transaction_id')

    try:
        payment_transaction = PaymentTransactions.objects.get(txn_ref_no=txn_ref_no)
    except Exception as e:
        print("Exception in Bykea RESPONSE " + str(e))
        return redirect(f"{settings.STOREFRONT_URL}/checkout?error=Some Error Occured in retrieving transaction")

    payment_transaction.response_code = "200"

    payload = {
        'checkout_id': payment_transaction.checkout_id
    }

    headers = {
        "Content-Type": "application/json",
        'User-agent': 'Gecko/20100101 Firefox/12.0 Mozilla/5.0'
    }

    payload = json.dumps(payload)
    response = requests.post(payment_transaction.callback_url, data=payload, headers=headers)

    order_id = (response.json())['transaction_id']

    if response.status_code == 200:
        payment_transaction.transaction_id = request.GET.get('transaction_id')
        payment_transaction.transaction_status = "Success"
        payment_transaction.save()
        return redirect(f"{payment_transaction.complete_url}/{order_id}")
    elif response.status_code == 422:
        payment_transaction.response_message = "Order placement failed!"
        payment_transaction.transaction_status = "Failed"
        payment_transaction.save()
        return redirect(f"{payment_transaction.cancel_url}?error={payment_transaction.response_message}")

def failed_response(self, request):
    txn_ref_no = self.request.GET.get('transaction_id')

    try:
        payment_transaction = PaymentTransactions.objects.get(txn_ref_no=txn_ref_no)
    except Exception as e:
        print("Exception in Bykea RESPONSE " + str(e))
        return redirect(f"{settings.STOREFRONT_URL}/checkout?error=Some Error Occured in retrieving transaction")

    payment_transaction.response_code = "422"
    payment_transaction.response_message = "Order Not Placed"
    payment_transaction.save()
    return redirect(payment_transaction.cancel_url)


import csv
import os
import pandas as pd

class Course:
    def __init__(self, id_crs, name, unit, capacity, name_prof, time_exam, time_class, field_crs,
                 status_capacity=0):
        """
        :param id_crs: id course is unique
        :param name:name of course
        :param unit:unit of course
        :param capacity:capacity of course
        :param name_prof:name professor present course
        :param time_exam:course exam time
        :param time_class:course time class
        :param field_crs:field course
        :param status_capacity:number of filled capacity
        """
        self.id_crs = id_crs
        self.name = name
        self.unit = unit
        self.capacity = capacity
        self.name_prof = name_prof
        self.time_exam = time_exam
        self.time_class = time_class
        self.field_crs = field_crs
        self.status_capacity = status_capacity

    def file_selective_crs(self, username_student, term):
        """
        write selective courses any student in file(create file selective course)
        :param username_student: username student for write student any course
        :param term: term student
        :return: no return just create file and write in file
        """
        check_file = os.path.exists('file_select_course.csv')
        # add course student to file
        if check_file:
            with open('file_select_course.csv', 'a', newline='') as write_csv:
                fieldnames = ['username_student', 'term', 'id_crs', 'name', 'unit', 'name_prof', 'time_exam',
                              'time_class',
                              'field_crs']
                csv_writer = csv.DictWriter(write_csv, fieldnames=fieldnames)
                csv_writer.writerow({'username_student': username_student,
                                     'term': term,
                                     'id_crs': self.id_crs,
                                     'name': self.name,
                                     'unit': self.unit,
                                     'name_prof': self.name_prof,
                                     'time_exam': self.time_exam,
                                     'time_class': self.time_class,
                                     'field_crs': self.field_crs,
                                     })
        # create file selection course
        else:
            with open('file_select_course.csv', 'a', newline='') as create_file:
                fieldnames = ['username_student', 'term', 'id_crs', 'name', 'unit', 'name_prof', 'time_exam',
                              'time_class',
                              'field_crs']
                csv_writer = csv.DictWriter(create_file, fieldnames=fieldnames)
                csv_writer.writeheader()
                csv_writer.writerow({'username_student': username_student,
                                     'term': term,
                                     'id_crs': self.id_crs,
                                     'name': self.name,
                                     'unit': self.unit,
                                     'name_prof': self.name_prof,
                                     'time_exam': self.time_exam,
                                     'time_class': self.time_class,
                                     'field_crs': self.field_crs,
                                     })

    def update_file_course(self):
        """
        :return: if id course exit in file so course file update  and return True else return 'not find id course'
        """
        df = pd.read_csv("file_course.csv")
        with open('file_course.csv', 'r') as edit_file:
            fieldnames = ['id_crs', 'name', 'unit', 'capacity', 'name_prof', 'time_exam', 'time_class', 'field_crs',
                          'status_capacity']
            file_crs_r = csv.DictReader(edit_file, fieldnames=fieldnames)
            line = 0
            for row in file_crs_r:
                if row['id_crs'].isdigit():
                    if int(self.id_crs) == int(row['id_crs']):
                        df.loc[line - 1, 'status_capacity'] = self.status_capacity
                        df.to_csv("file_course.csv", index=False)
                        return True
                line += 1
            return 'not find id course'

    def update_file_slc_course(self):
        """
        :return:if id course exit in file so selective course file update and return True else return 'not find id course'
        """
        df1 = pd.read_csv("file_select_course.csv")
        df_s = df1[:9]
        with open('file_select_course.csv', 'r') as edit_file:
            fieldnames = ['username_student', 'term', 'id_crs', 'name', 'unit', 'name_prof', 'time_exam',
                          'time_class', 'field_crs']
            file_slc_crs_r = csv.DictReader(edit_file, fieldnames=fieldnames)
            line = 0
            for row in file_slc_crs_r:
                if row['id_crs'].isdigit():
                    if int(self.id_crs) == int(row['id_crs']):
                        df_s = df_s.drop(df_s[(df_s.id_crs == self.id_crs)].index)
                        df_s.to_csv("file_select_course.csv", index=False)
                        return True
                line += 1
            return 'not find id course'

    def file_crs(self):
        """
        :return: create file course and write attributes class course in file
        """
        check_file = os.path.exists('file_course.csv')
        if check_file:
            with open('file_course.csv', 'a', newline='') as write_course_csv:
                fieldnames = ['id_crs', 'name', 'unit', 'capacity', 'name_prof', 'time_exam', 'time_class', 'field_crs',
                              'status_capacity']
                csv_writer = csv.DictWriter(write_course_csv, fieldnames=fieldnames)
                csv_writer.writerow({'id_crs': self.id_crs,
                                     'name': self.name,
                                     'unit': self.unit,
                                     'capacity': self.capacity,
                                     'name_prof': self.name_prof,
                                     'time_exam': self.time_exam,
                                     'time_class': self.time_class,
                                     'field_crs': self.field_crs,
                                     'status_capacity': self.status_capacity})
        else:
            with open('file_course.csv', 'a', newline='') as create_file:
                fieldnames = ['id_crs', 'name', 'unit', 'capacity', 'name_prof', 'time_exam', 'time_class', 'field_crs',
                              'status_capacity']
                csv_writer = csv.DictWriter(create_file, fieldnames=fieldnames)
                csv_writer.writeheader()
                csv_writer.writerow({'id_crs': self.id_crs,
                                     'name': self.name,
                                     'unit': self.unit,
                                     'capacity': self.capacity,
                                     'name_prof': self.name_prof,
                                     'time_exam': self.time_exam,
                                     'time_class': self.time_class,
                                     'field_crs': self.field_crs,
                                     'status_capacity': self.status_capacity})

    @classmethod
    def search_file_crs(cls, metric, value_metric):
        """
        :param metric:name attribute
        :param value_metric:value attribute
        :return:make a instance of course class
        """
        try:
            with open('file_course.csv', 'r') as read_course_csv:
                csv_read = csv.DictReader(read_course_csv)
                for row in csv_read:
                    if row[metric].isdigit():
                        if int(row[metric]) == int(value_metric):
                            row = [int(i.strip()) if i.isdigit() else i for i in row.values()]
                            return cls(*row)
            return False
        except FileNotFoundError:
            return False

    @staticmethod
    def search_file_slc_crs(metric, value_metric, term_now):
        """
        :param term_now: term of student
        :param metric:name attribute
        :param value_metric:value attribute
        :return:make a instance of course class
        """
        try:
            with open('file_select_course.csv', 'r') as crs_file:
                csv_read = csv.DictReader(crs_file)
                for row in csv_read:
                    if row[metric].isdigit():
                        if int(row[metric]) == int(value_metric) and int(row['term']) == int(term_now):
                            return True
            return False
        except FileNotFoundError:
            return False