import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torchvision.utils as vutils
import matplotlib.pyplot as plt
import numpy as np

def get_data(dataroot="data", image_size=64, bsize=64):
    dataset = datasets.ImageFolder(root=dataroot,
                               transform=transforms.Compose([
                                   transforms.Resize(image_size),
                                   transforms.RandomHorizontalFlip(),
                                   transforms.RandomVerticalFlip(),
                                   transforms.RandomAutocontrast(),
                                   transforms.CenterCrop(image_size),
                                   transforms.ToTensor(),
                                   transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]))

    dataloader = torch.utils.data.DataLoader(dataset, batch_size=bsize,
                                             shuffle=True, num_workers=0)

    return dataloader

def tensor2image(tensor):
    data_transforms = transforms.ToPILImage()
    image = vutils.make_grid(tensor, padding=2, normalize=True)
    image = data_transforms(image)
    image = image.convert('RGB')
    return image

def batch2image(batch, epoch):
    batch = vutils.make_grid(batch, padding=2, normalize=True)
    image = np.transpose(batch,(1,2,0))
    plt.figure(figsize=(15,15))
    plt.axis("off")
    plt.imshow(image)
    plt.savefig(f"output/epoch{epoch}.png")
    print(f"Current output is saved to output directory as epoch{epoch}.png")

def visualize(G_losses, D_losses, savefig=True):
    plt.figure(figsize=(15,10))
    plt.title("Generator and Discriminator Loss")
    plt.plot(G_losses,label="Generator", color="black")
    plt.plot(D_losses,label="Discriminator", color="blue")
    plt.xlabel("Iteration number")
    plt.ylabel("Loss value")
    plt.legend()
    plt.grid()
    if savefig:
        plt.savefig("progress.png")
    plt.show()


# -*- coding: utf-8 -*-
'''
@Date: 2020-01-12 23:39:15
@LastEditors  : fzzjj2008
@LastEditTime : 2020-01-14 07:34:11
'''
from hello.student import Teacher, Student

class Clazz:

    def __init__(self, tea_name, stu_list):
        self.tea = Teacher(tea_name)
        self.stu = []
        for stu_name in stu_list:
            self.stu.append(Student(stu_name))

    def greet(self):
        greet_content = ''
        greet_content += self.tea.greet()
        for student in self.stu:
            greet_content += student.greet()
        return greet_content

    def exam(self, score_dict):
        exam_content = ''
        for student in self.stu:
            if student.name in score_dict:
                student.set_score(score_dict[student.name])
        for student in self.stu:
            exam_content += student.print_score()
        return exam_content


from models import *
from utils import *
from ops import *
from losses import *
import time
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--test', action='store_true', help='Run test script')
args = parser.parse_args()

image_size = 64
channels = 1
z_dim = 8192
batch_size = 1
n_epochs = 51
save_step = 5
gan_criterion = mse_criterion
test = args.test
load_model_path = '/output/saved_models'
load_epoch = 100
tensorboard = tf.keras.callbacks.TensorBoard(log_dir='/output/logs')

sess = tf.keras.backend.get_session()

def create_generator3d(inputs, out_channels=3, name='generator'):

	# project = tf.keras.layers.Dense(16*16*16*64, activation='relu')(inputs)
	# project = tf.keras.layers.BatchNormalization()(project)
	# project = tf.keras.layers.ReLU()(project)

	x = tf.keras.layers.Reshape((8, 8, 8, 16))(reshape)

	x = up_block(x, 16, 5, n_dims=3, strides=1)
	x = up_block(x, 16, 5, n_dims=3, strides=2)
	x = up_block(x, 8, 5, n_dims=3, strides=1)
	x = up_block(x, 8, 5, n_dims=3, strides=2)
	x = up_block(x, 4, 5, n_dims=3, strides=1)
	x = up_block(x, 4, 5, n_dims=3, strides=2)
	pred = tf.keras.layers.Conv3D(out_channels, 3, strides=1, padding='same', activation='tanh')(x)

	return tf.keras.models.Model(inputs=[inputs], outputs=[pred], name=name)

def create_discriminator3d(inputs, nf=64, n_hidden_layers=3, reuse=False, name='discriminator'):

	x = conv_block(inputs, nf, strides=(2,2,2), n_dims=3, has_norm_layer=False, use_leaky_relu=True)

	for i in range(n_hidden_layers):
		n_filters = nf*(2**(i+1))
		x = conv_block(x, n_filters, strides=(2,2,2), n_dims=3, use_leaky_relu=True)

	pred = tf.keras.layers.Conv3D(1, 3, strides=(1,1,1), padding='same', activation='sigmoid')(x)

	return tf.keras.models.Model(inputs=[inputs], outputs=[pred], name=name)

z_input_shape = (z_dim,)
img_input_shape = (image_size, image_size, image_size, channels)

z = tf.keras.layers.Input(shape=z_input_shape, name='z')
real = tf.keras.layers.Input(shape=img_input_shape, name='real')

generator = create_generator3d(z, out_channels=channels, name='generator')
discriminator = create_discriminator3d(real, nf=32, n_hidden_layers=2, name='discriminator')

fake = generator(z)
d_pred_fake = discriminator(fake)
d_pred_real = discriminator(real)

d_loss = gan_criterion(tf.concat([tf.ones_like(d_pred_real), tf.zeros_like(d_pred_fake)],0), tf.concat([d_pred_real, d_pred_fake],0))
g_loss = gan_criterion(tf.ones_like(d_pred_fake), d_pred_fake)

d_optimizer = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5, beta2=0.999).minimize(d_loss, var_list=discriminator.trainable_variables)
g_optimizer = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5, beta2=0.999).minimize(g_loss, var_list=generator.trainable_variables)

# d_grad = d_optimizer.compute_gradients(d_loss, discriminator.trainable_weights)
# g_grad = g_optimizer.compute_gradients(g_loss, generator.trainable_weights)
# d_update = d_optimizer.apply_gradients(d_grad)
# g_update = g_optimizer.apply_gradients(g_grad)

print(len(discriminator.trainable_variables))
print(len(generator.trainable_variables))
print('='*100)

def get_internal_updates(model):
    # get all internal update ops (like moving averages) of a model
    inbound_nodes = model.inbound_nodes
    input_tensors = []
    for ibn in inbound_nodes:
        input_tensors+= ibn.input_tensors
    updates = [model.get_updates_for(i) for i in input_tensors]
    return updates

other_parameter_updates = [get_internal_updates(m) for m in [generator, discriminator]]

# train_step = [g_optimizer, d_optimizer]
train_step = [g_optimizer]
losses = [g_loss, d_loss]

tfrecords_filename = '/data/tfrecords/no-tumor-64.tfrecords'

dset = tf.data.TFRecordDataset(tfrecords_filename, compression_type='GZIP').map(lambda x: parse_mri_record(x, only_slice=False, image_size=image_size), num_parallel_calls=batch_size)
dset = dset.shuffle(100).batch(batch_size)
dset_iter = dset.make_initializable_iterator()
dset_next = dset_iter.get_next()

init_op = tf.global_variables_initializer()
sess.run(init_op)

print(discriminator.summary())
print(generator.summary())

learning_phase = tf.keras.backend.learning_phase()

discriminator.load_weights(os.path.join('/output', 'discriminator.h5'))
generator.load_weights(os.path.join('/output', 'generator.h5'))

for e in range(n_epochs):

	start = time.time()
	count = 0

	sess.run(dset_iter.initializer)

	losses_total = [0, 0]

	while True:
		# print(count)
		# print(time.time()-start)

		count+=1

		try:
			batch_real = sess.run(dset_next)
		except tf.errors.OutOfRangeError:
			break

		if len(batch_real)!=batch_size:
			break

		batch_z = np.random.uniform(-1, 1, size=(batch_size , z_dim))

		_, loss_ = sess.run([train_step, losses],
			feed_dict={z: batch_z, real: batch_real, learning_phase: True})
		losses_total[0]+=loss_[0]
		losses_total[1]+=loss_[1]

	print(time.time()-start)
	losses_total = [i/count for i in losses_total]
	print('Epoch {} : g loss {}, d loss {}'.format(e, losses_total[0], losses_total[1]))

	for i in range(10):
		batch_test = np.random.uniform(-1, 1, size=(batch_size , z_dim))
		fake_image = sess.run(fake, feed_dict={z: batch_test, learning_phase: False})
		# print(fake_image.shape)

		save_mri_image(fake_image[0],'/output/generated/{}.nii.gz'.format(i))

	discriminator.save(os.path.join('/output', 'discriminator.h5'))
	generator.save(os.path.join('/output', 'generator.h5'))

	with open('/output/logs.txt','a+') as f:
		f.write('Epoch {} : g loss {}, d loss {} \n'.format(e, losses_total[0], losses_total[1]))


from rlscore.learner import GreedyRLS
from rlscore.measure import sqerror

from housing_data import load_housing

class Callback(object):

    def __init__(self, X_test, Y_test):
        self.X_test = X_test
        self.Y_test = Y_test
        self.iteration = 0

    def callback(self, learner):
        self.iteration += 1
        P = learner.predict(self.X_test)
        e = sqerror(self.Y_test, P)
        print("Features selected %d, test error %f" %(self.iteration, e))

    def finished(self, learner):
        pass

def train_rls():
    X_train, Y_train, X_test, Y_test = load_housing()
    cb = Callback(X_test, Y_test)
    learner = GreedyRLS(X_train, Y_train, 13, callbackfun = cb)
    #Test set predictions
    P_test = learner.predict(X_test)
    print("test error %f" %sqerror(Y_test, P_test))
    print("Selected features " +str(learner.selected))

if __name__=="__main__":
    train_rls()


import discord
from discord.ext import commands

class HelpCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def help(self, ctx):
        embed = discord.Embed(
        title = "**INSA bot**",
        description = "Préfixe : !",
        url= "https://github.com/AliceVancypher/INSA-bot",
        colour = 15277667)
        embed.add_field(name = "role", value = "créer un message à \"reaction-role\", faire !role --help pour plus d'infos", inline = False)
        await ctx.send(embed = embed)


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  7 21:47:27 2023

@author: Seal-Rumi
"""

class Solution:
    def numberOfSteps(self, num: int) -> int:
        step = 0
        n = num
        while n!=0:
            if n%2:
                n-=1
            else:
                n//=2
            step +=1
        return step

Math/1342. Number of Steps to Reduce a Number to Zero.py


#!/usr/bin/env python3

from pathlib import Path
import math
from functools import reduce

def solve(size, lines, times=1, p2=False):
    nums = list(range(size))
    if not p2:
        lengths = [int(x) for x in lines.split(",")]
    if p2:
        lengths = [ord(x) for x in lines] + [17, 31, 73, 47, 23]
    skip = 0
    origin = 0
    for _ in range(times):
        for l in lengths:
            nums = nums[l:] + nums[:l][::-1]
            nums = nums[skip:] + nums[:skip]
            origin -= l + skip
            skip += 1
            skip %= len(nums)
    origin %= len(nums)
    nums = nums[origin:] + nums[:origin]
    return nums

def hash(nums):
    nnums = []
    for i in zip(*[iter(nums)] * 16):
        reduced = reduce(lambda x, y: x ^ y, i)
        nnums.append(reduced)
    return "".join(f"{x:02x}" for x in nnums)

lines = Path(Path(__file__).parent / "input10.txt").read_text().strip()

part1 = math.prod(solve(256, lines)[:2])
print(f"Part 1: {part1}")

part2 = solve(256, lines, 64, p2=True)
part2 = hash(part2)
print(f"Part 2: {part2}")


dataset_dir: str = '/equilibrium/delchiaro/datasets/flickr30k'
#dataset_dir = '/home/btwardow/datasets/flickr30k'

h5_path_fmt = '{}/resnet152_{}.h5'
resized_imdir_fmt = '{}/resized_{}'
resize_size = 256

SPLITS = ('train', 'val', 'test')
h5_path = {split: h5_path_fmt.format(dataset_dir, split) for split in SPLITS}
h5_train_path, h5_val_path, h5_test_path = [h5_path[s] for s in SPLITS]
resized_imdir = {split: resized_imdir_fmt.format(dataset_dir, split) for split in SPLITS}
resized_train_imdir, resized_val_imdir, resized_test_imdir = [resized_imdir[s] for s in SPLITS]

# for Flickr30k splits are first arg to Dataset, which in Coco is dir
train_imdir, val_imdir, test_imdir = [s for s in SPLITS]

vocab_path = f'{dataset_dir}/vocab.pkl'