import os, shutil,math,warnings,time
from glob import glob
from tqdm import tqdm
import json
import pycrs
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import fiona
from fiona.crs import from_epsg
from PIL import Image, ImageOps
from shapely import wkt
from shapely.geometry import box,Point
import pandas as pd
import geopandas as gpd
import rasterio
import rasterio.mask
from rasterio.plot import show
from rasterio.enums import Resampling
from rasterio.warp import calculate_default_transform, reproject, Resampling
from sklearn.decomposition import PCA
from sklearn import metrics
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier

warnings.simplefilter(action='ignore', category=FutureWarning)

class AnalysisTool:
    def __init__(self):
        pass

    def train_point_handler(self, shapefile_path, image_path, array_list=[],raster=None,num_points=1000):

        gdf = gpd.read_file(shapefile_path)

        values = []
        training_points = []

        if len(array_list)==0:
            raster = rasterio.open(image_path)
            array_list=[raster.read(i+1) for i in range(counts)]
        else:
            raster=raster
            array_list=array_list

        counts = raster.meta['count']

        while len(training_points) < num_points:
            idx = np.random.randint(0, gdf['geometry'].count())
            bounds = gdf[gdf['geometry'].index == idx].total_bounds

            xmin = bounds[0]
            xmax = bounds[2]
            ymin = bounds[1]
            ymax = bounds[3]

            x = np.random.uniform(xmin, xmax)
            y = np.random.uniform(ymin, ymax)
            point = Point(x, y)

            if len(gdf[gdf['geometry'].index == idx].loc[gdf[
                    gdf['geometry'].index == idx].intersects(
                        point)].index) == 0:
                pass
            else:
                val_list = []
                for i in range(counts):
                    #array = raster.read(i + 1)
                    array=array_list[i]
                    val = array[raster.index(x, y)]
                    val_list.append(val)
                if np.isnan(val_list).any() == True:
                    pass
                else:
                    values.append(val_list)
                    training_points.append(point)

        del raster

        return values, training_points

    def train_data_process(self,
                           shapefile_dir_path,
                           image_path=None,
                           num_points=1000,
                           show_spectrum=False,
                           band_order=[],
                           write_train_data=False,
                           output_train_data_path=None):

        raster = rasterio.open(image_path)
        band_names=list(raster.descriptions)
        output_train_data_epsg=raster.meta['crs']
        counts=raster.meta['count']
        array_list=[raster.read(i+1) for i in range(counts)]

        train_point_handler = self.train_point_handler
        shapefile_list = glob(shapefile_dir_path + '/*.shp')

        extracted_values = []
        lulc_class = []
        lulc_name = []
        lat = []
        lon = []

        cnt = 1
        for shapefile in tqdm(shapefile_list):
            filename = os.path.basename(shapefile).replace('.shp', '')

            values, training_point = train_point_handler(
                shapefile, image_path, num_points=num_points,array_list=array_list,raster=raster)
            extracted_values.extend(values)

            lat.extend([point.x for point in training_point])
            lon.extend([point.y for point in training_point])

            lulc_name.extend([filename for i in range(len(values))])
            lulc_class.extend([cnt for i in range(len(values))])
            cnt += 1

        output_df = pd.DataFrame({
            'lulc_name': lulc_name,
            'lulc_class': lulc_class,
            'extracted_values': extracted_values,
            'Latitude': lat,
            'Longitude': lon
        })

        output_gdf = gpd.GeoDataFrame(output_df,
                                      geometry=gpd.points_from_xy(
                                          output_df.Latitude,
                                          output_df.Longitude))
        output_gdf.set_crs(output_train_data_epsg, inplace=True)

        if show_spectrum==True:
            fig,ax=plt.subplots(figsize=(20,10))
            if len(band_order)==0:
                spectrum_axis=band_names
            else:
                spectrum_axis=band_order
            classes=set(extracted_data_gdf['lulc_name'])
            for cla in classes:
                extracted_data=extracted_data_gdf[extracted_data_gdf['lulc_name']==cla]
                values=np.array(list(extracted_data['extracted_values']))
                value_list=[]
                for band in spectrum_axis:
                    idx=band_names.index(band)
                    mean_val=np.mean(values[:,idx:idx+1])
                    value_list.append(mean_val)
                ax.plot(spectrum_axis,value_list,label=cla)
            ax.legend()

        if write_train_data == True:
            output_gdf.drop('extracted_values',
                            axis=1).to_file(output_train_data_path)
        else:
            pass

        return output_gdf

    def pca_image(self,
                  image_path,
                  RGBoption=False,
                  return_arrays=False,
                  n_components=10,
                  exception=[],
                  nanvalue=np.nan,
                  image_save_path=None,
                  image_name='pca.png'):
        raster = rasterio.open(image_path)
        width = raster.meta["width"]
        height = raster.meta["height"]
        shape = (height, width)

        counts = raster.meta['count']
        bands_opened = []
        cnt = 1
        for i in range(counts):
            if (cnt in exception) == True:
                pass
            else:
                array = raster.read(cnt).flatten()
                array = np.nan_to_num(array)
                bands_opened.append(array)
            cnt += 1

        bands_stacked = np.dstack(tuple(bands_opened))
        pca = PCA(n_components)
        pca.fit(bands_stacked[0])
        variance = pca.explained_variance_
        totalVariance = np.sum(variance)
        variance = variance / totalVariance * 100

        fig, ax = plt.subplots()

        ax.plot(variance)
        ax.set_xlabel("Components of PCA")
        ax.set_ylabel("Variance explained [%]")

        pca_image = pca.transform(bands_stacked[0])

        first_component = self.nan_mask(image_path,
                                        pca_image[:,
                                                  0].reshape(shape), nanvalue)
        second_component = self.nan_mask(image_path,
                                         pca_image[:,
                                                   1].reshape(shape), nanvalue)
        third_component = self.nan_mask(image_path,
                                        pca_image[:,
                                                  2].reshape(shape), nanvalue)

        if RGBoption == True:
            self.visualize([0, 1, 2],
                           array=np.stack([
                               first_component, second_component,
                               third_component
                           ]),
                           image_save_path=image_save_path,
                           image_name=image_name)
        else:
            first_component = (255 / np.nanmax(first_component) *
                               first_component).astype(np.uint8)
            image = Image.fromarray(first_component)
            image = ImageOps.equalize(image)
            image.show()
            if image_save_path != None:
                image.save(image_save_path + '/' + image_name)
            else:
                pass

        if return_arrays == True:
            return [
                pca_image[:, i].reshape(shape) for i in range(n_components)
            ]
        else:
            pass

    def visualize(self,
                  rgb_band,
                  array=None,
                  image_path=None,
                  nanvalue=np.nan,
                  image_save_path=None,
                  image_name='saved_image.png'):
        if image_path != None:
            raster = rasterio.open(image_path)
            R = raster.read(rgb_band[0])
            G = raster.read(rgb_band[1])
            B = raster.read(rgb_band[2])

            R = self.nan_mask(image_path, R, nanvalue)
            G = self.nan_mask(image_path, G, nanvalue)
            B = self.nan_mask(image_path, B, nanvalue)

            R = (255 / np.nanmax(R) * R).astype(np.uint8)
            G = (255 / np.nanmax(G) * G).astype(np.uint8)
            B = (255 / np.nanmax(B) * B).astype(np.uint8)

            image_stack = Image.fromarray(np.dstack((R, G, B)))
            image = ImageOps.equalize(image_stack)
            image.show()
        else:
            R = array[rgb_band[0]]
            G = array[rgb_band[1]]
            B = array[rgb_band[2]]

            R = (255 / np.nanmax(R) * R).astype(np.uint8)
            G = (255 / np.nanmax(G) * G).astype(np.uint8)
            B = (255 / np.nanmax(B) * B).astype(np.uint8)

            image_stack = Image.fromarray(np.dstack((R, G, B)))
            image = ImageOps.equalize(image_stack)
            image.show()

        if image_save_path != None:
            image.save(image_save_path + '/' + image_name)
        else:
            pass

    def un_supervised_classification(
            self,
            path_to_image,
            output_path,
            input_data=[],
            method='GaussianMixture',
            n=30,
            num_points=1000,
            preview=True,
            output_file_name='un_supervised_classification',
            params=None,
            nanvalue=np.nan,
            cmap='jet'):

        if len(input_data)!=0:
            input_data = input_data
            data = input_data['extracted_values']
        else:
            values = []
            raster = rasterio.open(path_to_image)
            counts = raster.meta['count']
            array_list=[raster.read(i+1) for i in range(counts)]
            bounds = raster.bounds
            xmin = bounds[0]
            xmax = bounds[2]
            ymin = bounds[1]
            ymax = bounds[3]

            cnt=0
            while len(values) < num_points:
                x = np.random.uniform(xmin, xmax)
                y = np.random.uniform(ymin, ymax)
                val_list = []
                for i in range(counts):
                    array=array_list[i]
                    val = array[raster.index(x, y)]
                    val_list.append(val)
                if np.isnan(val_list).any() == True:
                    pass
                else:
                    values.append(val_list)
            del raster
            data=values

        data = [spectrum for spectrum in data]
        X = np.array(data)
        print(X.shape)

        if method == 'GaussianMixture':
            if params != None:
                model = GaussianMixture(**params).fit(X)
            else:
                model = GaussianMixture(n_components=n).fit(X)
        elif method == 'KMeans':
            if params != None:
                model = KMeans(**params).fit(X)
            else:
                model = KMeans(n_clusters=n).fit(X)
        else:
            print(
                'The available methods are either GaussianMixture or KMeans.')

        raster = rasterio.open(path_to_image)
        counts = raster.meta['count']

        image_array = []
        for i in range(counts):
            image_array.append(raster.read(i + 1))

        cluster_output = []

        for i in tqdm(range(image_array[0].shape[0])):
            spectrum_data_at_row_i = []
            spectrum_data_at_row_i_nan_check = []
            for m in range(counts):
                spectrum_data_at_row_i.append(np.nan_to_num(image_array[m][i]))
                spectrum_data_at_row_i_nan_check.append(image_array[m][i])

            spectrum_data_at_row_i_T = np.transpose(
                np.array(spectrum_data_at_row_i))
            spectrum_data_at_row_i_nan_check_T = np.transpose(
                np.array(spectrum_data_at_row_i_nan_check))

            nan_ind = np.where(np.isnan(spectrum_data_at_row_i_nan_check_T))[0]
            classified = np.transpose(
                model.predict(spectrum_data_at_row_i_T)).astype(np.float)
            classified[nan_ind] = nanvalue
            cluster_output.append(classified)

        output_image = np.array(cluster_output)

        output_tif_name = output_file_name + '_' + method + '.tif'

        with rasterio.open(output_path + '/' + output_tif_name,
                           'w',
                           height=output_image.shape[0],
                           width=output_image.shape[1],
                           driver='GTiff',
                           count=1,
                           crs=raster.crs,
                           transform=raster.transform,
                           dtype=output_image.dtype) as output:
            output.write(output_image, 1)
            output.close()

        if preview == True:
            fig, ax = plt.subplots(figsize=(15, 15))
            rasterio.plot.show(output_image, ax=ax, cmap=cmap)
        else:
            pass

        del raster

    def supervised_classification_test(self,
                                      train_data_path=None,
                                      input_data=[],
                                      method='RandomForest',
                                      num_points=1000,
                                      test_size=0.2,
                                      params={}):

        if len(input_data)!=0:
            input_data = input_data
        else:
            input_data= self.train_data_process(train_data_path, path_to_image,num_points)

        data = input_data['extracted_values']
        data = [spectrum for spectrum in data]
        label = input_data['lulc_class']
        label = [l for l in label]

        X = np.array(data)
        y = np.array(label)

        X_train, X_test, y_train, y_test = train_test_split(X,
                                                            y,
                                                            test_size=0.2)

        if method == 'RandomForest':
            model = RandomForestClassifier(**params)
        elif method == 'NeuralNetwork':
            model = MLPClassifier(**params)
        elif method == 'KNeighbors':
            model = KNeighborsClassifier(**params)
        elif method == 'GradientBoosting':
            model = GradientBoostingClassifier(**params)
        else:
            print(
                'The available methods are either RandomForest, NeuralNetwork, KNeighbors, or GradientBoosting.'
            )

        model.fit(X_train, y_train)

        confusion_matrix = metrics.confusion_matrix(y_test,
                                                    model.predict(X_test))
        accuracy_train = metrics.accuracy_score(y_train, model.predict(X_train))
        accuracy_test = metrics.accuracy_score(y_test, model.predict(X_test))
        kappa = metrics.cohen_kappa_score(y_test, model.predict(X_test))

        print(f'Confusion matrix is:')
        print(confusion_matrix)
        print(f'Accuracy on train {accuracy_train:.5f}')
        print(f'Accuracy on test {accuracy_test:.5f}')
        print(f'Kappa coefficient {kappa:.5f}')

    def supervised_classification(self,
                                  path_to_image,
                                  output_path,
                                  train_data_path=None,
                                  input_data=[],
                                  method='RandomForest',
                                  num_points=1000,
                                  preview=True,
                                  output_file_name='supervised_classification',
                                  test_size=0.2,
                                  params={},
                                  nanvalue=np.nan,
                                  cmap='jet'):

        if len(input_data)!=0:
            input_data = input_data
        else:
            input_data= self.train_data_process(train_data_path, path_to_image,num_points)

        data = input_data['extracted_values']
        data = [spectrum for spectrum in data]
        label = input_data['lulc_class']
        label = [l for l in label]

        X = np.array(data)
        y = np.array(label)

        X_train, X_test, y_train, y_test = train_test_split(X,
                                                            y,
                                                            test_size=0.2)

        if method == 'RandomForest':
            model = RandomForestClassifier(**params)
        elif method == 'NeuralNetwork':
            model = MLPClassifier(**params)
        elif method == 'KNeighbors':
            model = KNeighborsClassifier(**params)
        elif method == 'GradientBoosting':
            model = GradientBoostingClassifier(**params)
        else:
            print(
                'The available methods are either RandomForest, NeuralNetwork, Kneighbors, or GradientBoosting.'
            )

        model.fit(X_train, y_train)

        confusion_matrix = metrics.confusion_matrix(y_test,
                                                    model.predict(X_test))
        accuracy = metrics.accuracy_score(y_test, model.predict(X_test))
        kappa = metrics.cohen_kappa_score(y_test, model.predict(X_test))

        print(f'Confusion matrix is:')
        print(confusion_matrix)
        print(f'Accuracy {accuracy:.5f}')
        print(f'Kappa coefficient {kappa:.5f}')

        raster = rasterio.open(path_to_image)
        counts = raster.meta['count']

        image_array = []
        for i in range(counts):
            image_array.append(raster.read(i + 1))

        classified_output = []

        for i in tqdm(range(image_array[0].shape[0])):
            spectrum_data_at_row_i = []
            spectrum_data_at_row_i_nan_check = []
            for m in range(counts):
                spectrum_data_at_row_i.append(np.nan_to_num(image_array[m][i]))
                spectrum_data_at_row_i_nan_check.append(image_array[m][i])

            spectrum_data_at_row_i_T = np.transpose(
                np.array(spectrum_data_at_row_i))
            spectrum_data_at_row_i_nan_check_T = np.transpose(
                np.array(spectrum_data_at_row_i_nan_check))

            nan_ind = np.where(np.isnan(spectrum_data_at_row_i_nan_check_T))[0]

            classified = np.transpose(
                model.predict(spectrum_data_at_row_i_T)).astype(np.float)
            classified[nan_ind] = nanvalue
            classified_output.append(classified)

        output_image = np.array(classified_output)
        output_tif_name = output_file_name + '_' + method + '.tif'

        with rasterio.open(output_path + '/' + output_tif_name,
                           'w',
                           height=output_image.shape[0],
                           width=output_image.shape[1],
                           driver='GTiff',
                           count=1,
                           crs=raster.crs,
                           transform=raster.transform,
                           dtype=output_image.dtype) as output:
            output.write(output_image, 1)
            output.close()

        if preview == True:
            fig, ax = plt.subplots(figsize=(15, 15))
            rasterio.plot.show(output_image, ax=ax, cmap=cmap)
        else:
            pass

        del raster

    def nan_mask(self, path_to_image, input_array, nanvalue):
        raster = rasterio.open(path_to_image)
        counts = raster.meta['count']

        image_array = []
        for i in range(counts):
            image_array.append(raster.read(i + 1))

        nan_mask = []

        for i in range(image_array[0].shape[0]):
            spectrum_data_at_row_i_nan_check = []
            mask = np.zeros(image_array[0].shape[1])

            for m in range(counts):
                spectrum_data_at_row_i_nan_check.append(image_array[m][i])

            spectrum_data_at_row_i_nan_check_T = np.transpose(
                np.array(spectrum_data_at_row_i_nan_check))

            nan_ind = np.where(np.isnan(spectrum_data_at_row_i_nan_check_T))[0]

            mask[nan_ind] = 1
            nan_mask.append(mask)

        nan_mask = np.array(nan_mask)

        idx = np.where(nan_mask == 1)
        input_array[idx] = nanvalue

        return input_array

    def create_composite(self,
                         path_to_image_folder,
                         output_path,
                         singleband=True,
                         merge_method='mean',
                         merge_image_name='merged_by_'):
        file_list = glob(path_to_image_folder + '/*')
        if singleband == True:
            with rasterio.open(file_list[0]) as opened:
                ref = opened
                crs=opened.meta['crs']
                shape = opened.read(1).shape
            opened_array_list = []
            for file in file_list:
                with rasterio.open(file) as opened:
                    opened_array = opened.read(1).flatten()
                    opened_array_list.append(opened_array)
            if merge_method == 'mean':
                output_array = np.nanmean(opened_array_list, axis=0)
            elif merge_method == 'max':
                output_array = np.nanmax(opened_array_list, axis=0)
            elif merge_method == 'min':
                output_array = np.nanmin(opened_array_list, axis=0)
            else:
                print('The available merging methods are mean, max, or min.')
            output_array = output_array.reshape(shape)
            with rasterio.open(output_path +
                               f"/{merge_image_name}{merge_method}.tif",
                               'w',
                               driver='GTiff',
                               width=output_array.shape[1],
                               height=output_array.shape[0],
                               count=1,
                               crs=crs,
                               transform=ref.transform,
                               dtype=output_array.dtype) as output:
                output.write(output_array, 1)
                output.close()
        else:
            with rasterio.open(file_list[0]) as opened:
                ref = opened
                shape = (opened.meta['height'], opened.meta['width'])
                count = opened.meta['count']
                descriptions = opened.descriptions
            band_array_list = []
            for i in range(count):
                opened_array_list = []
                for file in file_list:
                    with rasterio.open(file) as opened:
                        opened_array = opened.read(i + 1).flatten()
                        opened_array_list.append(opened_array)
                if merge_method == 'mean':
                    output_array = np.nanmean(opened_array_list, axis=0)
                elif merge_method == 'max':
                    output_array = np.nanmax(opened_array_list, axis=0)
                elif merge_method == 'min':
                    output_array = np.nanmin(opened_array_list, axis=0)
                else:
                    print(
                        'The available merging methods are mean, max, or min.')
                output_array = output_array.reshape(shape)
                band_array_list.append(output_array)
            with rasterio.open(output_path +
                               f"/{merge_image_name}{merge_method}.tif",
                               'w',
                               driver='GTiff',
                               width=shape[1],
                               height=shape[0],
                               count=count,
                               crs=crs,
                               transform=ref.transform,
                               dtype=output_array.dtype) as output:
                for i in range(count):
                    output.write(band_array_list[i], i + 1)
                    output.set_band_description(i + 1, descriptions[i])
                output.close()

    def clip(self, path_to_image, path_to_shapefile, path_to_output,nodata=np.nan):
        with fiona.open(path_to_shapefile, 'r') as shapefile:
            shapes = [feature['geometry'] for feature in shapefile]

        with rasterio.open(path_to_image) as src:
            out_image, out_transform = rasterio.mask.mask(src,
                                                          shapes,
                                                          crop=True,nodata=np.nan)
            out_meta = src.meta

        out_meta.update({
            'driver': 'GTiff',
            'height': out_image.shape[1],
            'width': out_image.shape[2],
            'transform': out_transform
        })

        filename=os.path.splitext(os.path.basename(path_to_image))[0]
        with rasterio.open(path_to_output+'/'+filename+'_clipped.tif','w',**out_meta) as opened:
            opened.write(out_image)

    def combine_bands(self,path_to_folder,path_to_output,output_filename='combined',remove=True,dtype=None):
        files=glob(path_to_folder+'/*')

        with rasterio.open(files[0]) as ref:
            crs=ref.meta['crs']
            width=ref.meta['width']
            height=ref.meta['height']
            transform=ref.transform
            if dtype==None:
                dtype=ref.read(1).dtype
            else:
                pass

        with rasterio.open(path_to_output+'/'+output_filename+'.tif',
                           'w',
                           driver='GTiff',
                           width=width,
                           height=height,
                           count=len(files),
                           crs=crs,
                           transform=transform,
                           dtype=dtype) as opened:
            cnt=1
            for file in files:
                with rasterio.open(file) as src:
                    output_raster=src.read(1)
                    src.close()
                opened.write(output_raster,cnt)
                band_name=os.path.splitext(os.path.basename(file))[0]
                opened.set_band_description(cnt,band_name)
                cnt+=1
            opened.close()

        if remove==True:
            for file in files:
                try:
                    os.remove(file)
                except:
                    time.sleep(3)
                    os.remove(file)

        else:
            pass

    def reprojection_to_crs(self,path_to_image,dst_crs='EPSG:4326',remove=False):
        epsg='_crs_'+dst_crs.replace('EPSG:','')
        dst_path=path_to_image.replace(os.path.basename(path_to_image),'')
        filename=os.path.splitext(os.path.basename(path_to_image))[0]
        with rasterio.open(path_to_image) as src:
            transform, width, height = calculate_default_transform(src.crs, dst_crs, src.width, src.height, *src.bounds)
            meta = src.meta.copy()
            meta.update({
                'crs': dst_crs,
                'transform': transform,
                'width': width,
                'height': height
            })

            with rasterio.open(dst_path+filename+epsg+'.tif', 'w', **meta) as dst:
                for i in range(1, src.count + 1):
                    reproject(
                        source=rasterio.band(src, i),
                        destination=rasterio.band(dst, i),
                        src_transform=src.transform,
                        src_crs=src.crs,
                        dst_transform=transform,
                        dst_crs=dst_crs,
                        resampling=Resampling.nearest)
        if remove==True:
            os.remove(path_to_image)
        else:
            pass

    def align_raster(self,path_to_ref_image,path_to_target_image,remove=True,nodata=np.nan):
        with rasterio.open(path_to_ref_image) as ref:
            bounds=ref.bounds
            height=ref.meta["height"]
            width=ref.meta["width"]
            crs=ref.meta["crs"]
            transform=ref.meta["transform"]

        bbox = box(bounds[0], bounds[1], bounds[2], bounds[3])
        geo = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=crs)
        geo = geo.to_crs(crs=crs)
        coords=[json.loads(geo.to_json())['features'][0]['geometry']]

        dst_path=path_to_target_image.replace(os.path.basename(path_to_target_image),'')
        filename=os.path.splitext(os.path.basename(path_to_target_image))[0]
        os.mkdir(dst_path+'/temp')

        with rasterio.open(path_to_target_image) as src:
            out_img, out_transform = rasterio.mask.mask(src, coords, crop=True,filled=False,nodata=nodata)
            src_crs=src.crs
            src_count=src.count
            dtype=out_img.dtype

        with rasterio.open(dst_path+'/temp'+f'/{filename}_clipped.tif','w',driver='GTiff',
                           width=out_img.shape[2],
                           height=out_img.shape[1],
                           count=src_count,
                           crs=src_crs,
                           transform=out_transform,
                           dtype=dtype) as output:
            for i in range(src_count):
                output.write(out_img[i],i+1)
            output.close()

        with rasterio.open(dst_path+'/temp'+f'/{filename}_clipped.tif') as src_clipped:
            clipped_resampled=src_clipped.read(out_shape=(height,width),resampling=Resampling.nearest)

        with rasterio.open(dst_path+f'/{filename}_aligned.tif',
                           'w',
                           driver='GTiff',
                           width=width,
                           height=height,
                           count=src_count,
                           crs=crs,
                           transform=transform,
                           dtype=dtype) as dst:
            for i in range(src_count):
                dst.write(clipped_resampled[i],i+1)
            dst.close()

        shutil.rmtree(dst_path+'/temp')

        if remove==True:
            os.remove(path_to_target_image)
        else:
            pass


#!/bin/python3
from pwn import *

elf = context.binary = ELF('shell')
context.terminal = ["tmux", "splitw", "-h"]
p = process(elf.path)
gdb.attach(p)
sc = asm("""
    mov rdx, 0x40
    lea rsi, [rbp]
    xor rdi, rdi
    syscall
""")

print(sc)
p.sendline(sc)
#p.sendline(b'\x90' *offset +  asm(shellcraft.sh()))
#p.interactive()


#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultLocation."""

from telegram import InlineQueryResult

class InlineQueryResultLocation(InlineQueryResult):
    """
    Represents a location on a map. By default, the location will be sent by the user.
    Alternatively, you can use :attr:`input_message_content` to send a message with the specified
    content instead of the location.

    Attributes:
        type (:obj:`str`): 'location'.
        id (:obj:`str`): Unique identifier for this result, 1-64 bytes.
        latitude (:obj:`float`): Location latitude in degrees.
        longitude (:obj:`float`): Location longitude in degrees.
        title (:obj:`str`): Location title.
        live_period (:obj:`int`): Optional. Period in seconds for which the location can be
            updated, should be between 60 and 86400.
        reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
            to the message.
        input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
            message to be sent instead of the location.
        thumb_url (:obj:`str`): Optional. Url of the thumbnail for the result.
        thumb_width (:obj:`int`): Optional. Thumbnail width.
        thumb_height (:obj:`int`): Optional. Thumbnail height.

    Args:
        id (:obj:`str`): Unique identifier for this result, 1-64 bytes.
        latitude (:obj:`float`): Location latitude in degrees.
        longitude (:obj:`float`): Location longitude in degrees.
        title (:obj:`str`): Location title.
        live_period (:obj:`int`, optional): Period in seconds for which the location can be
            updated, should be between 60 and 86400.
        reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
            to the message.
        input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
            message to be sent instead of the location.
        thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
        thumb_width (:obj:`int`, optional): Thumbnail width.
        thumb_height (:obj:`int`, optional): Thumbnail height.
        **kwargs (:obj:`dict`): Arbitrary keyword arguments.

    """

    def __init__(self,
                 id,
                 latitude,
                 longitude,
                 title,
                 live_period=None,
                 reply_markup=None,
                 input_message_content=None,
                 thumb_url=None,
                 thumb_width=None,
                 thumb_height=None,
                 **kwargs):
        # Required
        super(InlineQueryResultLocation, self).__init__('location', id)
        self.latitude = latitude
        self.longitude = longitude
        self.title = title

        # Optionals
        if live_period:
            self.live_period = live_period
        if reply_markup:
            self.reply_markup = reply_markup
        if input_message_content:
            self.input_message_content = input_message_content
        if thumb_url:
            self.thumb_url = thumb_url
        if thumb_width:
            self.thumb_width = thumb_width
        if thumb_height:
            self.thumb_height = thumb_height


from __future__ import division
import numpy as numpy
import cv2
import math as math

def prepareHough(frame, gray, video):

    kernel = numpy.ones((2, 2), numpy.uint8)

    if video == 'videos/video-3.avi' or video=='videos/video-8.avi':
        gray = cv2.erode(gray, kernel)
    #gray = cv2.morphologyEx(frame, cv2.MORPH_CLOSE, kernel)

    edges = cv2.Canny(gray,50,150,apertureSize = 3)
    minLineLength = 400
    maxLineGap = 5

    lines = cv2.HoughLinesP(edges,1,numpy.pi/180,50,minLineLength,maxLineGap)

    #a,b,c = lines.shape
    #for i in range(a):
        #cv2.line(frame, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA)
    #cv2.imshow('result', frame)
    #cv2.waitKey()
    #lineNumber = len(lines)
    #cv2.imshow('edges', edges)

    if video=='videos/video-3.avi':
        return appendLines3(lines,frame)
    return appendLines(lines, frame)

def appendLines(lines, frame):
    lineNumber = len(lines)
    resenFrame = frame

    lowerLinePoints = []
    upperLinePoints = []

    minx=lines[0][0][0]
    miny=lines[0][0][1]
    maxx=lines[0][0][2]
    maxy=lines[0][0][3]

    distance = math.sqrt(math.pow(minx-maxx,2) + math.pow(miny-maxy,2))

    #MIN I MAX OBE LINIJE ZAJEDNO
    for i in range(lineNumber-1):
        for j in range (lineNumber):
            x1 = lines[i][0][0]
            y1 = lines[i][0][1]
            x2 = lines[j][0][2]
            y2 = lines[j][0][3]

            tempd = math.sqrt(math.pow(x2-x1,2) + math.pow(y2-y1,2))
            if tempd > distance:
                distance = tempd
                minx = x1
                miny = y1
                maxx = x2
                maxy = y2

    middle_pointx = (minx+maxx)/2
    middle_pointy = (miny+maxy)/2

    print("MINIMUM IS : ", minx,miny)
    print("MAXIMUM IS : ", maxx, maxy)
    print("MIDDLE IS : ", middle_pointx, middle_pointy)

    middle_pointx = int(middle_pointx)
    middle_pointy = int(middle_pointy)
    cv2.circle(resenFrame, (middle_pointx, middle_pointy), 2, (0, 0, 255), 3)

    points1 = []
    points2 = []

    for i in range(lineNumber):
        x1 = lines[i][0][0]
        y1 = lines[i][0][1]

        list_item = lines[i][0][0], lines[i][0][1], lines[i][0][2], lines[i][0][3]
        if y1<=middle_pointy:
            points1.append(list_item)
        if abs(y1-middle_pointy)<30:
            points1.append(list_item)
        if abs(y1-middle_pointy)<20:
            points2.append(list_item)
        if y1>=middle_pointy:
            points2.append(list_item)

    minxp1 = points1[0][0]
    minyp1 = points1[0][1]
    maxxp1 = points1[0][2]
    maxyp1 = points1[0][3]

    for i in range(len(points1)):
        x1 = points1[i][0]
        y1 = points1[i][1]
        x2 = points1[i][2]
        y2 = points1[i][3]

        if x1<minxp1:
            minxp1 = x1
            minyp1 = y1
        if x2>maxxp1:
            maxxp1 = x2
            maxyp1 = y2
    cv2.line(resenFrame,(minxp1,minyp1),(maxxp1, maxyp1), (0, 255, 255),3)

    appendItem = minxp1, minyp1, maxxp1, maxyp1
    upperLinePoints.append(appendItem)

    minxp2 = points2[0][0]
    minyp2 = points2[0][1]
    maxxp2 = points2[0][2]
    maxyp2 = points2[0][3]

    for i in range(len(points2)):
        x1 = points2[i][0]
        y1 = points2[i][1]
        x2 = points2[i][2]
        y2 = points2[i][3]

        if x1 < minxp2:
            minxp2 = x1
            minyp2 = y1
        if x2 > maxxp2:
            maxxp2 = x2
            maxyp2 = y2
    cv2.line(resenFrame, (minxp2, minyp2), (maxxp2, maxyp2), (255, 0, 255), 3)
    cv2.imshow('Result',resenFrame)
    cv2.imwrite("lineDetected.jpg", resenFrame);

    appendItem = minxp2, minyp2, maxxp2, maxyp2
    lowerLinePoints.append(appendItem)

    cv2.line(frame,(minx, miny), (maxx,maxy), (0,255,255),3)
    cv2.waitKey()
    return lowerLinePoints, upperLinePoints

def appendLines3(lines,frame):
    lineNumber = len(lines)
    resenFrame = frame

    lowerLinePoints = []
    upperLinePoints = []

    x1k = lines[0][0][0]
    y1k = lines[0][0][1]
    x2k = lines[0][0][2]
    y2k = lines[0][0][3]

    k = ((y2k - y1k) / (x2k - x1k))
    n1 = y1k - k * x1k

    x1m = lines[lineNumber - 1][0][0]
    y1m = lines[lineNumber - 1][0][1]
    x2m = lines[lineNumber - 1][0][2]
    y2m = lines[lineNumber - 1][0][3]

    m = ((y2m - y1m) / (x2m - x1m))
    n2 = y1m - k * x1m

    first_line = []
    second_line = []

    minx = lines[0][0][0]
    miny = lines[0][0][1]
    maxx = lines[0][0][2]
    maxy = lines[0][0][3]

    for i in range(lineNumber):
        x1 = lines[i][0][0]
        y1 = lines[i][0][1]
        x2 = lines[i][0][2]
        y2 = lines[i][0][3]

        i_k = (y2 - y1) / (x2 - x1)
        i_n = y1-i_k*x1

        list_item = lines[i][0][0], lines[i][0][1], lines[i][0][2], lines[i][0][3]
        if abs(n1-i_n)<10:
            first_line.append(list_item)
        if abs(n1-i_n)>20:
            second_line.append(list_item)

        #cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 3)
        #cv2.imshow('test',frame);
        #cv2.waitKey()
    sminx = second_line[0][0]
    sminy = second_line[0][1]
    smaxx = second_line[0][2]
    smaxy = second_line[0][3]

    first_line_lenght = len(first_line)
    second_line_lenght = len(second_line)

    for i in range(second_line_lenght):
        x1 = second_line[i][0]
        y1 = second_line[i][1]
        x2 = second_line[i][2]
        y2 = second_line[i][3]
        if x1<sminx:
            sminx = x1
            sminy = y1
        if x2>smaxx:
            smaxx=x2
            smaxy=y2
    cv2.line(frame,(sminx, sminy), (smaxx,smaxy), (0,255,255),3)
    appendItem = sminx, sminy, smaxx, smaxy
    upperLinePoints.append(appendItem)
    #cv2.imshow("linije", frame)
    #cv2.waitKey()

    ssminx = first_line[0][0]
    ssminy = first_line[0][1]
    ssmaxx = first_line[0][2]
    ssmaxy = first_line[0][3]

    for i in range(first_line_lenght):
        x1 = first_line[i][0]
        y1 = first_line[i][1]
        x2 = first_line[i][2]
        y2 = first_line[i][3]
        if x1 < ssminx:
            ssminx = x1
            ssminy = y1
        if x2 > ssmaxx:
            ssmaxx = x2
            ssmaxy = y2
    cv2.line(frame, (ssminx, ssminy), (ssmaxx, ssmaxy), (255, 0, 255), 3)
    appendItem = ssminx, ssminy, ssmaxx, ssmaxy
    lowerLinePoints.append(appendItem)
    cv2.imshow("linije", frame)
    cv2.waitKey()

    return lowerLinePoints, upperLinePoints


import openpyxl

# 1) 엑셀 만들기
wb = openpyxl.Workbook()

# 2) 엑셀 워크시트 만들기

ws = wb.create_sheet('학생 정보')

# 3) 데이터 추가하기

ws['A1'] = '학번'
ws['B1'] = '이름'

ws['A2'] = 2020123456
ws['B2'] = '백준호'

# 4) 엑셀 저장하기

wb.save(r'학생정보.xlsx')


from pydantic import BaseSettings

class DevConfig(BaseSettings):

    # secret used for signing JWT tokens
    JWT_SECRET: str

    # hash of payload with pow_token must start with {POW_DIFFICULTY} 0 bits
    POW_DIFFICULTY: int

    # db uri like postgres://user:password@host:port/db-name
    DATABASE_URI: str

    # display name of this service instance
    SERVICE_NAME: str

    class Config:
        case_sensitive = True
        env_file = ".env"
        env_file_encoding = "utf-8"

settings = DevConfig()


billete_50 = 0
billete_20 = 0
billete_10 = 0
billete_5 = 0
moneda_2 = 0
moneda_1 = 0

num = int(input('Dame una cantidad en euros: '))
while num > 0:
    if num >= 50:
        billete_50 = billete_50 + 1
        num = num - 50
    elif num >= 20:
        billete_20 = billete_20 + 1
        num = num - 20
    elif num >= 10:
        billete_10 = billete_10 + 1
        num = num - 10
    elif num >= 5:
        billete_5 = billete_5 + 1
        num = num - 5
    elif num >= 2:
        moneda_2 = moneda_2 + 1
        num = num - 2
    elif num >= 1:
        moneda_1 = moneda_1 + 1
        num = num - 1

print("Billetes de 50: " + str(billete_50))
print("Billetes de 20: " + str(billete_20))
print("Billetes de 10: " + str(billete_10))
print("Billetes de 5: " + str(billete_5))
print("Monedas de 2: " + str(moneda_2))
print("Monedas de 1: " + str(moneda_1))


class Solution(object):
    def partition(self, s):
        if not s:
            return [[]]
        ans = []

        for i in range(1, len(s) + 1):
            if s[:i] == s[:i][::-1]:
                for j in self.partition(s[i:]):
                    ans.append([s[:i]] + j)
        return ans


"""
计算两幅图的梯度图的Bce_loss
"""
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

def show_tensor(image):
    gt = image["gt"]
    gt_sobel = image["gt_sobel"]
    pred_sobel = image["pred_sobel"]
    plt.subplot(1, 3, 1).imshow(gt[0, 0, :, :].detach().cpu().numpy())
    plt.subplot(1, 3, 2).imshow(gt_sobel[0, 0, :, :].detach().cpu().numpy())
    plt.subplot(1, 3, 3).imshow(pred_sobel[0, 0, :, :].detach().cpu().numpy())
    plt.show()

def compute_loss_and_metrics(images):
    """
    This part compute loss and metrics for the generator
    """
    grad_loss = F.l1_loss(images['gt_sobel'], images['pred_sobel'])
    # 取总体差的平方，适用于两组图不对应的情况
    # grad_loss = (torch.mean(images['gt_sobel']) - torch.mean(images['pred_sobel'])) ** 2
    return grad_loss

class SobelOperator(nn.Module):
    def __init__(self, epsilon):
        super().__init__()
        self.epsilon = epsilon

        x_kernel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) / 4
        self.conv_x = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
        self.conv_x.weight.data = torch.tensor(x_kernel).unsqueeze(0).unsqueeze(0).float().cuda()
        self.conv_x.weight.requires_grad = False

        y_kernel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) / 4
        self.conv_y = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
        self.conv_y.weight.data = torch.tensor(y_kernel).unsqueeze(0).unsqueeze(0).float().cuda()
        self.conv_y.weight.requires_grad = False

    def forward(self, x):
        b, c, h, w = x.shape
        if c > 1:
            x = x.view(b * c, 1, h, w)

        x = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)

        grad_x = self.conv_x(x)
        grad_y = self.conv_y(x)

        x = torch.sqrt(grad_x ** 2 + grad_y ** 2 + self.epsilon)
        x = x.view(b, c, h, w)

        return x

class SobelComputer:
    def __init__(self):
        self.sobel = SobelOperator(1e-4)

    def compute_edges(self, images):
        images['gt_sobel'] = self.sobel(images['gt'])
        images['pred_sobel'] = self.sobel(images['pred'])


# 物体検出スクリプトをテストするための画像を作る
# アノテーションファイルも作る
import cv2
import numpy as np
import random

w = 640
h = 480
N = 1000
tsize = 40
classesN = 0

fout = open("annotation.txt", "w") # txtファイルを書き込みモードで作成

for i in range(N):
    img = np.ones((h,w,3), np.uint8)
    img = img * 255

    for c in range(100):
        hr = random.randint(0, h)
        wr = random.randint(0, w)
        radr = random.randint(0, 100)
        rr = random.randint(0, 255)
        gr = random.randint(0, 255)
        br = random.randint(0, 255)
        img = cv2.circle(img,(wr,hr), radr, (rr,gr,br), -1)

    hr = random.randint(0, h-tsize)
    wr = random.randint(0, w-tsize)

    pts = np.array([[wr+tsize/2,hr],[wr,hr+tsize],[wr+tsize,hr+tsize]], np.int32)
    pts = pts.reshape((-1,1,2))
    #img = cv2.polylines(img,[pts],True,(0,0,0))
    img = cv2.fillConvexPoly(img, pts, (0,0,0))

    #画像を保存
    imname = 'JPG/' + 'img' + str(i) + '.jpg'
    cv2.imwrite(imname, img)
    #アノテーションファイルに記録
    annostr = 'model_data/' + imname + ' ' + str(wr) + ','  + str(hr) + ','  + str(wr+tsize) + ',' + str(hr+tsize) + ',' + str(classesN)
    fout.writelines(annostr + "\n")

fout.close()


import pygame,sys       #import modules

screen_w = 500
screen_h = 600

colors = {              #definition of basics colors
    "black":(0,0,0),
    "white":(255,255,255),
    "red":(255,0,0),
    "blue":(0,255,0),
    "green":(0,0,255),
    }

pygame.init()
window = pygame.display.set_mode((screen_h,screen_w)) #window creation
game = True

grass = pygame.image.load("grass.png")

snake = pygame.image.load("snake.png")

position_snake = snake.get_rect()
window.blit(snake, (100, 100))

try:
    while game:

        if pygame.key.get_pressed()[pygame.K_UP]:
            position_snake = position_snake.move(0,-1)
        if pygame.key.get_pressed()[pygame.K_DOWN]:
            position_snake = position_snake.move(0,1)
        if pygame.key.get_pressed()[pygame.K_LEFT]:
            position_snake = position_snake.move(-1,0)
        if pygame.key.get_pressed()[pygame.K_RIGHT]:
            position_snake = position_snake.move(1,0)

        for event in pygame.event.get():
            if event.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE]:  #Escape or exit  is pressed
                game = False #end of the game

        window.fill(colors["black"])
        for i in range (0,50):
            for j in range (0, 32):
                window.blit(grass, (i*16,j*16))

        window.blit(snake, position_snake)
        pygame.display.flip()

except:
    print("Exit error")

finally:
    pygame.quit()
    sys.exit()


def kth_biggest(k, nums, begin, end):
    if k<0 or len(nums)<1 or begin>end or k>end-begin+1:
        return -1
    else:
        # k < end - begin + 1
        pivot = nums[begin];
        head = begin;
        rear = end;
        while head < rear:
            while nums[head] <= pivot and head < rear:
                head += 1
            while nums[rear] > pivot and head < rear:
                rear -= 1
            swap(nums, head, rear)
        # judge nums[head=rear] and pivot
        if nums[head] > pivot:
            num_bigger = end - head + 1
            if num_bigger == k-1:
                return pivot
            elif num_bigger > k-1:
                return kth_biggest(k, nums, head, end)
            else:
                if k == 1:
                    return pivot
                else:
                    return kth_biggest(k-num_bigger, nums, begin, head-1)
        else:
            swap(nums, begin, head)
            num_bigger = end - head
            if num_bigger == k-1:
                return pivot
            elif num_bigger > k-1:
                return kth_biggest(k, nums, head+1, end)
            else:
                if k==1:
                    return pivot
                else:
                    return kth_biggest(k - num_bigger-1, nums, begin, head-1)
    return

def swap(l, p1, p2):
    temp = l[p1];
    l[p1] = l[p2];
    l[p2] = temp;
    return

ll = [1,1,1,1,1,13,4,2,999]
print (kth_biggest(3, ll, 0, len(ll)-1))


import mock

from buildbot.data import buildslaves
from buildbot.test.fake import fakedb
from buildbot.test.fake import fakemaster
from buildbot.test.util import endpoint
from buildbot.test.util import interfaces
from twisted.internet import defer
from twisted.trial import unittest

testData = [
    fakedb.Builder(id=40, name=u'b1'),
    fakedb.Builder(id=41, name=u'b2'),
    fakedb.Master(id=13),
    fakedb.Master(id=14),
    fakedb.BuilderMaster(id=4013, builderid=40, masterid=13),
    fakedb.BuilderMaster(id=4014, builderid=40, masterid=14),
    fakedb.BuilderMaster(id=4113, builderid=41, masterid=13),

    fakedb.Buildslave(id=1, name=u'linux', info={}),
    fakedb.ConfiguredBuildslave(id=14013,
                                buildslaveid=1, buildermasterid=4013),
    fakedb.ConfiguredBuildslave(id=14014,
                                buildslaveid=1, buildermasterid=4014),
    fakedb.ConnectedBuildslave(id=113, masterid=13, buildslaveid=1),

    fakedb.Buildslave(id=2, name=u'windows', info={"a": "b"}),
    fakedb.ConfiguredBuildslave(id=24013,
                                buildslaveid=2, buildermasterid=4013),
    fakedb.ConfiguredBuildslave(id=24014,
                                buildslaveid=2, buildermasterid=4014),
    fakedb.ConfiguredBuildslave(id=24113,
                                buildslaveid=2, buildermasterid=4113),
    fakedb.ConnectedBuildslave(id=214, masterid=14, buildslaveid=2),
]

def _filt(bs, builderid, masterid):
    bs['connected_to'] = sorted(
        [d for d in bs['connected_to']
         if not masterid or masterid == d['masterid']])
    bs['configured_on'] = sorted(
        [d for d in bs['configured_on']
         if (not masterid or masterid == d['masterid'])
         and (not builderid or builderid == d['builderid'])])
    return bs

def bs1(builderid=None, masterid=None):
    return _filt({
        'buildslaveid': 1,
        'name': 'linux',
        'slaveinfo': {},
        'connected_to': [
            {'masterid': 13},
        ],
        'configured_on': sorted([
            {'builderid': 40, 'masterid': 13},
            {'builderid': 40, 'masterid': 14},
        ]),
    }, builderid, masterid)

def bs2(builderid=None, masterid=None):
    return _filt({
        'buildslaveid': 2,
        'name': 'windows',
        'slaveinfo': {'a': 'b'},
        'connected_to': [
            {'masterid': 14},
        ],
        'configured_on': sorted([
            {'builderid': 40, 'masterid': 13},
            {'builderid': 41, 'masterid': 13},
            {'builderid': 40, 'masterid': 14},
        ]),
    }, builderid, masterid)

class BuildslaveEndpoint(endpoint.EndpointMixin, unittest.TestCase):

    endpointClass = buildslaves.BuildslaveEndpoint
    resourceTypeClass = buildslaves.Buildslave

    def setUp(self):
        self.setUpEndpoint()
        return self.db.insertTestData(testData)

    def tearDown(self):
        self.tearDownEndpoint()

    def test_get_existing(self):
        d = self.callGet(('buildslaves', 2))

        @d.addCallback
        def check(buildslave):
            self.validateData(buildslave)
            buildslave['configured_on'].sort()
            self.assertEqual(buildslave, bs2())
        return d

    def test_get_existing_name(self):
        d = self.callGet(('buildslaves', 'linux'))

        @d.addCallback
        def check(buildslave):
            self.validateData(buildslave)
            buildslave['configured_on'].sort()
            self.assertEqual(buildslave, bs1())
        return d

    def test_get_existing_masterid(self):
        d = self.callGet(('masters', 14, 'buildslaves', 2))

        @d.addCallback
        def check(buildslave):
            self.validateData(buildslave)
            buildslave['configured_on'].sort()
            self.assertEqual(buildslave, bs2(masterid=14))
        return d

    def test_get_existing_builderid(self):
        d = self.callGet(('builders', 40, 'buildslaves', 2))

        @d.addCallback
        def check(buildslave):
            self.validateData(buildslave)
            buildslave['configured_on'].sort()
            self.assertEqual(buildslave, bs2(builderid=40))
        return d

    def test_get_existing_masterid_builderid(self):
        d = self.callGet(('masters', 13, 'builders', 40, 'buildslaves', 2))

        @d.addCallback
        def check(buildslave):
            self.validateData(buildslave)
            buildslave['configured_on'].sort()
            self.assertEqual(buildslave, bs2(masterid=13, builderid=40))
        return d

    def test_get_missing(self):
        d = self.callGet(('buildslaves', 99))

        @d.addCallback
        def check(buildslave):
            self.assertEqual(buildslave, None)
        return d

class BuildslavesEndpoint(endpoint.EndpointMixin, unittest.TestCase):

    endpointClass = buildslaves.BuildslavesEndpoint
    resourceTypeClass = buildslaves.Buildslave

    def setUp(self):
        self.setUpEndpoint()
        return self.db.insertTestData(testData)

    def tearDown(self):
        self.tearDownEndpoint()

    def test_get(self):
        d = self.callGet(('buildslaves',))

        @d.addCallback
        def check(buildslaves):
            [self.validateData(b) for b in buildslaves]
            [b['configured_on'].sort() for b in buildslaves]
            self.assertEqual(sorted(buildslaves), sorted([bs1(), bs2()]))
        return d

    def test_get_masterid(self):
        d = self.callGet(('masters', '13', 'buildslaves',))

        @d.addCallback
        def check(buildslaves):
            [self.validateData(b) for b in buildslaves]
            [b['configured_on'].sort() for b in buildslaves]
            self.assertEqual(sorted(buildslaves),
                             sorted([bs1(masterid=13), bs2(masterid=13)]))
        return d

    def test_get_builderid(self):
        d = self.callGet(('builders', '41', 'buildslaves',))

        @d.addCallback
        def check(buildslaves):
            [self.validateData(b) for b in buildslaves]
            [b['configured_on'].sort() for b in buildslaves]
            self.assertEqual(sorted(buildslaves),
                             sorted([bs2(builderid=41)]))
        return d

    def test_get_masterid_builderid(self):
        d = self.callGet(('masters', '13', 'builders', '41', 'buildslaves',))

        @d.addCallback
        def check(buildslaves):
            [self.validateData(b) for b in buildslaves]
            [b['configured_on'].sort() for b in buildslaves]
            self.assertEqual(sorted(buildslaves),
                             sorted([bs2(masterid=13, builderid=41)]))
        return d

class Buildslave(interfaces.InterfaceTests, unittest.TestCase):

    def setUp(self):
        self.master = fakemaster.make_master(testcase=self,
                                             wantMq=True, wantDb=True, wantData=True)
        self.rtype = buildslaves.Buildslave(self.master)
        return self.master.db.insertTestData([
            fakedb.Master(id=13),
            fakedb.Master(id=14),
        ])

    def test_signature_findBuildslaveId(self):
        @self.assertArgSpecMatches(
            self.master.data.updates.findBuildslaveId,  # fake
            self.rtype.findBuildslaveId)  # real
        def findBuildslaveId(self, name):
            pass

    def test_signature_buildslaveConfigured(self):
        @self.assertArgSpecMatches(
            self.master.data.updates.buildslaveConfigured,  # fake
            self.rtype.buildslaveConfigured)  # real
        def buildslaveConfigured(self, buildslaveid, masterid, builderids):
            pass

    def test_findBuildslaveId(self):
        # this just passes through to the db method, so test that
        rv = defer.succeed(None)
        self.master.db.buildslaves.findBuildslaveId = \
            mock.Mock(return_value=rv)
        self.assertIdentical(self.rtype.findBuildslaveId(u'foo'), rv)

    def test_findBuildslaveId_not_id(self):
        self.assertRaises(ValueError, self.rtype.findBuildslaveId, 'foo')
        self.assertRaises(ValueError, self.rtype.findBuildslaveId, u'123/foo')


import bpy
from .select import FocusObject

def DuplicateObject(target):
    """
    Duplicates the given object.
    WARNING - Will also apply the transformation for that object in order to preserve the scale.  </3
    """

    #### Select and make target active
    bpy.ops.object.select_all(action='DESELECT')
    bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
    bpy.ops.object.select_pattern(pattern=target.name)

    # Duplicate the object
    bpy.ops.object.duplicate_move()

    # Now switch the active object to the duplicate
    duplicate = bpy.context.active_object

    # Now set the transform details
    duplicate.rotation_euler = target.rotation_euler
    duplicate.rotation_axis_angle = target.rotation_axis_angle

    # To preserve the scale, it has to be applied.  Sorreh!
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)

def DuplicateObjects(targets):
    """
    Duplicates the given objects.
    WARNING - Will also apply the transformation for the objects in order to preserve the scale.  </3
    """

    #### Select and make target active
    bpy.ops.object.select_all(action='DESELECT')

    for target in targets:
        bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
        bpy.ops.object.select_pattern(pattern=target.name)

    # Duplicate the object
    bpy.ops.object.duplicate_move()

    # Now switch the active object to the duplicate
    duplicate = bpy.context.active_object

    # Now set the transform details
    duplicate.rotation_euler = target.rotation_euler
    duplicate.rotation_axis_angle = target.rotation_axis_angle

    # To preserve the scale, it has to be applied.  Sorreh!
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)

def DeleteObject(target):
    """
    Deletes the given object and removes it from memory.
    """

    # This needs proper data deletion, and all delete operations need to use this
    FocusObject(target)
    bpy.ops.object.delete()

    # Currently removing just in case...
    DeleteObjectByMemory(target)

def DeleteObjectByMemory(target):

    try:
        ob = bpy.data.objects[target.name]

    except:
        ob = None

    if ob != None:
        ob.user_clear()
        bpy.data.objects.remove(ob)

    return

def SwitchObjectMode(newMode, target):
    """
    Forces an object mode switch to the one given, if it isn't already in that mode.
    """

    bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
    prevMode = target.mode
    if target.mode != newMode:
        bpy.context.view_layer.objects.active = bpy.data.objects[target.name]
        bpy.ops.object.mode_set(mode=newMode)
        return prevMode

def FindObjectsWithName(context, object_name):
    """
    Attempts to find an object with the given name in the scene of the given context.
    """

    objects_found = []

    for object in context.scene.objects:
        if object.name.find(object_name) != -1:
            objects_found.append(object)

    return objects_found


from flask import Flask, render_template, url_for, redirect, request, jsonify
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
import marisa_trie

app = Flask(__name__)

# hack to store vocabulary in MARISA Trie
class _MarisaVocabularyMixin(object):

    def fit_transform(self, raw_documents, y=None):
        super(_MarisaVocabularyMixin, self).fit_transform(raw_documents)
        self._freeze_vocabulary()
        return super(_MarisaVocabularyMixin, self).fit_transform(raw_documents, y)

    def _freeze_vocabulary(self):
        if not self.fixed_vocabulary_:
            self.vocabulary_ = marisa_trie.Trie(self.vocabulary_.keys())
            self.fixed_vocabulary_ = True
            del self.stop_words_

class MarisaTfidfVectorizer(_MarisaVocabularyMixin, TfidfVectorizer):
    def fit(self, raw_documents, y=None):
        super(MarisaTfidfVectorizer, self).fit(raw_documents)
        self._freeze_vocabulary()
        return super(MarisaTfidfVectorizer, self).fit(raw_documents, y)

# load the model from disk
loaded_model = pickle.load(open('finalized_model.sav', 'rb'))

data = pickle.load(open('dataframe.sav','rb'))

id_to_category = pickle.load(open('idcategory.sav','rb'))

tfidf = MarisaTfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
features = tfidf.fit_transform(data.text).toarray()

@app.route('/tickets', methods=['POST'])
def json_example():
    texts = []
    request_data = request.get_json()
    texts.append(request.form.get('ticket', ''))
    if(texts[0]==''):
        data_response = {'status':'400'}
        return jsonify(data_response)
    else:
        text_features = tfidf.transform(texts)
        predictions = loaded_model.predict(text_features)
        for text, predicted in zip(texts, predictions):
            print('"{}"'.format(text))
            print("  - Predicted as: '{}'".format(id_to_category[predicted]))
            print("")
            response = id_to_category[predicted]

        data_response = {'status':'200','category':response}

        return jsonify(data_response)

if __name__ == '__main__':
    app.run(host="localhost", debug=True)


# The constructor is a method that is called when an object is created.

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

# points to the first node in the linked list

class LinkedList:
    def __init__(self):
        self.head = None

    def print_list(self):
        if self.head is None:
            print('Empty linked list')
            return

        cur_node = self.head
        llstr = ''

        while cur_node:
            llstr += str(cur_node.data) + '-->'
            cur_node = cur_node.next
        print(llstr)

    def append(self, data):
        new_node = Node(data)

        if self.head is None:
            self.head = new_node
            return

        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = last_node

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def insert_after_node(self, prev_node, data):
        if prev_node:
            print('Previous node does not exist.')
            return
        new_node = Node(data)
        new_node.next = prev_node.next
        prev_node.next = new_node

    def delete_node(self, key):
        cur_node = self.head

        if cur_node and cur_node.data == key:
            self.head = cur_node.next
            cur_node = None
            return

        prev = None
        while cur_node and cur_node.data != key:
            prev = cur_node
        if cur_node is None:
            return

        prev.next = cur_node.next
        cur_node = None

llist = LinkedList()
llist.append('A')
llist.append('B')
llist.append('C')

llist.print_list()

Linked Lists/Singly Linked List/singlyLinked List.py


import os
import random
random.seed(1)

tree_dataset_path = os.path.join('data', 'NTU-stem-dataset')

if __name__ == '__main__':
    class_ = filter(os.path.isdir, [os.path.join(tree_dataset_path, child) for child in os.listdir(tree_dataset_path)])

    for class_id, d in enumerate(class_):
        image_file_list = os.listdir(d)
        class_label = os.path.basename(os.path.dirname(d+'/'))

        random.shuffle(image_file_list)
        image_num = len(image_file_list)

        if image_num < 24:
            train_num = 8
        else:
            train_num = 16

        val_num = (image_num - train_num) // 2 + train_num
        for cnt, image in enumerate(image_file_list):
            image_dir = os.path.join(d, image)
            if cnt < train_num:
                split_ = 'train'
            elif cnt < val_num:
                split_ = 'val'
            else:
                split_ = 'test'
            os.rename(image_dir, os.path.join(d, '{}_{}_{}_{}.jpg'.format(split_, class_id, class_label, cnt)))


# 1304. Find N Unique Integers Sum up to Zero

'''
Given an integer n, return any array containing n unique integers such that they add up to 0.
'''

class Solution:
    def sumZero(self, n: int) -> List[int]:
        res = []
        if n % 2 == 0:
            for i in range(1, n // 2 + 1):
                res.append(i)
                res.append(-i)
            return res
        else:
            res.append(0)
            for i in range(1, n // 2 + 1):
                res.append(i)
                res.append(-i)
            return res


import os
import re
import sys
import logging
import subprocess
from typing import Optional, Dict
from simuleval import options
from simuleval.utils.arguments import cli_argument_list
from simuleval.utils.agent import get_agent_class

logger = logging.getLogger("simuleval.slurm")

def mkdir_output_dir(path: str) -> bool:
    try:
        os.makedirs(path, exist_ok=True)
        return True
    except BaseException as be:
        logger.error(f"Failed to write results to {path}.")
        logger.error(be)
        logger.error("Skip writing predictions.")
        return False

def submit_slurm_job(config_dict: Optional[Dict] = None) -> None:
    if config_dict is not None and "slurm" in config_dict:
        raise RuntimeError("--slurm is only available as a CLI argument")
    parser = options.general_parser()
    cli_arguments = cli_argument_list(config_dict)
    options.add_evaluator_args(parser)
    options.add_scorer_args(parser, cli_arguments)
    options.add_slurm_args(parser)
    options.add_dataloader_args(parser, cli_arguments)
    system_class = get_agent_class(config_dict)
    system_class.add_args(parser)
    args = parser.parse_args(cli_argument_list(config_dict))
    args.output = os.path.abspath(args.output)
    assert mkdir_output_dir(args.output)

    if args.agent is None:
        args.agent = sys.argv[0]

    os.system(f"cp {args.agent} {args.output}/agent.py")
    _args = [sys.argv[0]]
    for arg in sys.argv[1:]:
        if str(arg).isdigit() or str(arg).startswith("--"):
            _args.append(arg)
        else:
            _args.append(f'"{arg}"')
    command = " ".join(_args).strip()
    command = re.sub(r"(--slurm\S*(\s+[^-]\S+)*)", "", command).strip()
    if subprocess.check_output(["which", "simuleval"]).decode().strip() in command:
        command = re.sub(
            r"--agent\s+\S+", f"--agent {args.output}/agent.py", command
        ).strip()
    else:
        # Attention: not fully tested!
        command = re.sub(
            r"[^\"'\s]+\.py", f"{os.path.abspath(args.output)}/agent.py", command
        ).strip()

    if "--output" in command:
        command = re.sub(r"--output\s+\S+", f"--output {args.output}", command).strip()
    else:
        command += f" --output {args.output}"

    command = command.replace("--", "\\\n\t--")
    script = f"""#!/bin/bash
#SBATCH --time={args.slurm_time}
#SBATCH --partition={args.slurm_partition}
#SBATCH --nodes=1
#SBATCH --gpus-per-node=1
#SBATCH --ntasks-per-node=8
#SBATCH --output="{args.output}/slurm-%j.log"
#SBATCH --job-name="{args.slurm_job_name}"

cd {os.path.abspath(args.output)}

GPU_ID=$SLURM_LOCALID

# Change to local a gpu id for debugging, e.g.
# GPU_ID=0

CUDA_VISIBLE_DEVICES=$GPU_ID {command}
    """
    script_file = os.path.join(args.output, "script.sh")
    with open(script_file, "w") as f:
        f.writelines(script)

    process = subprocess.Popen(
        ["sbatch", script_file],
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
    )
    stdout, stderr = process.communicate()
    logger.info("Using slurm.")
    logger.info(f"sbatch stdout: {stdout.decode('utf-8').strip()}")
    stderr = stderr.decode("utf-8").strip()
    if len(stderr) > 0:
        logger.info(f"sbatch stderr: {stderr.decode('utf-8').strip()}")


# x = 0
# while x < 10:
# 	x += 1

# 	if x == 5:
# 		continue

# 	print(x)

# exercise
# use a while loop to create a list with only even values from 0 to 100
# Do not add the value 58!

my_list = []
counter = 0

while counter <= 100:
	if counter % 2 == 0:
		if counter != 58:
			my_list.append(counter)
	counter += 1

print(my_list)


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

# About Site
AUTHOR = 'Ziya Adan'
SITENAME = 'Ziya Adan'
SITEURL = ''

PATH = 'content' # where the content lives
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = 'English'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

# Blogroll
LINKS = ()

# Social widget
SOCIAL = (('Twitter', 'https://twitter.com/ziya_adan'),
         ('Instagram', 'https://twitter.com/ziya_adan/following'),
         ('GoodReads', 'https://twitter.com/ziya_adan/following'),)

DEFAULT_PAGINATION = 10

# plugins and plugin config

PLUGIN_PATHS = ['/pelican/pelican-plugins']
PLUGINS = ['better_figures_and_images', 'i18n_subsites']

RESPONSIVE_IMAGES = True # better fig and img

# themes and config

THEME_PATHS = ['/pelican/pelican-themes/']
THEME = (''.join(THEME_PATHS)+('pelican-bootstrap3'))

JINJA_ENVIRONMENT = {'extensions': ['jinja2.ext.i18n']} # this is for bootstrap3
BOOTSTRAP_FLUID = True
DISPLAY_BREADCRUMBS = True
DISPLAY_CATEGORY_IN_BREADCRUMBS = True

ABOUT_ME = 'WRITER OF ROMANCES, BREAKER OF HEARTS'
AVATAR = 'images/avi.jpg'
TWITTER_USERNAME = 'ziya_adan'
TWITTER_CARDS = True

# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True


import argparse
import numpy as np

from torch.utils.tensorboard import SummaryWriter

from basics.agents.base_agent import Agent

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical

class Policy(nn.Module):
    def __init__(self, observation_space, action_space_size):
        super(Policy, self).__init__()

        if len(observation_space) != 1:
            raise RuntimeError("The Policy specified by this agent only supports 1d obs space")

        self.affine1 = nn.Linear(observation_space[0], 128)
        self.dropout = nn.Dropout(p=0.6)
        self.affine2 = nn.Linear(128, action_space_size)

        self.saved_log_probs = []
        self.rewards = []

    def forward(self, x):
        x = self.affine1(x)
        x = self.dropout(x)
        x = F.relu(x)
        action_scores = self.affine2(x)
        return F.softmax(action_scores, dim=1)

class ReinforceAgent(Agent):

    def __init__(self, args, observation_space, action_space_size):
        self.policy = Policy(observation_space, action_space_size)
        self.optimizer = optim.Adam(self.policy.parameters(), lr=1e-2)
        self.eps = np.finfo(np.float32).eps.item()
        self.gamma = args.gamma
        self.episode_reward = 0
        self.running_reward = 10
        self.writer = SummaryWriter()

    def select_action(self, state):
        state = torch.from_numpy(state).float().unsqueeze(0)
        probs = self.policy(state)
        m = Categorical(probs)
        action = m.sample()
        self.policy.saved_log_probs.append(m.log_prob(action))
        return action.item()

    def finish_iteration(self, reward, iteration_count):
        self.policy.rewards.append(reward)
        self.episode_reward += reward

    def finish_episode(self, episode):
        self.running_reward = 0.05 * self.episode_reward + (1 - 0.05) * self.running_reward
        R = 0
        policy_loss = []
        returns = []
        for r in self.policy.rewards[::-1]:
            R = r + self.gamma * R
            returns.insert(0, R)
        returns = torch.tensor(returns)
        returns = (returns - returns.mean()) / (returns.std() + self.eps)
        for log_prob, R in zip(self.policy.saved_log_probs, returns):
            policy_loss.append(-log_prob * R)
        self.optimizer.zero_grad()
        policy_loss = torch.cat(policy_loss).sum()
        policy_loss.backward()
        self.optimizer.step()
        del self.policy.rewards[:]
        del self.policy.saved_log_probs[:]
        self.writer.add_scalar("Last reward", self.episode_reward, episode)
        self.writer.add_scalar("Average reward", self.running_reward, episode)
        self.episode_reward = 0

    def check_solved_env(self, reward_threshold):
        return self.running_reward > reward_threshold

    @staticmethod
    def add_args(parser):
        parser.add_argument('--gamma', type=float, default=0.99, metavar='G',
                    help='discount factor (default: 0.99)')
        return parser


"""
Provides functions for testing functions
"""

import json

def ratio(success_count, attempt_count):
    """ Pretty-print a success rate """
    success_ratio = success_count / (attempt_count or 1)
    return "%d/%d=%d%%"%(success_count, attempt_count, int(success_ratio*100))

def test(func, get_parts=None):
    """
    Test a function on specific parts using the training data

    Parameters
    ----------
    func
        The function to test
    get_parts
        A function to split each case into sub-cases to independently test

        Default: just test each whole test case without splitting
    """
    with open("data/training/isl.json") as f:
        data = json.load(f)
    failures = []
    failure_count = 0
    success_count = 0
    case_success_count = 0
    case_total_count = len(data)
    for case in data:
        successful = True
        content = case["content"]
        try:
            if get_parts is None:
                parts = [content]
            else:
                print(get_parts)
                print(get_parts("abc $def$ hi"))
                parts = get_parts(content)
        except:
            print("failed on parts")
            successful = False
            parts = []
        for expr in parts:
            try:
                func(expr)
                success_count += 1
            except:
                if successful:
                    print("Failed on part ", expr)
                successful = False
                failure_count += 1
                failures.append(expr)
        if successful:
            case_success_count += 1
    total_count = success_count + failure_count
    print("Failed expressions:\n", "\n".join(failures))
    print("Successful parts: %s"%ratio(success_count, total_count))
    if get_parts is not None:
        print("Successful cases: %s"%ratio(case_success_count, case_total_count))


with open('../input.txt') as inp:
    text = inp.read()
    translation = text.maketrans("ABCXYZ", "123123")

    text_split = text.translate(translation).split('\n')
    print(text_split)

    winners = {'2': '1', '3': '2', '1': '3'}
    score = 0
    for i in text_split:
        score += int(i[2])
        if i[0] == i[2]:
            score += 3
        elif winners[i[2]] == i[0]:
            score += 6

    print(score)


import cocos
import pyglet

from models.battle.battle_model import BattleModel
from models.move_model import MoveModel
from models.pokemon_model import PokemonModel
from toolbox.game import Game
from toolbox.i18n import I18n
from toolbox.init import PATH
from toolbox.keyboard import is_key_left, is_key_right, is_key_down, is_key_up, is_key_action, is_key_cancel
from views.common.layer import Layer
from views.pkmn_infos.action_enum import ActionEnum
from .pkmn_infos_type_enum import PkmnInfosTypeEnum

class ActionsLayer(Layer):
    """Shows the list of actions available to the player."""

    SELECTED_SPRITE = "SELECTED_SPRITE"

    is_event_handler = True

    def __init__(self, pkmn_infos_type: PkmnInfosTypeEnum, pokemon: PokemonModel, selected_action: ActionEnum = None,
                 battle: BattleModel = None, new_move: MoveModel = None) -> None:
        """Create a layer with the list of actions and manage their interaction.

        :param pkmn_infos_type: The type of scene. Affects the information
        displayed and the interactions.
        :param pokemon: The pokemon whose infos is shown.
        :param selected_action: The selected action by default.
        :param battle: The battle model if it is for a shift.
        :param new_move: The new move to learn if any.
        """

        super().__init__()

        self._pokemon = pokemon
        self._pkmn_infos_type = pkmn_infos_type
        self._new_move = new_move
        self._available_actions = pkmn_infos_type.actions.copy()
        if ActionEnum.SHIFT in self._available_actions and (
                (battle is not None and battle.players_pokemon == pokemon) or pokemon.hp <= 0):
            self._available_actions.remove(ActionEnum.SHIFT)
        if ActionEnum.PREVIOUS in self._available_actions and Game().game_state.player.pokemons.index(pokemon) == 0:
            self._available_actions.remove(ActionEnum.PREVIOUS)
        if ActionEnum.NEXT and Game().game_state.player.pokemons.index(pokemon) == len(
                Game().game_state.player.pokemons) - 1:
            self._available_actions.remove(ActionEnum.NEXT)

        self._selected_action = self._available_actions.index(
            selected_action) if selected_action and selected_action in self._available_actions else self._available_actions.index(
            pkmn_infos_type.default_action)
        self._actions = {}

        if ActionEnum.PREVIOUS in self._available_actions:
            previous = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/small_left.png'), anchor=(0, 0))
            selected_previous = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/selected_small_left.png'), anchor=(0, 0))
            previous.add(selected_previous, name=ActionsLayer.SELECTED_SPRITE)
            previous_text = cocos.text.Label(I18n().get("POKEMON_INFOS.PREVIOUS"), font_size=20)
            previous_text.position = (previous.width / 2 - previous_text.element.content_width / 1.5,
                                      previous.height / 2 - previous_text.element.content_height / 4)
            previous.add(previous_text)
            self.add(previous)
            self._actions[ActionEnum.PREVIOUS] = previous

        if ActionEnum.SHIFT in self._available_actions:
            shift = cocos.sprite.Sprite(pyglet.image.load(
                PATH + '/assets/img/common/buttons/small_center_red.png'),
                anchor=(0, 0))
            shift.position = (cocos.director.director.get_window_size()[0] / 2 - shift.width - 5, 0)
            selected_shift = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/selected_small_center_red.png'), anchor=(0, 0))
            shift.add(selected_shift, name=ActionsLayer.SELECTED_SPRITE)
            shift_text = cocos.text.Label(I18n().get("POKEMON_INFOS.SHIFT"), font_size=14)
            shift_text.position = (shift.width / 2 - shift_text.element.content_width / 2,
                                   shift.height / 2 - shift_text.element.content_height / 4)
            shift.add(shift_text)
            self.add(shift)
            self._actions[ActionEnum.SHIFT] = shift

        if ActionEnum.CANCEL in self._available_actions:
            cancel = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/common/buttons/small_center.png'),
                                         anchor=(0, 0))
            cancel_position_x = cocos.director.director.get_window_size()[0] / 2
            if ActionEnum.SHIFT not in self._available_actions:
                cancel_position_x -= cancel.width / 2
            cancel.position = (cancel_position_x, 0)
            selected_cancel = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/selected_small_center.png'), anchor=(0, 0))
            cancel.add(selected_cancel, name=ActionsLayer.SELECTED_SPRITE)
            cancel_text = cocos.text.Label(I18n().get("POKEMON_INFOS.CANCEL"), font_size=14)
            cancel_text.position = (cancel.width / 2 - cancel_text.element.content_width / 2,
                                    cancel.height / 2 - cancel_text.element.content_height / 4)
            cancel.add(cancel_text)
            self.add(cancel)
            self._actions[ActionEnum.CANCEL] = cancel

        if ActionEnum.NEXT in self._available_actions:
            next = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/small_right.png'), anchor=(0, 0))
            next.position = (cocos.director.director.get_window_size()[0] - next.width, -2)
            selected_next = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/buttons/selected_small_right.png'), anchor=(0, 0))
            next.add(selected_next, name=ActionsLayer.SELECTED_SPRITE)
            next_text = cocos.text.Label(I18n().get("POKEMON_INFOS.NEXT"), font_size=20)
            next_text.position = (next.width / 2 - next_text.element.content_width / 4,
                                  next.height / 2 - next_text.element.content_height / 4)
            next.add(next_text)
            self.add(next)
            self._actions[ActionEnum.NEXT] = next

        list_moves = pokemon.moves + [new_move] if new_move else pokemon.moves
        for index, move in enumerate(list_moves):
            name = move.name.capitalize() if isinstance(move, MoveModel) else move.move.name.capitalize()
            current_pp = move.default_pp if isinstance(move, MoveModel) else move.current_pp
            max_pp = move.default_pp if isinstance(move, MoveModel) else move.pp
            type = move.type.name.lower() if isinstance(move, MoveModel) else move.move.type.name.lower()
            y_position = 170 if isinstance(move, MoveModel) else 350 - 40 * index

            move_sprite = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/battle/moves/{0}.png'.format(type)))
            move_sprite.position = (
                cocos.director.director.get_window_size()[0] - move_sprite.width / 2, y_position)

            selected_sprite = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/battle/moves/selected_{0}.png'.format(type)))
            selected_sprite.visible = False
            move_sprite.add(selected_sprite, name=ActionsLayer.SELECTED_SPRITE)

            name_label = cocos.text.Label(name, font_size=9, anchor_x="left", anchor_y="center", color=(0, 0, 0, 255),
                                          bold=True)
            name_label.position = (-57, 8)
            move_sprite.add(name_label)

            pp = cocos.text.Label("PP {0}/{1}".format(current_pp, max_pp),
                                  font_size=9, anchor_x="left", anchor_y="center", bold=True)
            pp.position = (-15, -8)
            move_sprite.add(pp)

            type = cocos.sprite.Sprite(
                pyglet.image.load(PATH + '/assets/img/common/types/{0}.png'.format(type)))
            type.position = (-35, -8)
            type.scale = 0.9
            move_sprite.add(type)

            self.add(move_sprite)
            if pkmn_infos_type == PkmnInfosTypeEnum.NEW_MOVE:
                if move == new_move:
                    new = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/pkmn_infos/new.png'.format(type)))
                    new.position = (-move_sprite.width / 2 + 8, -move_sprite.height / 2 + 8)
                    move_sprite.add(new)

                self._actions[self._available_actions[index]] = move_sprite

        self._update_screen()

    def _update_screen(self) -> None:
        """update the selected action."""

        for index, action in enumerate(self._available_actions):
            if self._selected_action == index:
                self._actions[action].get(ActionsLayer.SELECTED_SPRITE).visible = True
            else:
                self._actions[action].get(ActionsLayer.SELECTED_SPRITE).visible = False

    def on_key_press(self, key, modifiers) -> bool:
        """Manage the key press event.

        Update the selected action when pressing UP or BOTTOM.
        Activate the selected action when pressing ENTER.

        :param key: The pressed key.
        :param modifiers: The pressed modifiers.
        :return Whether the event has been handled.
        """

        event_handled = False
        if is_key_left(key) and self._selected_action > 0:
            self._selected_action -= 1
            event_handled = True
        elif is_key_right(key) and self._selected_action < len(self._available_actions) - 1:
            self._selected_action += 1
            event_handled = True
        elif is_key_up(key) and self._pkmn_infos_type == PkmnInfosTypeEnum.NEW_MOVE and self._selected_action > 0:
            self._selected_action -= 1
            event_handled = True
        elif is_key_down(key) and self._pkmn_infos_type == PkmnInfosTypeEnum.NEW_MOVE and self._selected_action < len(
                self._available_actions) - 1:
            self._selected_action += 1
            event_handled = True
        elif is_key_action(key):
            if self._available_actions[self._selected_action] == ActionEnum.CANCEL:
                self.parent.cancel()
                event_handled = True
            elif self._available_actions[self._selected_action] == ActionEnum.PREVIOUS:
                self.parent.next_previous_pokemon(ActionEnum.PREVIOUS)
                event_handled = True
            elif self._available_actions[self._selected_action] == ActionEnum.NEXT:
                self.parent.next_previous_pokemon(ActionEnum.NEXT)
                event_handled = True
            elif self._available_actions[self._selected_action] == ActionEnum.SHIFT:
                self.parent.shift(self._pokemon)
                event_handled = True
            elif self._available_actions[self._selected_action] == ActionEnum.NEW_MOVE:
                self.parent.cancel()
                event_handled = True
            elif self._available_actions[self._selected_action] in [ActionEnum.MOVE_1, ActionEnum.MOVE_2,
                                                                    ActionEnum.MOVE_3, ActionEnum.MOVE_4]:
                self.parent.cancel([self._pokemon.moves[self._selected_action]])
                event_handled = True
        elif is_key_cancel(key):
            self.parent.cancel()
            event_handled = True

        self._update_screen()

        return event_handled


def numero_ordinal(numero):
    if numero < 1 or numero > 12:
        return ""

    ordinais = ["primeiro", "segundo", "terceiro", "quarto", "quinto", "sexto",
                "sétimo", "oitavo", "nono", "décimo", "décimo primeiro", "décimo segundo"]

    return ordinais[numero - 1]

escolha = int(input("Digite um numero de 1 a 12: "))
if escolha in range(1, 13):
    resultado = numero_ordinal(escolha)
    print(f"{escolha} -> {resultado}")
else:
    print("Numero invalido")


import requests

import conf
import util

def link_moodle_course(course_id: str, moodle_short_name: str, sync_students: bool, sync_grades: bool, force: bool):
    body = {
        "moodle_props": {
            "moodle_short_name": moodle_short_name,
            "sync_students": sync_students,
            "sync_grades": sync_grades
        },
        "force": force
    }

    resp = requests.put(conf.EMS_BASE_URL + '/courses/' + course_id + '/moodle', json=body, headers=util.get_token_header())
    print(resp.status_code)


#!/usr/bib/env python3
# -*- encoding: utf-8 -*-
'''
   Escreva um programa que calcule o tempo de vida de um fumante. Pergunte a qtd
   de cigarro por dia e quantos anos já fumou. Considere perder 10 min de vida
   a cada cigarro. Calcule quantos dias de vida perderá. Exiba total de dias.
'''

qtddia = int(input("Digite quantos cigarros você fuma por dia: "))
anos = int(input("Quantos anos que você fuma: "))
print("Você fumou %d em %d anos e você perdeu %d dias de vida."%((qtddia * anos * 365), anos, (qtddia * anos * 365) * 10 - (365 * anos)))


import Adafruit_DHT

# Set the sensor type and Raspberry Pi pin number
sensor = Adafruit_DHT.DHT22
pin = 4

# Try to get a reading from the sensor
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# If a valid reading was taken, display the temperature and humidity
if humidity is not None and temperature is not None:
    print("Temperature: {:.1f} C".format(temperature))
    print("Humidity: {:.1f}%".format(humidity))
else:
    print("Failed to get reading from sensor.")


import pickle
import os
import random
import numpy as np
from config import BASE_PATH

class DataContainer:
    def __init__(self, pretrained_emb_path,
                 lexicon_path, corpus_vocab_path, down_sampling=False,
                 seed=101, name=None, verbose=True):
        if down_sampling:
            name = '{}_balanced'.format(name)
        self.name = name
        self.seed = seed
        self.verbose = verbose
        self.down_sampling = down_sampling

        data = self.load_from_cache(name=name, pretrained_emb_path=pretrained_emb_path,
                                    lexicon_path=lexicon_path, corpus_vocab_path=corpus_vocab_path)

        self.lexicon_words, self.non_lexicon_words, self.lexicon, self.init_emb = data
        _vec = next(iter(self.init_emb.values()))
        self.emb_shape = _vec.shape

        self.pos_words, self.neg_words = self.init_poles()

        _scores = [self.lexicon[key] for key in self.lexicon]
        if len(set(_scores)) == 2:
            self.binary = True
        else:
            self.binary = False

        if self.verbose:
            print('Num of lexicon words:', len(self.lexicon_words))
            print('Class Distribution of the lexicon words:')
            print('Positive:', len(self.pos_words), 'Negative:', len(self.neg_words),
                  'Neutral:', len(self.lexicon_words) - len(self.pos_words) - len(self.neg_words))

            _len_nl = 0
            for _bth in self.non_lexicon_words:
                _len_nl += len(_bth)
            print('Num of non-lexicon words:', _len_nl)

            print('The shape of the word representations is:', self.emb_shape, '!')

            if self.binary:
                print('***The lexicon is binary!***')
            else:
                print('***The lexicon is not binary!***')

        # self.init_2nd_emb = None
        self.init_1st_emb = dict(self.init_emb)

    def update_emb(self, embeddings):
        for word in embeddings:
            self.init_emb[word] = embeddings[word]
        # self.init_2nd_emb = dict(self.init_emb)

    def rescale(self, num, _min, _max):
        random.seed(self.seed)
        res = (num - _min) * 2 / (_max - _min) - 1
        if res == 0:
            res += random.choice([0.000001, -0.000001])
            self.seed += 1
        return res

    @staticmethod
    def batchify(words, batch_size):
        assert batch_size > 1
        batches = []
        batch = []
        count = 0
        for word in words:
            batch.append(word)
            count += 1
            if count > batch_size:
                batches.append(batch)
                batch = []
                count = 0
        batches.append(batch)
        return batches

    def preprocess(self, pretrained_emb_path, lexicon_path, corpus_vocab_path):
        '''
        cross compare vocabularies and initialize lexicon words, non lexicon words;
        rescale the lexicon scores to [-1, 1]
        cache the preprocessed data if wanted

        :param pretrained_emb_path:
        :param lexicon_path:
        :param corpus_vocab_path:
        :return:
        '''
        pretrained_emb = pickle.load(open(pretrained_emb_path, 'rb'))
        lexicon = pickle.load(open(lexicon_path, 'rb'))
        corpus_vocab = pickle.load(open(corpus_vocab_path, 'rb'))

        inter_corpus_vocab = list(set(pretrained_emb.keys()) & set(corpus_vocab.keys()))

        lexicon_words = list(set(pretrained_emb.keys()) & set(lexicon.keys()))
        non_lexicon_words = list(set(inter_corpus_vocab) - set(lexicon_words))

        random.seed(self.seed)
        random.shuffle(lexicon_words)
        random.shuffle(non_lexicon_words)

        _scores = [lexicon[key] for key in lexicon]
        _min = np.floor(min(_scores))
        _max = np.ceil(max(_scores))

        scaled_lexicon = {}
        for word in lexicon_words:
            scaled_lexicon[word] = self.rescale(lexicon[word], _min, _max)

        # down sampling
        if self.down_sampling:
            print('Down Sampling...')
            _pos_word = []
            _neg_word = []
            _neutral_word = []
            for word in lexicon_words:
                if scaled_lexicon[word] > 0.001:
                    _pos_word.append(word)
                elif scaled_lexicon[word] < -0.001:
                    _neg_word.append(word)
                else:
                    _neutral_word.append(word)
            _maxLen = min(len(_pos_word), len(_neg_word))

            _down_sampled = _pos_word[:_maxLen] + _neg_word[:_maxLen] + _neutral_word
            lexicon_words = _down_sampled

        full_vocab = list(set(lexicon_words) | set(non_lexicon_words))
        init_emb = {}
        for word in full_vocab:
            init_emb[word] = pretrained_emb[word]

        batch_non_lexicon_words = self.batchify(non_lexicon_words, len(lexicon_words) / 9)

        data = (lexicon_words, batch_non_lexicon_words, scaled_lexicon, init_emb)
        return data

    def init_poles(self):
        '''
        initialize the poles and save to the data container

        :return:
        '''
        pos_words = []
        neg_words = []
        _agg_pos_emb = np.zeros(shape=self.emb_shape)
        _agg_neg_emb = np.zeros(shape=self.emb_shape)
        _num_pos = 0
        _num_neg = 0

        for word in self.lexicon_words:
            if self.lexicon[word] > 0.001:
                pos_words.append(word)
                _agg_pos_emb += self.init_emb[word]
                _num_pos += 1
            elif self.lexicon[word] < -0.001:
                neg_words.append(word)
                _agg_neg_emb += self.init_emb[word]
                _num_neg += 1

        assert _num_pos > 0
        assert _num_neg > 0
        _pos_pole = _agg_pos_emb / _num_pos
        _neg_pole = _agg_neg_emb / _num_neg
        self.init_emb['POSPOLE'] = _pos_pole
        self.init_emb['NEGPOLE'] = _neg_pole
        self.lexicon['POSPOLE'] = 1
        self.lexicon['NEGPOLE'] = -1
        self.lexicon_words.append('POSPOLE')
        self.lexicon_words.append('NEGPOLE')
        pos_words.append('POSPOLE')
        neg_words.append('NEGPOLE')

        return pos_words, neg_words

    @staticmethod
    def _check_cache():
        cache_dir = os.path.join(BASE_PATH, "_cache")
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)

    def _get_cache_filename(self):
        return os.path.join(BASE_PATH, "_cache",
                            "_cachedData_{}.pkl".format(self.name))

    def _write_cache(self, data):
        self._check_cache()

        cache_file = self._get_cache_filename()

        with open(cache_file, 'wb') as pickle_file:
            pickle.dump(data, pickle_file)

    def load_from_cache(self, name, pretrained_emb_path,
                        lexicon_path, corpus_vocab_path):

        # NOT using cache
        if name is None:
            print("cache deactivated for data loading!")
            return self.preprocess(pretrained_emb_path=pretrained_emb_path,
                                   lexicon_path=lexicon_path,
                                   corpus_vocab_path=corpus_vocab_path)

        # using cache
        cache_file = self._get_cache_filename()

        if os.path.exists(cache_file):
            print("Loading {} from cache ...".format(self.name))
            with open(cache_file, 'rb') as f:
                return pickle.load(f)
        else:
            print("No cache file for {} ...".format(self.name))
            data = self.preprocess(pretrained_emb_path=pretrained_emb_path,
                                   lexicon_path=lexicon_path,
                                   corpus_vocab_path=corpus_vocab_path)
            self._write_cache(data)
            return data