from typing import List

class UserCard():
    gCardIds = []

    def __init__(self, tPackage: tuple=()) -> None:
        """
        Parameters
        ----------
        tPackage : tuple
            (id, userId, cardCode, level, bond, userTags, moves, skills)
        + id : str
        + userId : str
        + code : str
        + level : int
        + bond : int
        + userTags : iterable
        + moves : iterable
        + skills : iterable
        """

        self.mId = ''
        self.mUserId = ''
        self.mCode = ''

        self.mLevel = 0
        self.mExp = 0
        self.mBond = 0
        self._mUserTags = []

        self.mMoves = {}
        self.mSkills = []

        if tPackage:
            self.mId, self.mUserId, self.mCode, self.mLevel, self.mBond, tUserTags, self.mMoves, self.mSkills = tPackage
            # _mUserTags
            for userTag in tUserTags:
                self.AddUserTag(userTag)
            return

    def GetUserTags(self) -> List[str]:
        return self._mUserTags

    def SetUserTags(self, tUserTags: list) -> None:
        self._mUserTags = tUserTags

    def AddUserTag(self, tUserTag: str) -> None:
        """
        Add user's tag. If dupes is found, return False.
        """
        if tUserTag in self._mUserTags: return False
        self._mUserTags.append(tUserTag)

    @property
    def mId(self):
        return self.mId

    @mId.setter
    def mId(self, tCardId):
        if int(tCardId) == -1:  # Find best fit in the ID list
            i = 0
            while True:
                if int(tCardId) not in UserCard.gCardIds:
                    tCardId = str(i)
                    break
                i += 1
        UserCard.gCardIds.append(tCardId)

        return tCardId


import torch
from torch.utils.data import DataLoader
import torchaudio
import time
import warnings
warnings.filterwarnings('ignore')

yesno_data = torchaudio.datasets.YESNO('.', download=False)

def collate_fn(batch):

    tensors = [b[0].t() for b in batch if b]
    tensors = torch.nn.utils.rnn.pad_sequence(tensors, batch_first=True)
    tensors = tensors.transpose(1, -1)

    targets = torch.tensor([b[2] for b in batch if b])
    targets = torch.nn.utils.rnn.pad_sequence(targets, batch_first=True)

    return tensors, targets

pin_memory = False
print('pin_memory is', pin_memory)
for num_workers in range(0, 32, 1):
    data_loader = torch.utils.data.DataLoader(
                                                yesno_data,
                                                batch_size=32,
                                                pin_memory=pin_memory,
                                                num_workers=num_workers,
                                                collate_fn=collate_fn)
    start = time.time()
    for epoch in range(1, 5):
        for i, (data, _) in enumerate(data_loader):
            torch.tensor(data).to('cuda')
    end = time.time()
    print("Finish with:{} second, num_workers={}".format(end - start, num_workers))

pin_memory = True
print('pin_memory is', pin_memory)
for num_workers in range(0, 32, 1):
    data_loader = torch.utils.data.DataLoader(
                                                yesno_data,
                                                batch_size=32,
                                                pin_memory=pin_memory,
                                                num_workers=num_workers,
                                                collate_fn=collate_fn)
    start = time.time()
    for epoch in range(1, 5):
        for i, (data, _) in enumerate(data_loader):
            torch.tensor(data).to('cuda')
    end = time.time()
    print("Finish with:{} second, num_workers={}".format(end - start, num_workers))


import json
import os

from tornado import web

from .base import BaseApiHandler, check_xsrf, check_notebook_dir
from ...api import MissingEntry

class StatusHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    def get(self):
        self.write({"status": True})

class GradeCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self):
        submission_id = self.get_argument("submission_id")
        try:
            notebook = self.gradebook.find_submission_notebook_by_id(submission_id)
        except MissingEntry:
            raise web.HTTPError(404)
        self.write(json.dumps([g.to_dict() for g in notebook.grades]))

class CommentCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self):
        submission_id = self.get_argument("submission_id")
        try:
            notebook = self.gradebook.find_submission_notebook_by_id(submission_id)
        except MissingEntry:
            raise web.HTTPError(404)
        self.write(json.dumps([c.to_dict() for c in notebook.comments]))

class GradeHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, grade_id):
        try:
            grade = self.gradebook.find_grade_by_id(grade_id)
        except MissingEntry:
            raise web.HTTPError(404)
        self.write(json.dumps(grade.to_dict()))

    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def put(self, grade_id):
        try:
            grade = self.gradebook.find_grade_by_id(grade_id)
        except MissingEntry:
            raise web.HTTPError(404)

        data = self.get_json_body()
        grade.manual_score = data.get("manual_score", None)
        grade.extra_credit = data.get("extra_credit", None)
        if grade.manual_score is None and grade.auto_score is None:
            grade.needs_manual_grade = True
        else:
            grade.needs_manual_grade = False
        self.gradebook.db.commit()
        self.write(json.dumps(grade.to_dict()))

class CommentHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, grade_id):
        try:
            comment = self.gradebook.find_comment_by_id(grade_id)
        except MissingEntry:
            raise web.HTTPError(404)
        self.write(json.dumps(comment.to_dict()))

    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def put(self, grade_id):
        try:
            comment = self.gradebook.find_comment_by_id(grade_id)
        except MissingEntry:
            raise web.HTTPError(404)

        data = self.get_json_body()
        comment.manual_comment = data.get("manual_comment", None)
        self.gradebook.db.commit()
        self.write(json.dumps(comment.to_dict()))

class FlagSubmissionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, submission_id):
        try:
            submission = self.gradebook.find_submission_notebook_by_id(submission_id)
        except MissingEntry:
            raise web.HTTPError(404)

        submission.flagged = not submission.flagged
        self.gradebook.db.commit()
        self.write(json.dumps(submission.to_dict()))

class AssignmentCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self):
        assignments = self.api.get_assignments()
        self.write(json.dumps(assignments))

class AssignmentHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, assignment_id):
        assignment = self.api.get_assignment(assignment_id)
        if assignment is None:
            raise web.HTTPError(404)
        self.write(json.dumps(assignment))

    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def put(self, assignment_id):
        data = self.get_json_body()
        duedate = data.get("duedate_notimezone", None)
        timezone = data.get("duedate_timezone", None)
        if duedate and timezone:
            duedate = duedate + " " + timezone
        assignment = {"duedate": duedate}
        assignment_id = assignment_id.strip()
        self.gradebook.update_or_create_assignment(assignment_id, **assignment)
        sourcedir = os.path.abspath(self.coursedir.format_path(self.coursedir.source_directory, '.', assignment_id))
        if not os.path.isdir(sourcedir):
            os.makedirs(sourcedir)
        self.write(json.dumps(self.api.get_assignment(assignment_id)))

class NotebookCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, assignment_id):
        notebooks = self.api.get_notebooks(assignment_id)
        self.write(json.dumps(notebooks))

class SubmissionCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, assignment_id):
        submissions = self.api.get_submissions(assignment_id)
        self.write(json.dumps(submissions))

class SubmissionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, assignment_id, student_id):
        submission = self.api.get_submission(assignment_id, student_id)
        if submission is None:
            raise web.HTTPError(404)
        self.write(json.dumps(submission))

class SubmittedNotebookCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, assignment_id, notebook_id):
        submissions = self.api.get_notebook_submissions(assignment_id, notebook_id)
        self.write(json.dumps(submissions))

class StudentCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self):
        students = self.api.get_students()
        self.write(json.dumps(students))

class StudentHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, student_id):
        student = self.api.get_student(student_id)
        if student is None:
            raise web.HTTPError(404)
        self.write(json.dumps(student))

    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def put(self, student_id):
        data = self.get_json_body()
        student = {
            "last_name": data.get("last_name", None),
            "first_name": data.get("first_name", None),
            "email": data.get("email", None),
        }
        student_id = student_id.strip()
        self.gradebook.update_or_create_student(student_id, **student)
        self.write(json.dumps(self.api.get_student(student_id)))

class StudentSubmissionCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, student_id):
        submissions = self.api.get_student_submissions(student_id)
        self.write(json.dumps(submissions))

class StudentNotebookSubmissionCollectionHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def get(self, student_id, assignment_id):
        submissions = self.api.get_student_notebook_submissions(student_id, assignment_id)
        self.write(json.dumps(submissions))

class AssignHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.generate_assignment(assignment_id)))

class UnReleaseHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.unrelease(assignment_id)))

class ReleaseHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.release_assignment(assignment_id)))

class CollectHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.collect(assignment_id)))

class AutogradeHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id, student_id):
        self.write(json.dumps(self.api.autograde(assignment_id, student_id)))

class GenerateAllFeedbackHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.generate_feedback(assignment_id)))

class ReleaseAllFeedbackHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id):
        self.write(json.dumps(self.api.release_feedback(assignment_id)))

class GenerateFeedbackHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id, student_id):
        self.write(json.dumps(self.api.generate_feedback(assignment_id, student_id)))

class ReleaseFeedbackHandler(BaseApiHandler):
    @web.authenticated
    @check_xsrf
    @check_notebook_dir
    def post(self, assignment_id, student_id):
        self.write(json.dumps(self.api.release_feedback(assignment_id, student_id)))

default_handlers = [
    (r"/formgrader/api/status", StatusHandler),

    (r"/formgrader/api/assignments", AssignmentCollectionHandler),
    (r"/formgrader/api/assignment/([^/]+)", AssignmentHandler),
    (r"/formgrader/api/assignment/([^/]+)/assign", AssignHandler),
    (r"/formgrader/api/assignment/([^/]+)/unrelease", UnReleaseHandler),
    (r"/formgrader/api/assignment/([^/]+)/release", ReleaseHandler),
    (r"/formgrader/api/assignment/([^/]+)/collect", CollectHandler),
    (r"/formgrader/api/assignment/([^/]+)/generate_feedback", GenerateAllFeedbackHandler),
    (r"/formgrader/api/assignment/([^/]+)/release_feedback", ReleaseAllFeedbackHandler),
    (r"/formgrader/api/assignment/([^/]+)/([^/]+)/generate_feedback", GenerateFeedbackHandler),
    (r"/formgrader/api/assignment/([^/]+)/([^/]+)/release_feedback", ReleaseFeedbackHandler),

    (r"/formgrader/api/notebooks/([^/]+)", NotebookCollectionHandler),

    (r"/formgrader/api/submissions/([^/]+)", SubmissionCollectionHandler),
    (r"/formgrader/api/submission/([^/]+)/([^/]+)", SubmissionHandler),
    (r"/formgrader/api/submission/([^/]+)/([^/]+)/autograde", AutogradeHandler),

    (r"/formgrader/api/submitted_notebooks/([^/]+)/([^/]+)", SubmittedNotebookCollectionHandler),
    (r"/formgrader/api/submitted_notebook/([^/]+)/flag", FlagSubmissionHandler),

    (r"/formgrader/api/grades", GradeCollectionHandler),
    (r"/formgrader/api/grade/([^/]+)", GradeHandler),

    (r"/formgrader/api/comments", CommentCollectionHandler),
    (r"/formgrader/api/comment/([^/]+)", CommentHandler),

    (r"/formgrader/api/students", StudentCollectionHandler),
    (r"/formgrader/api/student/([^/]+)", StudentHandler),

    (r"/formgrader/api/student_submissions/([^/]+)", StudentSubmissionCollectionHandler),
    (r"/formgrader/api/student_notebook_submissions/([^/]+)/([^/]+)", StudentNotebookSubmissionCollectionHandler),
]


import identifier_phase, biomarker, clinical_trial_code, patient_number, lines_of_therapy, study_evaluation
import utils.chunk_utils as cu
import utils.json_utils as ju

def get_overall_info(content):
    overall_dict = {}
    identifier_phase_dicts = identifier_phase.get_final_result(content)
    overall_dict['Identifier'] = ','.join([d['Identifier'] for d in identifier_phase_dicts])
    overall_dict['Phase'] = ','.join([d['Phase'] for d in identifier_phase_dicts])
    overall_dict['Drug'] = ','.join([d['Drug'] for d in identifier_phase_dicts])
    clinical_trial_code_dicts = clinical_trial_code.get_final_result(content)
    overall_dict['Clinical Trial Code'] = ','.join([d['Clinical Trial Code'] for d in clinical_trial_code_dicts])
    biomarker_dicts = biomarker.get_final_result(content)
    overall_dict['Biomarker'] = ','.join([d['Biomarker'] for d in biomarker_dicts])
    # target_indication_dicts = target_indication.get_final_result(content)
    overall_dict['Target Indication'] = ','.join([d['Target Indication'] for d in biomarker_dicts])
    patient_number_dicts = patient_number.get_final_result(content)
    overall_dict['Overall Enrollment'] = ','.join([d['Overall Enrollment'] for d in patient_number_dicts])
    lines_of_therapy_dicts = lines_of_therapy.get_final_result(content)
    overall_dict['Line of Therapy'] = ','.join([d['Line of Therapy'] for d in lines_of_therapy_dicts])
    study_evaluation_dicts = study_evaluation.get_final_result(content)
    overall_dict['Overall Evaluation'] = ','.join([d['Evaluation'] for d in study_evaluation_dicts])
    print()
    print("============================   Overall Result  =============================")
    return overall_dict

if __name__ == '__main__':
    print(ju.json_beautify(get_overall_info(cu.get_file_content("data/tmp_test_data_1"))))


#!/usr/bin/env python3

import numpy as np
import time
import cv2
import matplotlib.pyplot as plt

def corr(F, I):
    """
    Input
        F: A (k, ell, c)-shaped ndarray containing the k x ell filter (with c channels).
        I: An (m, n, c)-shaped ndarray containing the m x n image (with c channels).

    Returns
        G: An (m, n)-shaped ndarray containing the correlation of the filter with the image.
    """
    ########## Code starts here ##########
    raise NotImplementedError("Implement me!")
    ########## Code ends here ##########

def norm_cross_corr(F, I):
    """
    Input
        F: A (k, ell, c)-shaped ndarray containing the k x ell filter (with c channels).
        I: An (m, n, c)-shaped ndarray containing the m x n image (with c channels).

    Returns
        G: An (m, n)-shaped ndarray containing the normalized cross-correlation of the filter with the image.
    """
    ########## Code starts here ##########
    raise NotImplementedError("Implement me!")
    ########## Code ends here ##########

def show_save_corr_img(filename, image, template):
    # Not super simple, because need to normalize image scale properly.
    fig, ax = plt.subplots()
    cropped_img = image[:-template.shape[0], :-template.shape[1]]
    im = ax.imshow(image, interpolation='none', vmin=cropped_img.min())
    fig.colorbar(im)
    fig.savefig(filename, bbox_inches='tight')
    plt.show()
    plt.close(fig)

def main():
    test_card = cv2.imread('test_card.png').astype(np.float32)

    filt1 = np.zeros((3, 3, 1))
    filt1[1, 1] = 1

    filt2 = np.zeros((3, 3, 1))
    filt2[1, -1] = 1

    filt3 = np.zeros((3, 3, 1))
    filt3[:, 0] = -1
    filt3[:, 2] = 1

    filt4 = (1./273.)*np.array([[1, 4, 7, 4, 1],
                              [4, 16, 26, 16, 4],
                              [7, 26, 41, 26, 7],
                              [4, 16, 26, 16, 4],
                              [1, 4, 7, 4, 1]])
    filt4 = np.expand_dims(filt4, -1)

    grayscale_filters = [filt1, filt2, filt3, filt4]

    color_filters = list()
    for filt in grayscale_filters:
        # Making color filters by replicating the existing
        # filter per color channel.
        color_filters.append(np.concatenate([filt, filt, filt], axis=-1))

    for idx, filt in enumerate(color_filters):
        start = time.time()
        corr_img = corr(filt, test_card)
        stop = time.time()
        print('Correlation function runtime:', stop - start, 's')
        show_save_corr_img("corr_img_filt%d.png" % idx, corr_img, filt)

if __name__ == "__main__":
    main()


# Detection Cross Sections
# All cross sections in cm^2
# All energies in MeV
from .constants import *
from .fmath import *
from .photon_xs import PECrossSection
from .matrix_element import *

from matplotlib.pyplot import hist2d

# Define ALP DETECTION cross-sections

#### Photon Coupling ####

def iprimakoff_dsigma_dtheta(theta, ea, g, ma, z, r0):
    # inverse-Primakoff scattering differential xs by theta
    # r0: screening parameter
    if ea < ma:
        return 0.0
    prefactor = (g * z)**2 / (2*137)
    q2 = -2*ea**2 + ma**2 + 2*ea*sqrt(ea**2 - ma**2)*cos(theta)
    beta = sqrt(ea**2 - ma**2)/ea
    return prefactor * (1 - exp(q2 * r0**2 / 4))**2 * (beta * sin(theta)**3)/(1+beta**2 - 2*beta*cos(theta))**2

def iprimakoff_nsigma(ea, g, ma, z, r0):
    # inverse-Primakoff scattering total xs (numerically integrated)
    # r0: screening parameter
    return quad(iprimakoff_dsigma_dtheta, 0, pi, args=(ea,g,ma,z,r0))[0]

def iprimakoff_sigma(ea, g, ma, z, r0 = 2.2e-10 / METER_BY_MEV):
    # inverse-Primakoff scattering total xs (Creswick et al)
    # r0: screening parameter
    prefactor = (g * z)**2 / (2*137)
    eta2 = r0**2 * (ea**2 - ma**2)
    return heaviside(ea-ma, 0.0)*prefactor * (((2*eta2 + 1)/(4*eta2))*log(1+4*eta2) - 1)

def dark_iprim_dsigma_dt(t, s, gZN, gaGZ, ma, mZp, M):
    # inverse Priamkoff with massive vector mediator (a + N -> \gamma + N via Z')
    prefactor = (gZN*gaGZ)**2 / (16*pi) / ((M + ma)**2 - s) / ((M - ma)**2 - s)
    return prefactor * (ma**2 * t * (M**2 + s) - (M*ma**2)**2 - t*((s-M**2)**2 + s*t) - t*(t-ma**2)/2) / (t-mZp**2)**2

def dark_iprim_dsigma_dcostheta(cosTheta, Ea, gZN, gaGZ, ma, mZp, z=6):
    # inverse Priamkoff with massive vector mediator (a + N -> \gamma + N via Z')
    prefactor = sqrt(M_P*(Ea - ma)*(2*Ea*M_P + ma**2))/(4*sqrt(2)*pi**2 * (2*Ea*M_P + M_P**2 + ma**2))
    t = ma**2 - ((ma**2 + 2*Ea*M_P)/(M_P + Ea - sqrt(Ea**2 - ma**2)*cosTheta)) * (Ea - sqrt(Ea**2 - ma**2)*cosTheta)
    s = M_P**2 + ma**2 + 2*Ea*M_P
    return prefactor * heaviside(Ea - ma, 0.0) * dark_iprim_dsigma_dt(t, s, gZN, gaGZ, ma, mZp, 2*z*M_P)

#### Electron Coupling ####

def axioelectric_sigma(energy, g, ma, mat):
    # Axio-electric total cross section for ionization
    pe_xs = PECrossSection(mat)
    beta = sqrt(np.heaviside(energy-ma,0.0) * (energy**2 - ma**2))/energy
    return  np.clip(np.heaviside(1.0 - energy, 0.0) *3 * power(energy * g / M_E, 2) * pe_xs.sigma_mev(energy) * \
        (1 - power(beta, 2/3)/3) / (16*pi*ALPHA*beta), a_min=0.0, a_max=None)

def icompton_sigma_old(ea, g, z=1):
    # TODO: deprecate
    # Total cross section (a + e- -> \gamma + e-)
    a = 1 / 137
    aa = g ** 2 / 4 / pi
    prefact = a * aa * pi / 2 / M_E / ea**2
    sigma = prefact * 2 * ea * (-(2*ea * (3*ea + M_E)/(2 * ea + M_E)**2) + np.log(2 * ea / M_E + 1))
    return z*sigma

def icompton_sigma(ea, ma, g, z=1):
    # Inverse Compton total cross section (a + e- -> \gamma + e-)
    # Borexino 2008, eq. 14
    y = 2 * M_E * ea + ma**2
    pa = sqrt((ea**2 - ma**2))
    prefactor = heaviside(ea - ma, 0.0) * z * ALPHA * power(g/M_E, 2) / (8 * pa)

    return np.clip(prefactor * ((2 * M_E**2 * (M_E + ea) * y)/power(M_E**2 + y, 2) \
        + (4*M_E*(ma**4 + 2*power(ma*M_E, 2) - power(2*M_E*ea, 2)))/(y*(M_E**2 + y)) \
        + log((M_E + ea + pa)/(M_E + ea - pa))*(power(2*M_E*pa, 2) + ma**4)/(ea*y)), a_min=0.0, a_max=None)

def icompton_dsigma_det(ea, et, g, ma, z=1):
    # Inverse Compton differential cross section by electron recoil (a + e- -> \gamma + e-)
    # dSigma / dEt   electron kinetic energy
    # ea: axion energy
    # et: transferred electron energy = E_e - m_e.
    y = 2 * M_E * ea + ma ** 2
    prefact = z*(1/137) * g ** 2 / (4 * M_E ** 2)
    pa = np.sqrt(ea ** 2 - ma ** 2)
    eg = ea - et
    return -(prefact / pa) * (1 - (8 * M_E * eg / y) + (12 * (M_E * eg / y) ** 2)
                                - (32 * M_E * (pa * ma) ** 2) * eg / (3 * y ** 3))

def icompton_dsigma_domega(theta, Ea, ma, ge, z=1):
    # Compton differential cross section by solid angle (a + e- -> \gamma + e-)
    # dSigma / dOmega
    y = 2*M_E*Ea + ma**2
    pa = sqrt(Ea**2 - ma**2)
    e_gamma = 0.5*y/(M_E + Ea - pa*cos(theta))

    prefactor = z*ge**2 * ALPHA * e_gamma / (4*pi*2*pa*M_E**2)
    return prefactor * (1 + 4*(M_E*e_gamma/y)**2 - 4*M_E*e_gamma/y - 4*M_E*e_gamma*(ma*pa*sin(theta))**2 / y**3)

def pair_production_sigma(Ea, ma, ge, mat: Material, n_samples=1000):
    m2 = M2PairProduction(ma, mat.m[0], mat.n[0], mat.z[0])

    tp = np.random.uniform(-15, -5, n_samples)
    tm = np.random.uniform(-15, -5, n_samples)

    tp = 10**tp
    tm = 10**tm
    mc_vol = tp * tm * (Ea - 2*M_E)*(2*pi)*(pi**2)*log(10)**2

    phi = np.random.uniform(0.0, 2*pi, n_samples)
    ep = np.random.uniform(M_E, Ea - M_E, n_samples)

    p1 = sqrt(ep**2 - M_E**2)
    em = Ea - ep
    p2 = sqrt(em**2 - M_E**2)
    va = sqrt(Ea**2 - ma**2)/Ea

    m2_wgts = m2.m2(Ea, ep, tp, tm, phi, coupling_product=ge)

    weights = abs(mc_vol * m2_wgts * (p1*p2*sin(tp)*sin(tm)/(512*pi**4)/Ea/va/mat.m[0]**2)/n_samples)

    return np.sum(weights)


n, m = map(int, input().split())
grid = [[0]*m for _ in range(n)]
s = ord('A')
dxs = [0, 1, 0, -1]
dys = [1, 0, -1, 0]
dir_num = 0
x, y = 0, 0
grid[x][y] = s

def in_range(x, y):
    return 0 <= x < n and 0 <= y < m

count = 1
for i in range(1, n*m):
    nx = x + dxs[dir_num]
    ny = y + dys[dir_num]

    if not (in_range(nx, ny)) or grid[nx][ny] != 0:
        dir_num = (dir_num + 1) % 4

    x = x + dxs[dir_num]
    y = y + dys[dir_num]

    s += 1

    if s > ord('Z'):
        s = ord('A')
    grid[x][y] = s

for i in range(n):
    for j in range(m):
        print(chr(grid[i][j]), end=" ")
    print()

코드트리/NM/시뮬레이션/빙빙돌며사각형채우기.py

빙빙돌며사각형채우기.py


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 20:12:52 2017

@author: dell
"""
import collections
def topKFrequent(nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        cnt=collections.Counter(nums)
        sort_fre=sorted(cnt.items(),key=lambda d:d[1],reverse=True)
        alpha=sort_fre[:k]
        return [x[0] for x in alpha]

s=[1,1,1,2,2,3,3]
print(topKFrequent(s, 2))


import torch
import torch.nn as nn
import torch.nn.functional as F

from pycls.models.resnet_style.shake_shake_function import get_alpha_beta, shake_function

import pycls.utils.logging as lu

logger = lu.get_logger(__name__)

def initialize_weights(module):
    if isinstance(module, nn.Conv2d):
        nn.init.kaiming_normal_(module.weight.data, mode='fan_out')
    elif isinstance(module, nn.BatchNorm2d):
        module.weight.data.fill_(1)
        module.bias.data.zero_()
    elif isinstance(module, nn.Linear):
        module.bias.data.zero_()

class ResidualPath(nn.Module):
    def __init__(self, in_channels, out_channels, stride):
        super(ResidualPath, self).__init__()

        self.conv1 = nn.Conv2d(
            in_channels,
            out_channels,
            kernel_size=3,
            stride=stride,
            padding=1,
            bias=False,
        )
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = nn.Conv2d(
            out_channels,
            out_channels,
            kernel_size=3,
            stride=1,
            padding=1,
            bias=False)
        self.bn2 = nn.BatchNorm2d(out_channels)

    def forward(self, x):
        x = F.relu(x, inplace=False)
        x = F.relu(self.bn1(self.conv1(x)), inplace=False)
        x = self.bn2(self.conv2(x))
        return x

class DownsamplingShortcut(nn.Module):
    def __init__(self, in_channels):
        super(DownsamplingShortcut, self).__init__()
        self.conv1 = nn.Conv2d(
            in_channels,
            in_channels,
            kernel_size=1,
            stride=1,
            padding=0,
            bias=False)
        self.conv2 = nn.Conv2d(
            in_channels,
            in_channels,
            kernel_size=1,
            stride=1,
            padding=0,
            bias=False)
        self.bn = nn.BatchNorm2d(in_channels * 2)

    def forward(self, x):
        x = F.relu(x, inplace=False)
        y1 = F.avg_pool2d(x, kernel_size=1, stride=2, padding=0)
        y1 = self.conv1(y1)

        y2 = F.pad(x[:, :, 1:, 1:], (0, 1, 0, 1))
        y2 = F.avg_pool2d(y2, kernel_size=1, stride=2, padding=0)
        y2 = self.conv2(y2)

        z = torch.cat([y1, y2], dim=1)
        z = self.bn(z)

        return z

class BasicBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride, shake_config):
        super(BasicBlock, self).__init__()

        self.shake_config = shake_config

        self.residual_path1 = ResidualPath(in_channels, out_channels, stride)
        self.residual_path2 = ResidualPath(in_channels, out_channels, stride)

        self.shortcut = nn.Sequential()
        if in_channels != out_channels:
            self.shortcut.add_module('downsample',
                                     DownsamplingShortcut(in_channels))

    def forward(self, x):
        x1 = self.residual_path1(x)
        x2 = self.residual_path2(x)

        if self.training:
            shake_config = self.shake_config
        else:
            shake_config = (False, False, False)

        alpha, beta = get_alpha_beta(x.size(0), shake_config, x.device)
        y = shake_function(x1, x2, alpha, beta)

        return self.shortcut(x) + y

class Network(nn.Module):
    def __init__(self, cfg):
        super(Network, self).__init__()

        print("Building Network of resnet Shake-Shake")

        self.cfg = cfg

        input_shape = (1, self.cfg.TRAIN.IM_CHANNELS, self.cfg.TRAIN.IM_SIZE, \
             self.cfg.TRAIN.IM_SIZE)

        print(f"Input_shape: {input_shape}")
        # input_shape = (1,3,224,224)

        n_classes = self.cfg.MODEL.NUM_CLASSES

        base_channels = self.cfg.SHAKE_SHAKE.BASE_CHANNELS
        #config['base_channels']
        depth = self.cfg.SHAKE_SHAKE.DEPTH
        #config['depth']
        self.shake_config = (self.cfg.SHAKE_SHAKE.FORWARD, self.cfg.SHAKE_SHAKE.BACKWARD, self.cfg.SHAKE_SHAKE.IMAGE)
        #(config['shake_forward'], config['shake_backward'],config['shake_image'])

        block = BasicBlock

        n_blocks_per_stage = (depth - 2) // 6
        assert n_blocks_per_stage * 6 + 2 == depth, f"Condition (n_blocks_per_stage * 6 + 2) == model_depth fails as model_depth: {model_depth} \
            and n_blocks_per_stage*6 + 2 = {n_blocks_per_stage*6 + 2}"

        n_channels = [base_channels, base_channels * 2, base_channels * 4]

        self.conv = nn.Conv2d(
            input_shape[1],
            n_channels[0],
            kernel_size=3,
            stride=1,
            padding=1,
            bias=False)

        self.bn = nn.BatchNorm2d(base_channels)

        self.stage1 = self._make_stage(
            n_channels[0], n_channels[0], n_blocks_per_stage, block, stride=1)
        self.stage2 = self._make_stage(
            n_channels[0], n_channels[1], n_blocks_per_stage, block, stride=2)
        self.stage3 = self._make_stage(
            n_channels[1], n_channels[2], n_blocks_per_stage, block, stride=2)

        # # compute conv feature size

        # with torch.no_grad():
        #     self.feature_size = self._forward_conv(
        #         torch.zeros(1,3,224,224)).view(-1).shape[0]

        self.feature_size = 128

        # if self.cfg.TRAIN.DATASET == "IMAGENET":
        #     self.feature_size = 128
        # else:
        #     self.feature_size = 128
        #     #raise NotImplementedError

        self.fc = nn.Linear(self.feature_size, n_classes)

        ###
        self.penultimate_active = False
        #Describe model with source code link
        self.description = "Open source implementation of Resnet shake-shake adapted from hysts/pytorch_shake_shake/ repository"

        self.source_link = "https://github.com/hysts/pytorch_shake_shake/blob/master/shake_shake.py"

        self.model_depth = cfg.MODEL.TRANSFER_MODEL_DEPTH if cfg.TRAIN.TRANSFER_EXP else cfg.MODEL.DEPTH

        logger.info('Constructing: Shake Shake ResNet with depth:{}'.format(self.model_depth))

        # initialize weights
        self.apply(initialize_weights)

    def _make_stage(self, in_channels, out_channels, n_blocks, block, stride):
        stage = nn.Sequential()
        for index in range(n_blocks):
            block_name = 'block{}'.format(index + 1)
            if index == 0:
                stage.add_module(
                    block_name,
                    block(
                        in_channels,
                        out_channels,
                        stride=stride,
                        shake_config=self.shake_config))
            else:
                stage.add_module(
                    block_name,
                    block(
                        out_channels,
                        out_channels,
                        stride=1,
                        shake_config=self.shake_config))
        return stage

    def _forward_conv(self, x):
        x = F.relu(self.bn(self.conv(x)), inplace=True)
        x = self.stage1(x)
        x = self.stage2(x)
        x = self.stage3(x)
        x = F.adaptive_avg_pool2d(x, output_size=1)
        return x

    def forward(self, x):
        x = self._forward_conv(x)
        z = x.view(x.size(0), -1)
        # print(f"~~z.shape[1]: {z.shape[1]}")
        x = self.fc(z)
        if self.penultimate_active:
            return z,x
        return x


from rest_framework import generics
from rest_framework.response import Response
from .models import Ganado, Categoria, Raza, LitrosDeLeche
from .serializers import GanadoSerializer,CategoriaSerializer, RazaSerializer, LitrosDeLecheSerializer
from django.views.generic import View

class GanadoListCreateAPIView(generics.ListCreateAPIView):
    queryset = Ganado.objects.all()
    serializer_class = GanadoSerializer

class GanadoRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Ganado.objects.all()
    serializer_class = GanadoSerializer

class GanadoDestroyAPIView(generics.DestroyAPIView):
    queryset = Ganado.objects.all()
    serializer_class = GanadoSerializer

class GanadoSearchView(View):
    def get(self, request):
        search_query = request.GET.get('search')
        if search_query:
            ganados = Ganado.objects.filter(nombre__icontains=search_query)
        else:
            ganados = Ganado.objects.all()
        return render(request, 'ganado_search.html', {'ganados': ganados, 'search_query': search_query})

    #categoria

class CategoriaListCreateAPIView(generics.ListCreateAPIView):
    queryset = Categoria.objects.all()
    serializer_class = CategoriaSerializer

class CategoriaRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Categoria.objects.all()
    serializer_class = CategoriaSerializer

class CategoriaDestroyAPIView(generics.DestroyAPIView):
    queryset = Categoria.objects.all()
    serializer_class = CategoriaSerializer

class CategoriaSearchView(View):
    def get(self, request):
        search_query = request.GET.get('search')
        if search_query:
            categorias = Categoria.objects.filter(nombre__icontains=search_query)
        else:
            categorias = Categoria.objects.all()
        return render(request, 'ganado_search.html', {'ganados': categorias, 'search_query': search_query})

    #Raza

class RazaListCreateAPIView(generics.ListCreateAPIView):
    queryset = Raza.objects.all()
    serializer_class = RazaSerializer

class RazaRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Raza.objects.all()
    serializer_class = RazaSerializer

class RazaDestroyAPIView(generics.DestroyAPIView):
    queryset = Raza.objects.all()
    serializer_class = RazaSerializer

#litros de leche
class LitrosDeLecheListCreateAPIView(generics.ListCreateAPIView):
    queryset = LitrosDeLeche.objects.all()
    serializer_class = LitrosDeLecheSerializer

class LitrosDeLecheRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = LitrosDeLeche.objects.all()
    serializer_class = LitrosDeLecheSerializer

class LitrosDeLecheDestroyAPIView(generics.DestroyAPIView):
    queryset = LitrosDeLeche.objects.all()
    serializer_class = LitrosDeLecheSerializer


import random
from turtle import Turtle, Screen
import turtle
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
is_race_on = False
i = 0
all_turtles = []
red = Turtle(shape="turtle")
red.color(colors[i])
i += 1
screen = Screen()

screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")

red.penup()
red.goto(-230, -99)
all_turtles.append(red)

orange = Turtle(shape="turtle")
orange.color(colors[i])
i += 1
orange.penup()
orange.goto(-230, -66)
all_turtles.append(orange)

yellow = Turtle(shape="turtle")
yellow.color(colors[i])
i += 1
yellow.penup()
yellow.goto(-230, -33)
all_turtles.append(yellow)

green = Turtle(shape="turtle")
green.color(colors[i])
i += 1
green.penup()
green.goto(-230, 33)
all_turtles.append(green)

blue = Turtle(shape="turtle")
blue.color(colors[i])
i += 1
blue.penup()
blue.goto(-230, 66)
all_turtles.append(blue)

purple = Turtle(shape="turtle")
purple.color(colors[i])
i += 1
purple.penup()
purple.goto(-230, 99)
all_turtles.append(purple)
is_race_on = True

while is_race_on:
    for turtlee in all_turtles:
        if turtlee.xcor() > 230:
            print(f"Turtle of color {turtlee.pencolor()} has won the race.")
            if turtlee == user_bet:
                print("Turtle that you betted on has won the race!")
            else:
                print("Somebodies else's turtle won the race!")
            exit()
        rand_distance = random.randint(0, 10)
        turtlee.forward(rand_distance)

turtle.exitonclick()


from telnetServer import TelnetServer
from player import Player
from mud import Mud
from worker import Worker
from busevent import BusEvent
from mysql import Mysql
from callback import Callback
import time

def loadBroadcasts(mysql, callbacks, worker):
    for i in mysql.getEntry("select time_interval, message from broadcast"):
        if not i:
            return
        callbacks.register(i["time_interval"], worker.broadcast, i["message"])

server = TelnetServer("0.0.0.0", 23)
mud = Mud("data.xml")
bus = BusEvent()
mysql = Mysql('localhost', 'mud', 'root', '')
if not mysql.ok:
    print("Error while connecting to mysql")
    exit()
if not mud.begin:
    print("Error while loading data for mud")
    exit()
worker = Worker(mud, server, bus, mysql)
callbacks = Callback()
loadBroadcasts(mysql, callbacks, worker)

while server.update():
    worker.connections()
    worker.disconnections()
    worker.messages()
    callbacks.run()
    time.sleep(0.2)


L=[]
K=[]
M=[]
R=[]
def Solution():
  for i in range(100,1000):
    L.append(i)
    print(L)
  for a in range(1,10):
    for b in range(0,10):
      for c in range(0,10):
          K=[str(a),str(b),str(c),str(c),str(b),str(a)]
          new=''.join(K)
          print(new)
          M.append(int(new))
  print(M)
  for j in L:
    for p in L:
      if j*p in M:
        R.append(j*p)
        print(('{}x{} = {}').format(j,p,j*p))
  R.sort()
  print(R)
Solution()


from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask_app.controllers.users import User

class Sighting:
    def __init__(self, data):
        self.id = data['id']
        self.location = data['location']
        self.scenario = data['scenario']
        self.date_of_sighting = data['date_of_sighting']
        self.qty_of_sq = data['qty_of_sq']
        self.created_at = data['created_at']
        self.updated_at = data['updated_at']
        self.user = None
        self.skeptic_user = []

    @classmethod
    def all_sightings(cls):
        query = """
                SELECT * FROM sightings
                JOIN users on sightings.user_id = users.id;
                """
        results = connectToMySQL('sasquatch2').query_db(query)
        sightings = []
        if not results:
            return sightings
        for info in results:
            sighting = cls(results[0])
            row = {
                'id': info['users.id'],
                'first_name': info['first_name'],
                'last_name': info['last_name'],
                'email': info['email'],
                'password': "",
                'created_at': info['users.created_at'],
                'updated_at': info['users.updated_at']

            }
            sighting.user = User(row)
            sightings.append(sighting)
        return sightings

    @classmethod
    def add_sighting(cls,data):
        query = """
                INSERT INTO sightings(location, scenario, date_of_sighting, qty_of_sq, created_at, updated_at, user_id)
                VALUES(%(location)s, %(scenario)s, %(date_of_sighting)s, %(qty_of_sq)s,NOW(), NOW(), %(user_id)s);
                """
        results = connectToMySQL('sasquatch2').query_db(query,data)
        return results

    @classmethod
    def getidby(cls,data):
        query = """
                SELECT * FROM sightings
                WHERE id = %(id)s;
                """
        results = connectToMySQL('sasquatch2').query_db(query,data)
        return cls(results[0])

    @classmethod
    def update_sightings(cls,data):
        query = """
                UPDATE sightings
                SET location = %(location)s, scenario = %(scenario)s, date_of_sighting = %(date_of_sighting)s, qty_of_sq = %(qty_of_sq)s, updated_at = NOW()
                WHERE id = %(id)s;
                """
        results = connectToMySQL('sasquatch2').query_db(query,data)
        return results

    @staticmethod
    def validate_sighting(sighting_info):
        is_valid = True

        if len(sighting_info['location']) < 2:
            flash("Location is needed/Not valid location")
            is_valid = False
        if len(sighting_info['scenario']) < 2:
            flash("Tell us what happened/Not a valid entry")
            is_valid = False
        if sighting_info['qty_of_sq'] == ''  :
            flash("Please tell us how many you saw")
            is_valid = False
        if sighting_info['date_of_sighting'] == ''  :
            flash("Please input a date")
            is_valid = False

        return is_valid

    @classmethod
    def remove_sighting(cls, data):
        query = """
                DELETE FROM sightings
                WHERE id = %(id)s
                """
        results = connectToMySQL('sasquatch2').query_db(query,data)
        return results

    @classmethod
    def skeptic_sight(cls):
        query = """
                SELECT * FROM sightings
                LEFT JOIN skeptics ON sightings.id = skeptics.sighting_id
                LEFT JOIN users ON users.id = skeptics.user_id
                WHERE sightings.id = %(id)s;
                """
        results = connectToMySQL('sasquatch2').query_db(query)
        sightings = []
        if not results:
            return sightings
        for sight in results:
            if sight['users.id'] == None:
                break
            sighting = cls(results[0])
            data ={
                'id': sight['users.id'],
                'first_name': sight['first_name'],
                'last_name': sight['last_name'],
                'email': sight['email'],
                'password': "",
                'created_at': sight['users.created_at'],
                'updated_at': sight['users.updated_at']
            }
            sighting.user= User(data)
            sightings.append(sighting)
        return sightings


from . import bp
from flask.views import MethodView
from app import db
from app.schemas import JobQueryArgsSchema, JobSchema
from app.models import Job

@bp.route('/jobs')
class Jobs(MethodView):
    @bp.arguments(JobQueryArgsSchema, location="query")
    @bp.response(JobSchema(many=True))
    @bp.paginate()
    def get(self, args, pagination_parameters):
        """List all jobs currently available"""
        data, total = Job.get(args, pagination_parameters.page,
                              pagination_parameters.page_size)
        pagination_parameters.item_count = total
        return data

    @bp.arguments(JobSchema)
    @bp.response(JobSchema)
    def post(self, job):
        """Post a new job with tags"""
        db.session.add(job)
        db.session.commit()
        return job


import json
import time
import os
import datetime

from scraper.halooglasi import get_latest_with_retry
from scraper.db import check_if_exists, insert_property
from scraper.discord import send_to_discord
from scraper.logger import logger

def get_local_time():
    """
    convert current time to CEST
    """
    cest_time = datetime.datetime.now() + datetime.timedelta(hours=2)
    return cest_time.strftime("%D %H:%M:%S")

def main():
    CFG_FILE = os.environ.get("CFG_FILE", "/app/config.json")
    # in seconds
    SLEEP_TIME = float(os.environ.get("SLEEP_TIME", 30))

    config = []
    while True:
        with open(CFG_FILE, "r") as f:
            _config = json.load(f)
            if _config != config:
                logger.info(f"New config: {_config}")
                config = _config

        for url, hook_url in config.items():
            logger.info(f"Scraping... {get_local_time()}")
            results = get_latest_with_retry(url, max_retries=5, sleep_time=SLEEP_TIME)
            for link, price, name, location in results[::-1]:
                if not check_if_exists(link):
                    insert_property(link, price, name, location)
                    logger.info(f"Inserted {name} with price {price}")
                    send_to_discord(link, price, name, location, hook_url=hook_url)
            time.sleep(SLEEP_TIME)

if __name__ == "__main__":
    main()


import util
from command import process_command
import session as discord_session
import filters
from discord import Embed
from logger import log

# for the memes
from random import choice

@util.client.event
async def on_message(message):
    if message.author.bot:
        # check to make sure it didn't send message
        if message.author == util.client.user:
            return

        # brandon clauses
        if message.content.startswith('What do you call a'):
            await insult(message)
        elif message.content.startswith('How do you'):
            await insult(message)
        return

    try:
        await handle_message(message)
    except Exception as e:
        log(message.server.id, str(e))
        await util.client.send_message(message.channel, embed=Embed(color=util.error_color, description='An unknown error occurred.'))

async def insult(message):
    messages = [
        'That joke wasn\'t funny and it never will be.',
        'You are not funny.',
        'Please be quiet for all of our sakes.',
        'You make me want to die.',
        'You don\'t need to tell jokes; you are one.',
        'Inferior...',
        ':joy: :gun:',
        '```Roses are red,\nViolets are blue,\nThat bot is garbage,\nand Brandon is too.```'
    ]
    await util.client.send_message(message.channel, choice(messages))

@util.client.event
async def on_server_join(server):
    embed = Embed(color=util.theme_color, title='Null Bot')
    embed.description = 'Null is a fully featured, powerful, multipurpose Discord bot from easy use on any server.'
    embed.add_field(name='Get Started', value='Use `!help` to get list of command and how to use them.', inline=False)
    embed.add_field(name='Support', value='**Donate** donate_url\n**Source** github_url\n**Upvote** upvote_url', inline=False)
    embed.add_field(name='Join our Discord', value='discord_url', inline=False)
    icon_url = 'https://cdn.discordapp.com/avatars/226732838181928970/19562db0c14f445ac5a0bf8f605989c1.png?size=128'
    embed.set_footer(text='Developed by ComedicChimera#3451', icon_url=icon_url)
    await util.client.send_message(server.default_channel, embed=embed)

@util.client.event
async def on_member_join(member):
    if member.id in util.servers[member.server].hack_bans:
        await util.client.kick(member)
    else:
        await util.client.send_message(member.server.default_channel, 'Welcome `%s`!' % member.name)

async def handle_message(message):
    prefix = util.get_server_prefix(message.server)
    # use custom input handler if specified
    if discord_session.has_session(message.server, message.channel, message.author):
        await util.client.send_typing(message.channel)
        s = discord_session.get_session(message.server, message.channel, message.author)
        await s.handler(message, s.session_id)
    # else pass to command handler
    elif message.content.startswith(prefix):
        await process_command(message, prefix)
    # apply filters
    elif filters.match_filters(message):
        await util.client.delete_message(message)

if __name__ == '__main__':
    # imported command sets
    import modules.general.commands
    import modules.music.commands
    import modules.math.commands
    import modules.internet.commands
    import modules.money.commands
    import modules.games.commands
    import modules.admin.commands

    # start the bot
    util.client.run(util.token)


#!/usr/bin/env python
# vim: set expandtab tabstop=4 shiftwidth=4:

import sys
from ftexplorer.data import Data

data = Data('BL2')

locker_count = 0
for (name, node) in data.get_level_package_nodes('GaiusSanctuary_P'):
    for point in node.get_children_with_name('willowpopulationopportunitypoint'):
        point_struct = point.get_structure()
        if 'Locker' in point_struct['PopulationDef']:
            locker_count += 1
            print('{}.{}'.format(name, point))
print('--')
print('Locker count: {}'.format(locker_count))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep  2 11:44:08 2019

@author: ashish
"""

import pandas as pd
import numpy as np
import seaborn as sn
import matplotlib.pyplot as plt
import time

dataset = pd.read_csv('new_appdata10.csv')

# Data Preprocessing

response = dataset["enrolled"]
dataset = dataset.drop(columns='enrolled')

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(dataset, response, test_size=0.2, random_state=0)

train_identifier = X_train['user']
X_train = X_train.drop(columns='user')

test_identifier = X_test['user']
X_test = X_test.drop(columns='user')

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train2 = pd.DataFrame(sc_X.fit_transform(X_train))
X_test2 = pd.DataFrame(sc_X.transform(X_test))
X_train2.columns = X_train.columns.values
X_test2.columns = X_test.columns.values
X_train2.index = X_train.index.values
X_test2.index = X_test.index.values
X_train = X_train2
X_test = X_test2

# Model Building

from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state=0, penalty='l1')
classifier.fit(X_train, y_train)

y_predict = classifier.predict(X_test)

from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score

cm = confusion_matrix(y_test, y_predict)
accuracy_score(y_test, y_predict)
precision_score(y_test, y_predict)
recall_score(y_test, y_predict)
f1_score(y_test, y_predict)

df_cm = pd.DataFrame(cm, index=(0, 1), columns=(0,1))
plt.figure(figsize=(10,7))
sn.set(font_scale=1.4)
sn.heatmap(df_cm, annot=True, fmt='g')
print("Test Data Accuracy: %0.4f" % accuracy_score(y_test, y_predict))

from sklearn.model_selection import cross_val_score

accuracies = cross_val_score(estimator = classifier, X=X_train, y=y_train, cv=10)

print("Logistic Accuracy: %0.3f (+/- %0.3f)" % (accuracies.mean(), accuracies.std() * 2))


#tire_volume.py
from datetime import datetime
import math
print('This program calculte the tire volume')
print()
form_1 = 0
volume_1 = None

w=float(input('Please Enter the width of the tire in mm: '))
a =float(input('Please Enter the aspect ratio of the tire: '))
d =float(input('Enter the diameter of the wheel in inches : '))
w1 =int(w)
a1 =int(a)
d1 =int(d)

volume_1 = math.pi*(w**2)*a*(w*a+2540*d)/10000000000

print('the volume is: {:,.2f}'.format(volume_1))
current_date_and_time = datetime.now()
print(f"{current_date_and_time:%Y-%m-%d}")
with open("tire_volume.txt",'a')as volume_file:
    print(file = volume_file)
    print(f"{current_date_and_time:%Y-%m-%d}, {w1}, {a1}, {d1}, {volume_1:,.2f}", file = volume_file)


import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import logging
import os
import pymongo
from urllib.parse import urlparse
from datetime import datetime

# constants
MESSAGE_START_CONFIRMED = 'Okay. Asking feedback from **{}** to **{}**.'
MESSAGE_WRONG_FORMAT = 'Wrong usage of command.'
MESSAGE_NOT_A_COMMAND_ADMIN = 'Sorry, I can\'t recognize that command.'
MESSAGE_NOT_A_COMMAND_NOTADMIN = '''Hi! There is no feedback session currently, we will let you know when it is.
You can check whether you received any feedback by typing in the `list` command.'''
MESSAGE_ADMIN_USAGE = '''If you want to start a session, type `start @giver @receiver`.
If you want to define new questions, type `questions define`.
If you want to list feedback given to you, type `list`.'''
MESSAGE_ASK_FOR_FEEDBACK = ('Hi! It\'s feedback time! Please write your feedback to **{}**! '
                            'Be specific, extended and give your feedback on behavior. '
                            'And don\'t forget to give more positive feedback than negative!')
MESSAGE_FEEDBACK_CONFIRMED = 'You\'ve given **{}** the following feedback: {}. Thank you!'
MESSAGE_LIST_FEEDBACK = 'You have got the following feedback until now: \n{}'
MESSAGE_NO_FEEDBACK_AVAILABLE = '''Sorry, you haven''t got any feedback until now.
Ask an admin to start a feedback session, so you can got feedback.'''
MESSAGE_DEFINE_QUESTIONS = 'You can add new questions by issuing the `questions` command'
MESSAGE_CURRENT_QUESTIONS = 'These are the questions currently defined: \n{}'
MESSAGE_NO_QUESTIONS = 'There are no questions defined.'
MESSAGE_WANT_NEW_QUESTION = 'Do you want to add a new question? (`yes`/`no`)'
MESSAGE_ADD_NEW_QUESTION = 'Please type in your question.'
MESSAGE_EXIT_DEFINE_QUESTIONS = 'You have chosen to exit adding more questions.'
MESSAGE_DEFINE_QUESTIONS_YESNO = 'Please respond with either `yes` or `no`.'
MESSAGE_NEXT_QUESTION = 'The next question is: '
MESSAGE_WANT_REMOVE_QUESTION = 'Please type in the number of the question you want to remove '
MESSAGE_EXIT_REMOVE_QUESTIONS = 'You have chosen to exit removing more questions. '
MESSAGE_REMOVE_QUESTIONS_ONLY_NUMBERS = 'Please choose from the list of numbers corresponding to the questions '
MESSAGE_REMOVE_QUESTIONS_CANCEL = 'or `cancel` if you want to exit question removal.'
MESSAGE_REMOVAL_SUCCESS = 'Successfully removed question.'
LOG_GOT_MESSAGE = 'Got message from user {}: {}'
LOG_SENDING_MESSAGE = 'Sending message to user {}: {}'
ENVVAR_TOKEN = 'FEEDBACKBOT_TOKEN'

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('feedbackbot')

class MemberNotFound(Exception):
    pass

class RoleOrMemberNotFound(Exception):
    pass

# global variables
client = Bot(description="feedbackbot by Sly (test version)",
             command_prefix="", pm_help=False)

mongodb_uri = os.environ.get('MONGODB_URI')
try:
    conn = pymongo.MongoClient(mongodb_uri)
    logger.info('Database connection successful.')
except pymongo.errors.ConnectionFailure as e:
    logger.error('Could not connect to MongoDB: {}'.format(e))

db = conn[urlparse(mongodb_uri).path[1:]]

def is_admin(user_id):
    """Checks whether the giver user is in the 'admins' role in any of the servers the bot is connected to."""
    for server in client.servers:
        for member in server.members:
            if member.id == user_id:
                for role in member.roles:
                    if role.name == 'admins':
                        return True
                return False
    return False

def get_member_by_username(username_string):
    """Returns the Member object if it's found on any of the servers the bot is connected to.
    Otherwise, raises an exception."""

    # username and discriminator like @szilveszter.erdos#7945
    elements = username_string.strip('@').split('#')
    username = elements[0]
    if len(elements) > 1:
        discriminator = elements[1]
    else:
        discriminator = ''

    for server in client.servers:
        for member in server.members:
            if member.name == username and member.discriminator == discriminator:
                return member
    raise MemberNotFound('Username `{}` not found.'.format(username))

def get_member_or_role(name_string):
    """Returns the member/mention or members of a role/mention in a list on any of the servers
    the bot is connected to. Otherwise, raises an exception."""
    try:
        member = get_member_by_username(name_string)
        return [member], member.nick
    except MemberNotFound:
        members = []
        name_string = name_string.strip('@')
        for server in client.servers:
            for server_role in server.roles:
                if server_role.name == name_string:
                    # search for all members with that role
                    for member in server.members:
                        for member_role in member.roles:
                            if member_role == server_role:
                                members.append(member)
                                break
                    break
        if members:
            return members, '@' + server_role.name
        else:
            raise RoleOrMemberNotFound('Username or role `{}` not found.'.format(name_string))

@client.event
async def on_ready():
    """This is what happens everytime the bot launches. """
    print('Logged in as '+client.user.name+' (ID:'+client.user.id+') | Connected to ' +
          str(len(client.servers))+' servers | Connected to '+str(len(set(client.get_all_members())))+' users')
    print('--------')
    print('Current Discord.py Version: {} | Current Python Version: {}'.format(
        discord.__version__, platform.python_version()))
    print('--------')
    print('Use this link to invite {}:'.format(client.user.name))
    print('https://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=8'.format(client.user.id))

    # This is buggy, let us know if it doesn't work.
    return await client.change_presence(game=discord.Game(name='Feedback game ;)'))

async def send_msg(user, msg):
    """Sends a message to a user or channel and logs it. """
    logger.info(LOG_SENDING_MESSAGE.format(user, msg))
    await client.send_message(user, msg)

async def process_ask_queue(giver, first_time=False):
    next_to_ask_details = db['ask-queue'].find_one(
            {
                'id': giver.id,
                'status': 'to-ask'
            }
        )
    if next_to_ask_details:
        receiver_id = next_to_ask_details['receiver_id']
        receiver_nick = next_to_ask_details['receiver_nick']
        question_content = next_to_ask_details['question_content']

        if first_time:
            msg = MESSAGE_ASK_FOR_FEEDBACK.format(receiver_nick)
            await send_msg(giver, msg)

        msg = MESSAGE_NEXT_QUESTION + question_content
        await send_msg(giver, msg)

        db['ask-queue'].update(
            {
                'id': giver.id,
                'receiver_id': receiver_id
            },
            {
                '$set': {
                    'status': 'asked'
                }
            }
        )

def push_ask_queue(receiver, giver, question):
    db['ask-queue'].insert(
        {
            'id': giver.id,
            'giver_nick': giver.nick,
            'receiver_id': receiver.id,
            'receiver_nick': receiver.nick,
            'question_content': question['content'],
            'status': 'to-ask'
        }
    )

async def list_questions(message):
    """List questions defined in the database with numbering. """

    if 'questions' in db.collection_names() and db['questions'].count():
        questions_db = list(db['questions'].find({}, {'content': 1}))
        questions_with_index_str = \
            ['{}. {}'.format(i+1, e['content']) for i, e in enumerate(questions_db) if 'content' in e]
        questions_str = '\n'.join(questions_with_index_str)
        msg = MESSAGE_CURRENT_QUESTIONS.format(questions_str)
        await send_msg(message.channel.user, msg)
    else:
        msg = MESSAGE_NO_QUESTIONS

def renumber_questions():
    for counter, question in enumerate(db['questions'].find({})):
        db['questions'].update_one(
            {
                '_id': question['_id']
            },
            {
                '$set': {
                    'index': str(counter + 1)
                }
            },
            upsert=True
        )

async def handle_start_questions_define(message):
    """Handles the `questions` command issued by an admin and starts a conversation
    to add questions. """

    await list_questions(message)

    db['settings'].update_one(
        {
            'status': {
                '$exists': True
            }
        },
        {
            '$set': {
                'status': 'questions-define-pending'
            }
        },
        upsert=True
    )
    msg = MESSAGE_WANT_NEW_QUESTION
    await send_msg(message.channel.user, msg)

async def handle_want_question(message):
    """Handles responding with yes/no while admin in question defining session. """

    if message.content.lower() == 'yes':
        db['settings'].update_one(
            {
                'status': {
                    '$exists': True
                }
            },
            {
                '$set': {
                    'status': 'questions-define-new'
                }
            },
            upsert=True
        )
        msg = MESSAGE_ADD_NEW_QUESTION
        await send_msg(message.channel.user, msg)
    elif message.content.lower() == 'no':
        db['settings'].remove(
            {
                'status': 'questions-define-pending'
            }
        )
        msg = MESSAGE_EXIT_DEFINE_QUESTIONS
        await send_msg(message.channel.user, msg)
    else:
        msg = MESSAGE_DEFINE_QUESTIONS_YESNO
        await send_msg(message.channel.user, msg)

async def handle_add_question(message):
    """Handles adding new question while admin in question defining session. """

    # inserting new question into database
    db['questions'].insert(
        {
            'content': message.content
        }
    )

    renumber_questions()

    # asking whether admin wants new question to add
    db['settings'].update_one(
        {
            'status': {
                '$exists': True
            }
        },
        {
            '$set': {
                'status': 'questions-define-pending'
            }
        },
        upsert=True
    )
    await list_questions(message)
    msg = MESSAGE_WANT_NEW_QUESTION
    await send_msg(message.channel.user, msg)

async def handle_start_question_removal(message):
    """Handles `question remove` command issued by an admin, lists the currently defined questions
    and gives an opportunity to remove from them. """

    await list_questions(message)

    msg = MESSAGE_WANT_REMOVE_QUESTION + MESSAGE_REMOVE_QUESTIONS_CANCEL
    await send_msg(message.channel.user, msg)

    db['settings'].update_one(
        {
            'status': {
                '$exists': True
            }
        },
        {
            '$set': {
                'status': 'questions-remove-pending'
            }
        },
        upsert=True
    )

async def handle_question_remove(message):
    """Handles removing questions while admin in question removal session. """

    if message.content.lower() == 'cancel':
        db['settings'].remove(
            {
                'status': 'questions-remove-pending'
            }
        )
        msg = MESSAGE_EXIT_REMOVE_QUESTIONS
        await send_msg(message.channel.user, msg)
    # we can assume that indexes are continous since we renumber them after each insert/remove with renumber_questions()
    elif message.content in [str(i+1) for i in range(db['questions'].count())]:
        db['questions'].remove(
            {
                'index': message.content
            }
        )
        renumber_questions()
        msg = MESSAGE_REMOVAL_SUCCESS + '\n' + MESSAGE_WANT_REMOVE_QUESTION + MESSAGE_REMOVE_QUESTIONS_CANCEL
        await list_questions(message)
        await send_msg(message.channel.user, msg)
    else:
        msg = MESSAGE_REMOVE_QUESTIONS_ONLY_NUMBERS + MESSAGE_REMOVE_QUESTIONS_CANCEL
        await send_msg(message.channel.user, msg)

async def handle_start(message):
    """Handles the `start @giver @receiver` command issued by an admin and starts a
    feedback session. """

    # if we have questions defined
    if 'questions' in db.collection_names():
        msg_elements = message.content.split()
        # because usage is `start @giver @receiver`
        if len(msg_elements) == 3:
            # get member or role and confirm command
            try:
                givers, giver_mention = get_member_or_role(msg_elements[1])
                receivers, receiver_mention = get_member_or_role(msg_elements[2])
            except RoleOrMemberNotFound as e:
                msg = str(e)
                await send_msg(message.channel.user, msg)
            else:
                msg = MESSAGE_START_CONFIRMED.format(giver_mention, receiver_mention)
                await send_msg(message.channel.user, msg)

                # asking for feedback
                for giver in givers:
                    for receiver in receivers:
                        if receiver is not giver:
                            for question in db['questions'].find({}):
                                push_ask_queue(receiver, giver, question)
                    await process_ask_queue(giver, True)

        else:
            msg = MESSAGE_WRONG_FORMAT + '\n' + MESSAGE_ADMIN_USAGE
            await send_msg(message.channel.user, msg)
    else:
        msg = MESSAGE_NO_QUESTIONS + ' ' + MESSAGE_DEFINE_QUESTIONS
        await send_msg(message.channel.user, msg)

async def handle_list(message):
    """Handles `list` command and lists given feedback messages. """
    feedback_details = db['feedbacks'].find_one({'id': message.author.id})
    if feedback_details is not None:
        question_list = {}
        for feedback in feedback_details['feedback']:
            if feedback['question_content'] not in question_list:
                question_list[feedback['question_content']] = []

            question_list[feedback['question_content']].append(
                '**{}** ({:%Y.%m.%d. %H:%M}): {}'.format(
                    feedback['giver_nick'],
                    feedback['datetime'],
                    feedback['message']
                )
            )

        feedback_list_str = ''
        for question_content, feedback_list in question_list.items():
            feedback_list_str += '\n*' + question_content + '*\n'
            for feedback_str in feedback_list:
                feedback_list_str += '\t' + feedback_str + '\n'

        msg = MESSAGE_LIST_FEEDBACK.format(feedback_list_str)
    else:
        msg = MESSAGE_NO_FEEDBACK_AVAILABLE
    await send_msg(message.channel.user, msg)

async def handle_send_feedback(message):
    """Handles feedback sent as an answer to the bot's question. """
    ask_details = db['ask-queue'].find_one({'id': message.author.id, 'status': 'asked'})
    giver_nick = ask_details['giver_nick']
    giver = message.author
    receiver_id = ask_details['receiver_id']
    receiver_nick = ask_details['receiver_nick']
    question_content = ask_details['question_content']

    db['feedbacks'].update_one(
        {
            'id': receiver_id,
            'receiver_nick': receiver_nick
        },
        {
            '$push': {
                'feedback': {
                    'giver': giver.id,
                    'giver_nick': giver_nick,
                    'question_content': question_content,
                    'message': message.content,
                    'datetime': datetime.now()
                }
            }
        },
        upsert=True
    )

    # confirm feedback
    msg = MESSAGE_FEEDBACK_CONFIRMED.format(receiver_nick, message.content)
    await send_msg(message.channel.user, msg)

    # remove from queue and continue processing
    db['ask-queue'].remove({'id': giver.id, 'receiver_id': receiver_id, 'question_content': question_content})
    await process_ask_queue(giver)

@client.event
async def on_message(message):
    """This is what happens every time when the bot sees a message. """
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    # we do not want the bot to reply not in a pm
    elif message.channel.type.name != 'private':
        return
    # admin starting the session
    elif message.content.startswith('start') and is_admin(message.author.id):
        await handle_start(message)
    # admin starting question defining
    elif message.content.startswith('questions define') and is_admin(message.author.id):
        await handle_start_questions_define(message)
    # admin answering yes/no while defining questions
    elif 'settings' in db.collection_names() and \
            db['settings'].find_one({'status': 'questions-define-pending'}) and \
            is_admin(message.author.id):
        await handle_want_question(message)
    # admin typing in new question
    elif 'settings' in db.collection_names() and \
            db['settings'].find_one({'status': 'questions-define-new'}) and \
            is_admin(message.author.id):
        await handle_add_question(message)
    # admin starting question removal
    elif message.content.startswith('questions remove') and is_admin(message.author.id):
        await handle_start_question_removal(message)
    # admin remove question
    elif 'settings' in db.collection_names() and \
            db['settings'].find_one({'status': 'questions-remove-pending'}) and \
            is_admin(message.author.id):
        await handle_question_remove(message)
    # receiver listing feedback
    elif message.content.startswith('list'):
        await handle_list(message)
    # giver sending a feedback
    elif db['ask-queue'].find_one({'id': message.author.id, 'status': 'asked'}):
        await handle_send_feedback(message)
    # not matching any case
    else:
        if is_admin(message.author.id):
            msg = MESSAGE_NOT_A_COMMAND_ADMIN + '\n' + MESSAGE_ADMIN_USAGE
            await send_msg(message.channel, msg)
        else:
            msg = MESSAGE_NOT_A_COMMAND_NOTADMIN
            await send_msg(message.channel, msg)

    try:
        logger.info(LOG_GOT_MESSAGE.format(message.channel.user.name, message.content))
    except AttributeError:
        logger.info(LOG_GOT_MESSAGE.format(message.channel, message.content))

if __name__ == '__main__':
    if ENVVAR_TOKEN in os.environ:
        token = os.environ.get(ENVVAR_TOKEN)
        client.run(token)
    else:
        print("Please define an environment variable named {} and put the secret token into it!".format(ENVVAR_TOKEN))


import argparse
import logging
import os
import shutil
import subprocess
import time

logging.basicConfig(level=logging.DEBUG)

parser = argparse.ArgumentParser(description="Famous Submitter")
parser.add_argument("-t", "--tag", type=str, help="Dataset tag.")
parser.add_argument("-i", "--input", type=str, help="Input filelist")
parser.add_argument(
    "-r",
    "--resubmits",
    type=int,
    default=10,
    help="Number of resubmissions.",
    required=False,
)
parser.add_argument(
    "-hours",
    "--hours",
    type=float,
    default=1.0,
    help="Number of hours per resubmission, in addition to the time between sample submissions.",
    required=False,
)
parser.add_argument(
    "-ms",
    "--movesample",
    type=int,
    default=0,
    help="Move each sample after submitting it (accomplishes it during the buffer time between samples set by default in monitor.py).",
)
parser.add_argument(
    "-m",
    "--move",
    type=int,
    default=0,
    help="Move all samples after all submissions (during the buffer specified by -hours).",
)
parser.add_argument(
    "-dry", "--dryrun", type=int, default=0, help="running without submission"
)

options = parser.parse_args()
nResubmits = options.resubmits
nHours = options.hours
tag = options.tag

username = os.environ["USER"]
dataDir = f"/data/submit/{username}/SUEP/{tag}/"
moveDir = f"/work/submit/{username}/SUEP/{tag}/"

# Making sure that the proxy is good
proxy_base = f"x509up_u{os.getuid()}"
home_base = os.environ["HOME"]
proxy_copy = os.path.join(home_base, proxy_base)
regenerate_proxy = False
if not os.path.isfile(proxy_copy):
    logging.warning("--- proxy file does not exist")
    regenerate_proxy = True
else:
    lifetime = subprocess.check_output(
        ["voms-proxy-info", "--file", proxy_copy, "--timeleft"]
    )
    lifetime = float(lifetime)
    lifetime = lifetime / (60 * 60)
    logging.info(f"--- proxy lifetime is {round(lifetime, 1)} hours")
    if lifetime < nHours * nResubmits * 1.5:
        logging.warning("--- proxy has expired !")
        regenerate_proxy = True

if regenerate_proxy:
    redone_proxy = False
    while not redone_proxy:
        status = os.system(
            "voms-proxy-init -voms cms --hours=" + str(nHours * nResubmits * 1.5)
        )
        if os.WEXITSTATUS(status) == 0:
            redone_proxy = True
    shutil.copyfile("/tmp/" + proxy_base, proxy_copy)

logging.info("Running resubmission script from " + str(os.environ["HOSTNAME"]))
for i in range(nResubmits):
    logging.info("Resubmission " + str(i))
    logging.info("Removing all jobs...")
    os.system("condor_rm {}".format(os.environ["USER"]))
    logging.info("Checking for corrupted files and removing them...")

    t_start = time.time()

    # delete files that are corrupted
    subDirs = os.listdir(dataDir)
    for subDir in subDirs:
        for file in os.listdir(dataDir + subDir):
            size = os.path.getsize(dataDir + subDir + "/" + file)
            if size == 0:
                subprocess.run(["rm", dataDir + subDir + "/" + file])
            elif size < 5000:
                subprocess.run(["rm", dataDir + subDir + "/" + file])

    if not options.dryrun:
        logging.info("Executing monitor.py ...")
        os.system(
            "python3 monitor.py --tag={} --input={} -r=1 -m={}".format(
                tag, options.input, options.movesample
            )
        )

    if options.move:
        if not os.path.isdir(moveDir):
            os.system("mkdir " + moveDir)

        subDirs = os.listdir(dataDir)

        for subDir in subDirs:
            if not os.path.isdir(moveDir + subDir):
                os.system("mkdir " + moveDir + subDir)

            # get list of files already in /work
            movedFiles = os.listdir(moveDir + subDir)

            # get list of files in T3
            allFiles = os.listdir(dataDir + subDir)

            # get list of files missing from /work that are in T3
            filesToMove = list(set(allFiles) - set(movedFiles))

            # move those files
            logging.info(
                "Moving " + str(len(filesToMove)) + " files to " + moveDir + subDir
            )
            for file in filesToMove:
                subprocess.run(
                    [
                        "xrdcp",
                        "root://submit50.mit.edu/" + dataDir + subDir + "/" + file,
                        moveDir + subDir + "/",
                    ]
                )

    t_end = time.time()

    # don't wait if it's the last submission
    if i == nResubmits - 1:
        logging.info("All done")
        break

    # wait to resubmit jobs using the parameter <hours>, accounts for time it took to submit them
    sleepTime = 60 * 60 * nHours
    mod = t_end - t_start
    logging.info("Submitting and moving files took " + str(round(mod)) + " seconds")
    if sleepTime - mod <= 0:
        continue
    if nHours > 0:
        logging.info("Sleeping for " + str(round(sleepTime - mod)) + " seconds")
        logging.info("(" + str(round(nHours - mod * 1.0 / 3600, 2)) + " hours)...")
    time.sleep(sleepTime - mod)


'''Task
You are given the shape of the array in the form of space-separated integers,
each integer representing the size of different dimensions,
your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones.'''

import numpy as np

N,M,P = map(int,input().split())
arr=[]
for _ in range(P):
    arr.append(np.zeros((N,M),dtype= np.int))
arr=np.array(arr)
print(arr)
arr=[]
for _ in range(P):
    arr.append(np.ones((N,M),dtype= np.int))
arr=np.array(arr)
print(arr)


import os
import ctypes

dir_path = os.path.dirname(os.path.realpath(__file__))
lib = ctypes.cdll.LoadLibrary(dir_path  + "/" + "larcv2_to_larcv3.so")
class larcv2_to_larcv3(object):
    def __init__(self):
        lib.larcv2_to_larcv3_new.argtypes = []
        lib.larcv2_to_larcv3_new.restype = ctypes.c_void_p
        lib.larcv2_to_larcv3_add_in_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
        lib.larcv2_to_larcv3_add_in_file.restype = ctypes.c_void_p
        lib.larcv2_to_larcv3_set_out_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
        lib.larcv2_to_larcv3_set_out_file.restype = ctypes.c_void_p
        lib.larcv2_to_larcv3_initialize.argtypes = [ctypes.c_void_p]
        lib.larcv2_to_larcv3_initialize.restype = ctypes.c_void_p
        lib.larcv2_to_larcv3_convert.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
        lib.larcv2_to_larcv3_convert.restype = ctypes.c_void_p
        self.obj = lib.larcv2_to_larcv3_new()

    def add_in_file(self, in_file):
        # in_file = in_file.encode('utf-8')
        # # in_file = bytes(in_file, encoding="ascii")
        # print(in_file)
        # print(type(in_file))
        lib.larcv2_to_larcv3_add_in_file(self.obj, in_file.encode('utf-8'))

    def set_out_file(self, out_file):
        lib.larcv2_to_larcv3_set_out_file(self.obj, out_file.encode('utf-8'))

    def initialize(self):
        lib.larcv2_to_larcv3_initialize(self.obj)

    def convert(self, n_events, n_skip):
        lib.larcv2_to_larcv3_convert(self.obj, n_events, n_skip)

import argparse

def main():
    parser = argparse.ArgumentParser(description='LArCV2 to larcv3 Conversion script')

    parser.add_argument('-il','--input-larcv',required=True,
                        dest='larcv_fin',nargs='+',
                        help='string or list, Input larcv file name[s] (Required)')

    parser.add_argument('-nevents','--num-events',
                        type=int, dest='nevents', default=-1,
                        help='integer, Number of events to process')

    parser.add_argument('-nskip','--num-skip',
                        type=int, dest='nskip', default=0,
                        help='integer, Number of events to skip before processing')

    parser.add_argument('-ol','--output-larcv',default='',
                        type=str, dest='larcv_fout',
                        help='string,  Output larcv file name (optional)')

    args = parser.parse_args()
    print(args)
    converter = larcv2_to_larcv3()

    for file_name in args.larcv_fin:
        converter.add_in_file(file_name)

    if args.larcv_fout == "":
        print("No output file specified, using basename and same path as first input.")
        args.larcv_fout = args.larcv_fin[0].replace(".root", ".h5")

    converter.set_out_file(args.larcv_fout)

    converter.initialize()
    converter.convert(args.nevents, args.nskip)

if __name__ == "__main__":
    main()

# # help(conversion_libs)
# # print(conversion_libs)

# # conversion_libs.add_in_file


import numpy as np
from copy import deepcopy

class Car:
    # x, y in meters
    # angle in radians
    # velocity in meters/sec
    # dt in seconds

    def __init__(self, x_init, y_init, L, theta_init, phi_init, velocity_init, dt, goal_loc,
                max_velocity=25.0, min_velocity=-25.0, max_angle=45,
                fov=180*np.pi/180, n_reflections=1, max_laser_distance=15, unoccupied_points_per_meter=0.5):
        # position values
        self.x_pos = x_init
        self.y_pos = y_init
        self.L = L
        self.theta = theta_init
        self.phi = phi_init
        self.dt = dt
        self.goal_loc = goal_loc
        self.dist_to_goal = np.sqrt((x_init - goal_loc[0]) ** 2 + (y_init - goal_loc[1]) ** 2)

        # kinematic values
        self.velocity = velocity_init

        # constraints on dynamics
        self.max_velocity = max_velocity
        self.min_velocity = min_velocity
        self.max_turn_angle = max_angle * np.pi / 180

        self.max_phi_dot = 50 * np.pi / 180
        self.max_v_dot = 7

        # lidar data
        self.dist_theta = [0] * n_reflections
        self.fov = fov
        self.n_reflections = n_reflections
        self.max_laser_distance = max_laser_distance
        self.unoccupied_points_per_meter = unoccupied_points_per_meter

        angle_goal_car    = np.arctan2((goal_loc[1] - y_init), (goal_loc[0] - x_init))
        if angle_goal_car < 0:
            angle_goal_car += 2 * np.pi
        self.angle_to_goal = angle_goal_car - self.theta
        if self.angle_to_goal > np.pi:
            self.angle_to_goal -= 2 * np.pi

        # initialize state variables
        self.s = None
        self.a = None
        self.sp = None

        self.goal_reached = False
        self.map_max_dist = np.sqrt(25**2 + 50**2)

    def get_robot_pos(self):
        return [self.x_pos, self.y_pos, self.theta]

    def apply_car_kinematics(self, v_dot, phi_dot):
        # position updates
        self.x_pos    += np.cos(self.theta) * self.velocity * self.dt
        self.y_pos    += np.sin(self.theta) * self.velocity * self.dt
        self.theta    += 1.0 / self.L * np.tan(self.phi) * self.velocity * self.dt
        if self.theta > 2 * np.pi:
            self.theta -= 2 * np.pi
        elif self.theta < 0:
            self.theta += 2 * np.pi

        # velocity updates
        self.phi      = clamp(self.phi + phi_dot * self.dt, -self.max_turn_angle, self.max_turn_angle)
        self.velocity = clamp(self.velocity + v_dot * self.dt, self.min_velocity, self.max_velocity)

    def update(self, v_dot, phi_dot, obstacles):

        # save old state for reward calculation
        # contains lidar readings, goal dist, and goal angle at time t

        # self.dist_theta = get_laser_ref(obstacles, self.fov, self.n_reflections, self.max_laser_distance, self.get_robot_pos())

        self.s = (deepcopy(self.dist_theta), self.dist_to_goal, self.angle_to_goal * 180 / np.pi, self.get_robot_pos())

        # save old action taken
        self.a = (v_dot, phi_dot)

        # apply kinematics
        self.apply_car_kinematics(v_dot, phi_dot)

        # update dist to goal
        self.dist_to_goal = np.sqrt((self.x_pos - self.goal_loc[0]) ** 2 + (self.y_pos - self.goal_loc[1]) ** 2)

        # update angle to goal
        angle_goal_car    = np.arctan2((self.goal_loc[1] - self.y_pos), (self.goal_loc[0] - self.x_pos))
        if angle_goal_car < 0:
            angle_goal_car += 2 * np.pi
        self.angle_to_goal = angle_goal_car - self.theta
        if self.angle_to_goal > np.pi:
            self.angle_to_goal -= 2 * np.pi

        # update lidar reading
        self.dist_theta = get_laser_ref(obstacles, self.fov, self.n_reflections, self.max_laser_distance, self.get_robot_pos())

        # save sprime
        self.sp = (deepcopy(self.dist_theta), self.dist_to_goal, self.angle_to_goal * 180 / np.pi, self.get_robot_pos())

    # call update before calling reward
    def reward(self):
        # calculates the cummulative reward of taking an action in s_old and transitioning
        # to a new state by taking an action a
        # returns:
            # reward, game_flag

        lidar_old = self.s[0]
        lidar_new = self.sp[0]

        gdist_old = self.s[1]
        gdist_new = self.sp[1]

        theta_old = self.s[2]
        theta_new = self.sp[2]

        reward = 0
        end_game = False

########################################################################

        if gdist_new <= 2:
            reward = 10
            end_game = True
            self.goal_reached = True
            print("GOAL")
            return (reward, end_game)

        hit_points = np.where(np.array(lidar_new) <= 2)[0]
        if hit_points.size >= 1:
            reward = -10
            end_game = True
            return (reward, end_game)              # return a large negative value and end game

        end_game = False

        if theta_old > 0 and self.a[1] > 0 or theta_old < 0 and self.a[1] < 0:
            reward += 0.01 * np.abs(self.a[1]) # 5
        elif theta_old > 0 and self.a[1] < 0 or theta_old < 0 and self.a[1] > 0:
            reward -= 0.03 * np.abs(self.a[1]) # 15

        # 3. if we move towards the goal give reward based on scaling
        # scaling_factor = 0.25 #1 / np.sqrt((100) ** 2 + (50) ** 2)        # WARNING! HARDCODED field dimensions (100, 50)
        # delta_goal_dist = scaling_factor / self.dist_to_goal    # TODO: change a scaling factor potentially
        # reward += delta_goal_dist

        diff_arr =  np.array(lidar_new) - np.array(lidar_old)
        diff_arr, wts = get_arr_wts(np.array(diff_arr))        # get the distances in the 180 degree fov and corresponding weights

        scaling_factor = 0.1
        cummulative_reward = np.sum(scaling_factor * diff_arr * wts)
        reward += cummulative_reward

########################################################################

        return (reward, end_game)

    def state_numpy(self):
        r = np.empty((len(self.dist_theta) + 5))
        r[:len(self.dist_theta)] = self.dist_theta / float(self.max_laser_distance)
        r[len(self.dist_theta)] = self.s[1]
        r[len(self.dist_theta) + 1] = self.s[2]
        r[len(self.dist_theta) + 2:] = np.array(self.get_robot_pos())
        return r

def clamp(value, minimum, maximum):
    if value > maximum:
        return maximum
    elif value < minimum:
        return minimum
    return value

def get_arr_wts(a):
    # remove last value
    a = a[:-1]

    # get num lasers in each quadrant
    n_quad_1 = np.ceil(90 / (360.0 / a.size)).astype(np.int16)
    n_quad_2 = np.floor(90 / (360.0 / a.size)).astype(np.int16)

    # extract and form an array
    arr1 = np.flip(a[:n_quad_1])
    arr2 = np.flip(a[-n_quad_2:])
    arr = np.concatenate((arr1, arr2))
    norm_arr = (np.arange(-n_quad_1 + 1, n_quad_2 + 1))

    mu    = np.mean(norm_arr)
    sigma = np.std(norm_arr)

    wts = []
    for i in range(norm_arr.size):
        wts.append(np.round(0.4 * np.exp(-(0.5) * ((norm_arr[i] - mu) / (sigma)) ** 2), 2))

    return(arr, wts)

def get_laser_ref(segments, fov=np.pi, n_reflections=180, max_dist=100, xytheta_robot=np.array([0.0, 0.0])):
    """
    :param segments: start and end points of all segments as ((x1,y1,x1',y1'), (x2,y2,x2',y2'), (x3,y3,x3',y3'), (...))
           fov: sight of the robot - typically pi or 4/3*pi
           n_reflections: resolution=fov/n_reflections
           max_dist: max distance the robot can see. If no obstacle, laser end point = max_dist
           xy_robot: robot's position in the global coordinate system
    :return: 1xn_reflections array indicating the laser end point
    """
    xy_robot = xytheta_robot[:2] #robot position
    theta_robot = xytheta_robot[2] #robot angle in rad

    angles = np.linspace(theta_robot, theta_robot+fov, n_reflections)
    dist_theta = max_dist*np.ones(n_reflections) # set all laser reflections to 100

    for seg_i in segments:
        xy_i_start, xy_i_end = np.array(seg_i[:2]), np.array(seg_i[2:]) #starting and ending points of each segment
        for j, theta in enumerate(angles):
            xy_ij_max = xy_robot + np.array([max_dist*np.cos(theta), max_dist*np.sin(theta)]) # max possible distance
            intersection = get_intersection(xy_i_start, xy_i_end, xy_robot, xy_ij_max)

            if intersection is not None: #if the line segments intersect
                r = np.sqrt(np.sum((intersection-xy_robot)**2)) #radius

                if r < dist_theta[j]:
                    dist_theta[j] = r

    return dist_theta

def get_intersection(a1, a2, b1, b2) :
    """
    :param a1: (x1,y1) line segment 1 - starting position
    :param a2: (x1',y1') line segment 1 - ending position
    :param b1: (x2,y2) line segment 2 - starting position
    :param b2: (x2',y2') line segment 2 - ending position
    :return: point of intersection, if intersect; None, if do not intersect
    #adopted from https://github.com/LinguList/TreBor/blob/master/polygon.py
    """
    def perp(a) :
        b = np.empty_like(a)
        b[0] = -a[1]
        b[1] = a[0]
        return b

    da = a2-a1
    db = b2-b1
    dp = a1-b1
    dap = perp(da)
    denom = np.dot(dap, db)
    num = np.dot( dap, dp )

    if denom.astype(float) == 0:
        denom = denom + 1
    intersct = np.array((num/denom.astype(float))*db + b1) ## TODO: check divide by zero!

    delta = 1e-3
    condx_a = min(a1[0], a2[0])-delta <= intersct[0] and max(a1[0], a2[0])+delta >= intersct[0] #within line segment a1_x-a2_x
    condx_b = min(b1[0], b2[0])-delta <= intersct[0] and max(b1[0], b2[0])+delta >= intersct[0] #within line segment b1_x-b2_x
    condy_a = min(a1[1], a2[1])-delta <= intersct[1] and max(a1[1], a2[1])+delta >= intersct[1] #within line segment a1_y-b1_y
    condy_b = min(b1[1], b2[1])-delta <= intersct[1] and max(b1[1], b2[1])+delta >= intersct[1] #within line segment a2_y-b2_y
    if not (condx_a and condy_a and condx_b and condy_b):
        intersct = None #line segments do not intercept i.e. interception is away from from the line segments

    return intersct