# -*- coding: utf-8 -*-
"""
This module contains any functions directly related to ROI operations and queries.
"""
import sys
import os.path
import math
import lib
import roi

import numpy as np

import logging
from HMR_RS_LoggerAdapter import HMR_RS_LoggerAdapter

base_logger = logging.getLogger("hmrlib." + os.path.basename(__file__)[:-3])
""" The basic logger object used for logging in hmrlib.
It was loaded in memory by python-sphinx, which is why you see the object's address!"""

logger = HMR_RS_LoggerAdapter(base_logger)
""" The basic logger object adapted with an HMR_RS_LoggerAdapter.
It was loaded in memory by python-sphinx, which is why you see the object's address!"""

# To allow importation of module by sphinx-python
try:
    from connect import *
    # import ScriptClient
except Exception as e:
    if 'IronPython' in sys.version:
        raise
    else:
        pass

def get_poi(poi_name, examination=None):
    """
    Returns POI object from a POI name.

    Args:
        poi_name (str): the name of the POI
        examination (str, optional): the name of the examination (CT or StructureSet) for which the poi is defined; if left out the currently selected examination is used.

    Returns:
        the RayStation POI object
    """
    patient = lib.get_current_patient()

    if examination is None:
        examination = lib.get_current_examination()

    try:
        poi = [x for x in patient.PatientModel.StructureSets[examination.Name].PoiGeometries if x.OfPoi.Name == poi_name][0]

        if abs(poi.Point.x) == sys.float_info.max or abs(poi.Point.x) == sys.float_info.min:
            lib.error('POI %s is not segmented on current examination.  Select correct CT and try again.' % poi_name)

        return poi
    except IndexError as e:
        logger.error('No POI found named %s', poi_name)
        logger.exception(e)
        raise
    except Exception as e:
        logger.exception(e)
        raise

def show_poi_coordinates(poi_name):
    """
        In a popup window, shows DICOM coordinates of a specific POI defined for the current patient model in RayStation.

        Args:
            poi_name (str): the name of the POI for which to show the coordinates
    """
    import gui
    # poi = get_poi(poi_name)
    coords = get_poi_coordinates(poi_name)
    msg = 'Les coordonnées DICOM du point "%s" sont : [x = %.2f cm, y = %.2f cm, z = %.2f cm]' % (poi_name, coords.x, coords.y, coords.z)
    gui.show_log_window(msg)

def show_all_poi_coordinates():
    """
        In a popup window, shows DICOM coordinates of all POIs defined to the current patient model.
    """
    import gui
    patient = lib.get_current_patient()
    poi_names = [r.Name for r in patient.PatientModel.PointsOfInterest]
    msg = ''
    for poi_name in poi_names:
        coords = get_poi_coordinates(poi_name)
        #msg += 'Les coordonnées DICOM du point "%s" sont : [x = %.2f cm, y = %.2f cm, z = %.2f cm]\n' % (poi_name, coords.x, coords.y, coords.z)
        msg += '%s: [x = %.2f cm, y = %.2f cm, z = %.2f cm]\n' % (poi_name, coords.x, coords.y, coords.z)
    #gui.show_log_window(msg)
    return msg

def identify_isocenter_poi():
    """ Attempts to identify isocenter POI.

        The expected name of the isocenter POI is either *ISO* or *ISO SCAN*.
        If either of the two is found, it is returned, with priority to *ISO*.
        If not, the shortest string in the name candidates is returned.

        Returns:
            str: Name of most probable isocenter POI if found, `None` if not.
    """
    patient = lib.get_current_patient()
    poi_names = [r.Name for r in patient.PatientModel.PointsOfInterest]
    iso_candidates = [x for x in poi_names if x.upper().startswith('ISO')]

    # No candidates
    if len(iso_candidates) == 0:
        logger.warning('No isocenter POI could be found.')
        return None

    # Multiple candidates
    if len(iso_candidates) > 1:
        for i in sorted(iso_candidates, key=lambda x: len(x)):
            if i.upper() == 'ISO':
                logger.info('Isocenter POI identified as "%s"', i)
                return i
            if i.upper() == 'ISO SCAN':
                logger.info('Isocenter POI identified as "%s"', i)
                return i

        # If all else fails, return shortest string.
        guess = sorted(iso_candidates, key=lambda x: len(x))[0]
        logger.warning('Best isocenter POI candidate is "%s"', guess)
        return guess

    # Case where there is only 1 candidates
    logger.info('Isocenter POI identified as "%s"', iso_candidates[0])
    return iso_candidates[0]

def set_poi_type(poi_name, poi_type='Marker'):
    """
    Sets a POI to a given POI type.

    Args:
        poi_name (str): the name of the POI for which to set the type
        poi_type (str, optional): the type of the POI.  By default, will set to type *Marker*.
    """

    if get_poi_approval(poi_name):
        logger.warning('POI "%s" is approved and therefore cannot be changed.' % poi_name)
        return

    patient = lib.get_current_patient()
    try:
        patient.PatientModel.PointsOfInterest[poi_name].Type = poi_type
        logger.info('Type of POI "%s" set as %s', poi_name, poi_type)
    except Exception as e:
        logger.exception(e)
        raise

def auto_assign_poi_types():
    """
        Attempts to automatically assign correct POI types.

        Assumes localization point has string *SCAN* as part of its name.
        If no POI with *SCAN* in its name ca be found, the isocenter will
        be assumed to be the proper localization point.

        Isocenter is set to the type *isocenter*, save for the case above.

        All other POIs are set to type *marker*.
    """
    patient = lib.get_current_patient()
    poi_names = [p.Name for p in patient.PatientModel.PointsOfInterest]

    iso_name = identify_isocenter_poi()

    set_poi_type(iso_name, 'Isocenter')

    loc_name = [p.Name for p in patient.PatientModel.PointsOfInterest if 'SCAN' in p.Name.upper()]
    if len(loc_name) > 1:
        logger.error('More than one POI found for possible localization points.  Only one POI should exist with "SCAN" in its name.')
        raise SystemError('More than one POI found for possible localization points.  Only one POI should exist with "SCAN" in its name.')
    elif len(loc_name) == 0:
        logger.warning('No localization point could be found.  Using the isocenter point for localization.')
        loc_name = iso_name
        set_poi_type(loc_name, 'LocalizationPoint')
    else:
        loc_name = loc_name[0]
        set_poi_type(loc_name, 'LocalizationPoint')

    done_pois = [iso_name, loc_name]

    for p in poi_names:
        if p not in done_pois:
            set_poi_type(p, 'Marker')

def place_prescription_point(target_fraction_dose, ptv_name, poi_name, beamset=None, exam=None):
    """
    Attempts to place automatically a POI on a target per-fraction isodose line.

    .. rubric::
      PRE-REQUISITES

    - Existence of an identifiable PTV contour.
    - Dose is calculated.

    .. rubric::
      Algorithm description

    - A point on the PTV contour on a slice near the PTV center is found.
    - The dose is evaluated at that point.
    - An approximate unit vector towards the PTV center is calculated from that position.
        + If the evaluated dose is smaller than the prescription dose, the evaluation point is moved a short distance towards the PTV center.
        + If the evaluated dose is greater than the prescription dose, the evaluation point is moved a short distance away from the PTV center.
    - If the prescription dose is overshot by this procedure, the direction of movement is reversed and the move distance halved.
    - This process is repeated until evaluated dose equals the prescription dose to 3 decimal figures or 100 iterations are reached.

    Finally,

    - The specified POI is placed at the found coordinates.

    .. seealso::
      function `hmrlib.hmrlib.auto_place_prescription_point`

    """

    patient = lib.get_current_patient()
    if exam is None:
        exam = lib.get_current_examination()

    if beamset is None:
        beamset = lib.get_current_beamset()

    try:
        # Get PTV center
        ptv_center = lib.RSPoint(point=patient.PatientModel.StructureSets[exam.Name].RoiGeometries[ptv_name].GetCenterOfRoi())

        # Get slice thickness from CT
        slice_width = abs(exam.Series[0].ImageStack.SlicePositions[1] - exam.Series[0].ImageStack.SlicePositions[0])
        logger.info('CT slice width = %s cm', slice_width)

        initial_point = None
        # Find contour point on a slice close to PTV center
        for c in patient.PatientModel.StructureSets[exam.Name].RoiGeometries[ptv_name].PrimaryShape.Contours:
            #if lib.check_version(4.7):
            if c[0].z < ptv_center.z + slice_width and c[0].z > ptv_center.z - slice_width:
                initial_point = lib.RSPoint(c[0].x, c[0].y, c[0].z)
                break
            #else:
            #    if c.ContourData[0].z < ptv_center.z + slice_width and c.ContourData[0].z > ptv_center.z - slice_width:
            #        initial_point = lib.RSPoint(c.ContourData[0].x, c.ContourData[0].y, c.ContourData[0].z)
            #        break

        if initial_point is None:
            logger.info('Could not find a point on the same slice as the ROi center. Disjoint/noncoplanar PTV?')
            logger.info('Trying with first point in contour shape.')
            c = patient.PatientModel.StructureSets[exam.Name].RoiGeometries[ptv_name].PrimaryShape.Contours[0]
            #if lib.check_version(4.7):
            initial_point = lib.RSPoint(c[0].x, c[0].y, c[0].z)
            #else:
            #    initial_point = lib.RSPoint(c.ContourData[0].x, c.ContourData[0].y, c.ContourData[0].z)

        logger.info('Initial point = %s cm', initial_point)

        u = lib.RSPoint(point=lib.unit_vector(ptv_center - initial_point))
        logger.info('Unit vector towards PTV center = %s cm', u)

        # Change unit vector so that we stay on the same transverse slice
        u.z = 0
        logger.info('Approximate unit vector towards PTV center on single CT slice = %s cm', u)

        def move_point(point, direction, target_fraction_dose, initial_dose, step=0.05, iteration=0):
            point = point + step * direction
            dose = beamset.FractionDose.InterpolateDoseInPoint(Point=point.value)
            logger.info('Dose at %s = %.3f cGy', point, dose)
            if round(dose, 3) == round(target_fraction_dose, 3) or iteration > 100:
                # Found a suitable point or reached max iterations
                return point
            elif (initial_dose < target_fraction_dose and dose > target_fraction_dose) or (initial_dose > target_fraction_dose and dose < target_fraction_dose):
                # We overshot the point, so inverse direction and reduce step
                return move_point(point, -direction, target_fraction_dose, dose, step=0.5 * step, iteration=iteration + 1)
            else:
                # Keep going in the same direction with same step
                return move_point(point, direction, target_fraction_dose, dose, step=step, iteration=iteration + 1)

        dose = beamset.FractionDose.InterpolateDoseInPoint(Point=initial_point.value)

        if math.isnan(dose):
            lib.error('No dose value available.  Check if dose is calculated.')

        logger.info('Dose per fraction at initial point = %.3f cGy', dose)

        # Assume dose rises when moving towards center of PTV
        if dose < target_fraction_dose:
            point = move_point(initial_point, u, target_fraction_dose, dose)
        else:
            point = move_point(initial_point, -u, target_fraction_dose, dose)

        logger.info('Final point = %s cm', point)

    except Exception as e:
        logger.exception(e)
        raise

    if get_poi_approval(poi_name):
        logger.warning('POI %s is approved; cannot continue.', poi_name)
        lib.error('POI %s exists and is approved; cannot continue.  Unapprove %s before running script.' % (poi_name, poi_name))

    set_poi_coordinates(poi_name, point, examination=exam)

    return point

def auto_place_prescription_point():
    """
    Attempts to place automatically a POI on the prescription dose isoline near
    the boundaries of the PTV contour.

    .. rubric::
      PRE-REQUISITES

    1. Prescription dose defined for current beamset.
    2. Existence of a dose specification point (requires manual creation).
    3. Existence of an identifiable PTV contour.
    4. Dose is calculated.

    .. rubric::
      Algorithm description

    - A point on the PTV contour on a slice near the PTV center is found.
    - The dose is evaluated at that point.
    - An approximate unit vector towards the PTV center is calculated from that position.
        + If the evaluated dose is smaller than the prescription dose, the evaluation point is moved a short distance towards the PTV center.
        + If the evaluated dose is greater than the prescription dose, the evaluation point is moved a short distance away from the PTV center.
    - If the prescription dose is overshot by this procedure, the direction of movement is reversed and the move distance halved.
    - This process is repeated until evaluated dose equals the prescription dose to 3 decimal figures or 100 iterations are reached.

    Finally,

    - A POI named *PT PRESC* is placed at the final coordinates of the evaluation point.  This POI is created if not already existing.
    - The prescription is changed to prescribe the prescription dose at the final evaluation point, on the prescription dose isoline.  It is thus automatically satisfied.

    .. seealso::
      function `hmrlib.hmrlib.place_prescription_point`

    """
    # patient = lib.get_current_patient()
    # exam = lib.get_current_examination()
    beamset = lib.get_current_beamset()

    # Create PT PRESC if not present
    create_poi({'x': 0, 'y': 0, 'z': 0}, 'PT PRESC')

    ptv_candidates = roi.identify_ptvs2()
    if len(ptv_candidates) > 1:
        logger.warning('More than one possible PTV found: %s.  Trying highest PTV in the list %s.', ptv_candidates, sorted(ptv_candidates, key=lambda x: x[3:], reverse=True)[0])
    elif len(ptv_candidates) == 0:
        logger.error('No PTV could be found.  Aborting.')
        raise SystemError('No PTV could be found.  Aborting.')

    ptv = sorted(ptv_candidates, key=lambda x: x[3:], reverse=True)[0]
    logger.info('PTV identified as %s', ptv)

    try:
        presc_dose = lib.get_prescription_dose()
        logger.info('Presc dose = %.3f cGy', presc_dose)

        fractions = lib.get_fractions()
        logger.info('Fractions = %s', fractions)

        target_dose = presc_dose / float(fractions)
        logger.info('Target dose = %.3f cGy', target_dose)

    except Exception as e:
        logger.exception(e)
        raise

    point = place_prescription_point(target_dose, ptv, 'PT PRESC', beamset=beamset)

    # Set prescription to PT PRESC
    try:
        beamset.AddDosePrescriptionToPoi(PoiName='PT PRESC', DoseValue=presc_dose)
    except Exception as e:
        logger.exception(e)
        raise

    # Update dose specification point
    try:
        dsp = [x for x in beamset.DoseSpecificationPoints][0]
        dsp.Coordinates = point.value
    except IndexError as e:
        logger.error('You must create a dose specification point manually before executing this script.')
        logger.exception(e)
        raise
    except Exception as e:
        logger.exception(e)
        raise

    # Set beam dose specification points
    # Doesn't really update point coordinates for some reason.
    # Leaving to the user to do manually.
    # for b in beamset.Beams:
    #     b.SetDoseSpecificationPoint(Name=dsp.Name)

def create_poi(point, name, color='Green', poi_type='Marker', examination=None):
    """
    Creates a new POI.

    Args:
        point (dict or RSPoint): the (x, y, z) DICOM coordinates of the new point
        name (str): the name of the new POI
        color (str, optional): the color of the new POI (default: *Green*)
        poi_type (str, optional): the type of the new POI (default: *Marker*)

    Returns:
        the RayStation POI object corresponding to the newly created POI
    """

    # Must used dictionary representation of the point if an RSPoint
    if isinstance(point, lib.RSPoint):
        point = point.value

    patient = lib.get_current_patient()
    if examination is None:
        examination = lib.get_current_examination()

    try:
        poi = patient.PatientModel.CreatePoi(Examination=examination, Point=point, Volume=0, Name=name, Color=color, Type=poi_type)
        return poi
    except SystemError as e:
        if str(e) == 'Name not unique':
            logger.warning('A POI named %s already exists.' % name)
    except Exception as e:
        logger.exception(e)
        raise

def poi_exists(poi_name, examination=None):
    """
        Checks if a POI exists.

    Args:
        poi_name (str): the name of the POI
        examination (str, optional): the name of the examination (CT or StructureSet) for which the poi is defined; if left out the currently selected examination is used.

    Returns:
        True if it exists, False if not.

    """
    patient = lib.get_current_patient()

    if examination is None:
        examination = lib.get_current_examination()

    try:
        poi = [x for x in patient.PatientModel.StructureSets[examination.Name].PoiGeometries if x.OfPoi.Name == poi_name][0]
    except:
        return False

    if abs(poi.Point.x) == sys.float_info.max or abs(poi.Point.x) == sys.float_info.min:
        # Not segmented
        return False

    return True

def get_poi_approval(poi_name, examination=None):
    """
    Checks if POI named *poi_name* is approved (in any of the existing beamsets).

    TODO: handle the case where no beamsets or no plans exists, implying that
    the structures cannot be approved ?

    Args:
        poi_name (str): the name of the POI
        examination (str, optional): the name of the examination (CT or StructureSet) for which the poi is defined; if left out the currently selected examination is used.

    Returns:
        True if the POI is approved, False if not.
    """

    patient = lib.get_current_patient()

    if examination is None:
        examination = lib.get_current_examination()

    # print 'before'

    try:
        for beamset_approved_structure_set in patient.PatientModel.StructureSets[examination.Name].ApprovedStructureSets:
            for beamset_approved_pois in beamset_approved_structure_set.ApprovedPoiStructures:
                if beamset_approved_pois.OfPoi.Name == poi_name:
                    # print 'after True'
                    logger.info('POI %s is approved.', poi_name)
                    return True
        # print 'after False'
        logger.info('POI %s is NOT approved.', poi_name)
        return False
    except Exception as e:
        logger.exception(e)
        raise

def get_poi_coordinates(poi_name, examination=None):
    """
        Returns coordinates of POI poi_name in DICOM coordinate system.

        Args:
            poi_name (str): the name of the POI for which to get the coordinates
            examination (str, optional): the name of the examination (CT or StructureSet) for which the poi is defined; if left out the currently selected examination is used.

        Returns:
            RSPoint: the POI's DICOM coordinates in a RSPoint object
    """
    poi = get_poi(poi_name, examination)
    logger.info('POI %s: (x, y, z) = (%s, %s, %s)', poi_name, poi.Point.x, poi.Point.y, poi.Point.z)
    # poi.Point is a RayStation ExpandoObject

    return lib.RSPoint(point=poi.Point)
    # return dict(x=poi.Point.x, y=poi.Point.y, z=poi.Point.z)

def set_poi_coordinates(poi_name, point, examination=None):
    """
        Sets POI DICOM coordinates for POI poi_name to those specified in point.

        Args:
            point (RSPoint or RayStation ExpandoObject): the new DICOM coordinates of the point
    """
    if examination is None:
        examination = lib.get_current_examination()

    poi = get_poi(poi_name, examination=examination)

    # Need to check if POI is approved.  If it it, setting the coordinates
    # will crash RayStation.
    if get_poi_approval(poi_name):
        logger.warning('POI "%s" is approved and therefore cannot be changed.' % poi_name)
        return

    try:
        # ====================================================================
        # For some reason this doesn't update point coords !!
        # but also doesn't produce an error.
        # poi.Point.x = point.x
        # poi.Point.y = point.y
        # poi.Point.z = point.z
        # ====================================================================

        # ... but this does update the coordinates, also silently.
        poi.Point = {'x': point.x, 'y': point.y, 'z': point.z}
        logger.info('Set coordinates of POI "%s" to %s.', poi_name, point)
    except Exception as e:
        logger.exception(e)
        raise

def create_iso(exam=None):
    """
    Checks to see if a point named ISO exists. If not, the script creates a copy of REF SCAN to serve as the isocenter.

    Args:
        exam : RayStation examination object
    """
    if exam is None:
        exam = lib.get_current_examination()
    if not poi_exists("ISO", exam):
        if poi_exists("REF SCAN", exam):
            REF_SCAN_coords = get_poi_coordinates('REF SCAN', exam)
            create_poi(REF_SCAN_coords, 'ISO', 'Blue', 'Isocenter', exam)

def erase_pois_not_in_list(poi_list=None):

    patient = lib.get_current_patient()

    if poi_list is None:
        poi_list = ['ISO', 'REF SCAN']
    for poi in patient.PatientModel.PointsOfInterest:
        if not poi.Name.upper() in poi_list:
            poi.DeleteRoi()

def get_max_dose_coordinates(dose,grid):

    #Convert the 3D dose into a one-dimensional list and determine the index for the voxel that receives the highest dose

    dose_list = list(dose.DoseValues.DoseData)

    max_dose = 0
    max_dose_index = 0
    for i,d in enumerate(dose_list):
        if d > max_dose:
            max_dose = d
            max_dose_index = i

    #Convert that index into DICOM coordinates
    nb_vox = [grid.NrVoxels.x,grid.NrVoxels.y,grid.NrVoxels.z]
    res = [grid.VoxelSize.x,grid.VoxelSize.y,grid.VoxelSize.z]
    corner = [grid.Corner.x,grid.Corner.y,grid.Corner.z]

    #NOTE that unravel_index takes coordinates in slowest-changing to fastest-changing order, which in our case means z-y-x
    coords = np.unravel_index(np.array(max_dose_index),(grid.NrVoxels.z,grid.NrVoxels.y,grid.NrVoxels.x))

    x_coord = grid.Corner.x + grid.VoxelSize.x*coords[2]
    y_coord = grid.Corner.y + grid.VoxelSize.y*coords[1]
    z_coord = grid.Corner.z + grid.VoxelSize.z*coords[0]

    #Package the coorindates as a RSPoint object
    max_coords = lib.RSPoint(x_coord,y_coord,z_coord)

    #Note that the dose returned is in cGy and the coordinates are in the DICOM system
    return max_dose,max_coords

def check_eccentricity(poi_name):

    #Script to check if a current point can be used as an isocenter without a collision occurring between the gantry and the patient.
    #Simply creates a large cylinder centered on the point and sets the window/level to Lung so the planner can confirm visually that the clearance is adequate.
    #Currently assumes a safe radius of 40cm for all types of linac, this number may change if further measurements are made.

    patient = lib.get_current_patient()
    exam = lib.get_current_examination()

    lung_dict = dict(x=-600,y=1600)
    exam.Series[0].LevelWindow = lung_dict

    if roi.roi_exists("verif_excentricite",exam):
        patient.PatientModel.RegionsOfInterest["verif_excentricite"].DeleteRoi()

    center = get_poi_coordinates(poi_name,exam)

    patient.PatientModel.CreateRoi(Name="verif_ex_temp1", Color="Green", Type="Organ", TissueName=None, RoiMaterial=None)
    patient.PatientModel.RegionsOfInterest["verif_ex_temp1"].CreateCylinderGeometry(Radius=30, Axis={ 'x': 0, 'y': 0, 'z': 1 }, Length=50, Examination=exam, Center={ 'x': center.x, 'y': center.y, 'z': center.z })

    patient.PatientModel.CreateRoi(Name="verif_ex_temp2", Color="Pink", Type="Organ", TissueName=None, RoiMaterial=None)
    patient.PatientModel.RegionsOfInterest["verif_ex_temp2"].SetMarginExpression(SourceRoiName="verif_ex_temp1", MarginSettings={'Type': "Expand", 'Superior': 0, 'Inferior': 0, 'Anterior': 5, 'Posterior': 5, 'Right': 5, 'Left': 5})
    patient.PatientModel.RegionsOfInterest["verif_ex_temp2"].UpdateDerivedGeometry(Examination=exam)

    patient.PatientModel.CreateRoi(Name="verif_excentricite", Color="Red", Type="Organ", TissueName=None, RoiMaterial=None)
    patient.PatientModel.RegionsOfInterest["verif_excentricite"].SetMarginExpression(SourceRoiName="verif_ex_temp2", MarginSettings={'Type': "Expand", 'Superior': 0, 'Inferior': 0, 'Anterior': 5, 'Posterior': 5, 'Right': 5, 'Left': 5})
    patient.PatientModel.RegionsOfInterest["verif_excentricite"].UpdateDerivedGeometry(Examination=exam)

    patient.PatientModel.RegionsOfInterest["verif_ex_temp1"].DeleteRoi()
    patient.PatientModel.RegionsOfInterest["verif_ex_temp2"].DeleteRoi()


for c in range(0, 5):
    p = float(input('Digite o peso: '))
    if c == 0:
        m = p
        n = p
    else:
        if p > m:
            m = p
        if p < n:
            n = p
print('O maior peso é {}Kg e o menor é {}Kg'.format(m, n))


"""
The (U)nique (ID)entity of a cosmic particle entering earth's atmosphere.
Airshowers have UIDs. Airshowers may lead to a detection by the
instrument which in turn will create a record.
So record-IDs are an instrument-specific measure,
while UIDs are a simulation specific measure to keep track of all
thrown particles when estimating the instrument's response-function.

The UID is related to CORSIKAs scheme of production RUNs and EVENTs within
the runs.
"""
RUN_ID_NUM_DIGITS = 6
EVENT_ID_NUM_DIGITS = 6
UID_NUM_DIGITS = RUN_ID_NUM_DIGITS + EVENT_ID_NUM_DIGITS

RUN_ID_UPPER = 10 ** RUN_ID_NUM_DIGITS
EVENT_ID_UPPER = 10 ** EVENT_ID_NUM_DIGITS

UID_FOTMAT_STR = "{:0" + str(UID_NUM_DIGITS) + "d}"

RUN_ID_FORMAT_STR = "{:0" + str(RUN_ID_NUM_DIGITS) + "d}"
EVENT_ID_FORMAT_STR = "{:0" + str(EVENT_ID_NUM_DIGITS) + "d}"

def make_uid(run_id, event_id):
    assert 0 <= run_id < RUN_ID_UPPER
    assert 0 <= event_id < EVENT_ID_UPPER
    return RUN_ID_UPPER * run_id + event_id

def split_uid(uid):
    run_id = uid // RUN_ID_UPPER
    event_id = uid % RUN_ID_UPPER
    return run_id, event_id

def make_uid_str(run_id, event_id):
    uid = make_uid(run_id, event_id)
    return UID_FOTMAT_STR.format(uid)

def split_uid_str(s):
    uid = int(s)
    return split_uid(uid)


from flask import Flask, render_template
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from bs4 import BeautifulSoup
import requests

#don't change this
matplotlib.use('Agg')
app = Flask(__name__) #do not change this

#insert the scrapping here
url_get = requests.get('https://www.coingecko.com/en/coins/ethereum/historical_data/usd?start_date=2020-01-01&end_date=2021-06-30#panel')
soup = BeautifulSoup(url_get.content,"html.parser")
web_address = "https://www.coingecko.com/en/coins/ethereum/historical_data/usd?start_date=2020-01-01&end_date=2021-06-30#panel"
web_content = requests.get(web_address).text
web_content_soup = BeautifulSoup(web_content, "html.parser")

#find your right key here
table = soup.find('table', attrs={'class': 'table table-striped text-sm text-lg-normal'})
cek_row = table.find_all('tr')
row_length = len(cek_row)
table_ethereum = web_content_soup.find('table', attrs={'class': 'table table-striped text-sm text-lg-normal'})

list_ethereum = [] #initiating a list

for table_rows in table_ethereum.find_all('tr'):
    # Find Header Date
    header_date = table_rows.find('th', attrs={'class': 'font-semibold text-center'})
    if(header_date) != None:
        periode = header_date.text.replace("-", "/")

    # Find record
    column_iteration = 0
    for table_columns in table_rows.find_all('td'):

        if (column_iteration) == 0:
            market_cap = table_columns.text.replace("$", "").replace(",", "").strip()
        elif (column_iteration) == 1:
            volume = table_columns.text.replace("$", "").replace(",", "").strip()
        elif (column_iteration) == 2:
            open_price = table_columns.text.replace("$", "").replace(",", "").strip()
        elif (column_iteration) == 3:
            close = table_columns.text.replace("$", "").replace(",", "").strip()

        if column_iteration == 3:
            list_ethereum.append((periode,market_cap, volume, open_price, close))

        column_iteration += 1

#change into dataframe
df_ethereum = pd.DataFrame(list_ethereum, columns = ('Periode','Market Cap','Volume', 'Open Price', 'Close'))

#insert data wrangling here
df_ethereum['Periode'] = df_ethereum['Periode'].astype('datetime64')
df_ethereum['Volume'] = df_ethereum['Volume'].astype('float64')
df_ethereum = df_ethereum.set_index('Periode')
df_ethereum['Volume'] = df_ethereum['Volume']

#end of data wranggling

@app.route("/")
def index():

	card_data = f'{df_ethereum["Volume"].mean().round(2)}' #be careful with the " and '

	# generate plot
	ax = df_ethereum.plot(figsize = (20,9))

	# Rendering plot
	# Do not change this
	figfile = BytesIO()
	plt.savefig(figfile, format='png', transparent=True)
	figfile.seek(0)
	figdata_png = base64.b64encode(figfile.getvalue())
	plot_result = str(figdata_png)[2:-1]

	# render to html
	return render_template('index.html',
		card_data = card_data,
		plot_result=plot_result
		)

if __name__ == "__main__":
    app.run(debug=True)


from datetime import datetime

from ninja import FilterSchema, Schema
from pydantic import Field, validator

class CourseIn(Schema):
    title: str
    description: str
    slug: str
    language: str
    requirements: str
    what_you_will_learn: str
    level: str
    categories: list[int] | None
    instructors: list[int] | None
    is_published: bool = False

class CourseOut(Schema):
    id: int
    title: str
    description: str
    slug: str
    language: str
    requirements: str
    what_you_will_learn: str
    level: str
    categories: list[int]
    instructors: list[int]
    is_published: bool = False
    created: datetime
    modified: datetime

    @validator('created', 'modified', allow_reuse=True)
    def convert_datetime(cls, value: datetime):
        return value.isoformat()

    @staticmethod
    def resolve_categories(obj):
        return [category.id for category in obj.categories.all()]

    @staticmethod
    def resolve_instructors(obj):
        return [instructor.id for instructor in obj.instructors.all()]

class CourseFilter(FilterSchema):
    categories: str | None = Field(q='categories__in')
    language: str | None = Field(q='language__in')
    level: str | None = Field(q='level__in')

    @validator('categories', 'language', 'level', allow_reuse=True)
    def split_testing(cls, value):
        return value.split(',')

class CourseUpdate(Schema):
    title: str | None
    description: str | None
    slug: str | None
    language: str | None
    requirements: str | None
    what_you_will_learn: str | None
    level: str | None
    categories: list[int] | None
    instructors: list[int] | None
    is_published: bool | None

class InvalidCategoriesOrInstructors(Schema):
    detail: str = 'invalid instructors or categories'

class CourseRelationIn(Schema):
    course_id: int

class CourseRelationOut(Schema):
    id: int
    creator_id: int
    course_id: int
    done: bool
    created: datetime
    modified: datetime

    @validator('created', 'modified', allow_reuse=True)
    def convert_datetime(cls, value: datetime):
        return value.isoformat()

class CourseRelationUpdate(Schema):
    done: bool


from django.contrib import admin

from .models import Service, AppointmentRequest, Appointment, EmailVerificationCode, Config

@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    list_display = ('name', 'duration', 'price', 'created_at', 'updated_at',)
    search_fields = ('name',)
    list_filter = ('duration',)

@admin.register(AppointmentRequest)
class AppointmentRequestAdmin(admin.ModelAdmin):
    list_display = ('date', 'start_time', 'end_time', 'service', 'created_at', 'updated_at',)
    search_fields = ('date', 'service__name',)
    list_filter = ('date', 'service',)

@admin.register(Appointment)
class AppointmentAdmin(admin.ModelAdmin):
    list_display = ('client', 'appointment_request', 'created_at', 'updated_at',)
    search_fields = ('client__user__username', 'appointment_request__service__name',)
    list_filter = ('client', 'appointment_request__service',)

@admin.register(EmailVerificationCode)
class EmailVerificationCodeAdmin(admin.ModelAdmin):
    list_display = ('user', 'code')

@admin.register(Config)
class ConfigAdmin(admin.ModelAdmin):
    list_display = ('slot_duration', 'lead_time', 'finish_time', 'appointment_buffer_time', 'website_name')


import multiprocessing
from multiprocessing import Pool
import time
# def spawn(num):
# 	print('Spawned!{}'.format(num))

# if __name__ == '__main__':
# 	s1 = time.time()
# 	for i in range(500):
# 		p = multiprocessing.Process(target=spawn,args=(i,))
# 		p.start()
# 		#p.join()
# 	e1 = time.time()
# 	s2 = time.time()
# 	for i in range(500):
# 		p = multiprocessing.Process(target=spawn,args=(i,))
# 		p.start()
# 		p.join()
# 	e2 = time.time()

# print(e1-s1,e2-s2)

def  job(num):
	return(2*num)

if __name__=='__main__':
	p = Pool(processes=20)
	data = p.map(job,range(20))
	p.close()
	print(data)

#use map to retrive data from the proceses


"""backend/main.py."""
from typing import Optional

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from maze_generator import ALPHA, DISCOUNT, EPSILON, NUM_EPISODES, MazeGenerator
from pydantic import BaseModel, validator

# Initialize FastAPI app
app = FastAPI(
    title="DungeonMazeGenerator",
    description="Generate a maze with a start, treasure and an end point."
    'Legend: "x"= starting point, "+": treasure point, "o": end point',
)

class MazeGeneratorRequest(BaseModel):
    """MazeGeneratorRequest Model."""

    maze_size: int = 4
    alpha: Optional[float] = ALPHA
    discount: Optional[float] = DISCOUNT
    epsilon: Optional[float] = EPSILON
    num_episodes: Optional[int] = NUM_EPISODES

    @validator("num_episodes", pre=True)
    def validate_num_episodes(cls, v):
        if v <= 0:
            raise ValueError("num_episodes should be a positive integer")
        return v

    @validator("epsilon", pre=True)
    def validate_epsilon(cls, v):
        if not (0 <= v <= 1):
            raise ValueError("epsilon should be between 0 and 1")
        return v

    @validator("alpha", pre=True)
    def validate_alpha(cls, v):
        if not (0 <= v <= 1):
            raise ValueError("alpha should be between 0 and 1")
        return v

    @validator("maze_size", pre=True)
    def validate_maze_size(cls, v):
        if v <= 1:
            raise ValueError("maze_size should be at least 2")
        return v

    @validator("discount", pre=True)
    def validate_discount(cls, v):
        if not (0 <= v <= 1):
            raise ValueError("discount should be between 0 and 1")
        return v

# Endpoint that serves generation of a maze prediction
@app.post("/generate_maze", status_code=200, tags=["Generate maze"])
async def generate_maze(maze_generator_request: MazeGeneratorRequest):
    """Generate a maze.

    :param maze_generator_request: MazeGeneratorRequest model
    :return: StreamingResponse to plot the maze as a response
    """
    maze_generator = MazeGenerator(
        maze_size=maze_generator_request.maze_size,
        alpha=maze_generator_request.alpha,
        discount=maze_generator_request.discount,
        epsilon=maze_generator_request.epsilon,
        num_episodes=maze_generator_request.num_episodes,
    )
    buffer = maze_generator.generate()
    buffer.seek(0)  # Return cursor to starting point
    return StreamingResponse(buffer, media_type="image/png")


import logging

from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware

import pandas as pd

from .convert import xlsx_to_jvfdtm

logging.basicConfig(level=logging.DEBUG)

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:8080"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

@app.post("/convert")
async def convert(file: UploadFile):
    contents = await file.read()
    df = pd.read_excel(contents, header=None)
    xlsx_to_jvfdtm(df)

    return {"ok": "ok"}


"""
server.py
version = 0.002
Remote Access Tool
Made by Lukas Alstrup
github.com/LukasAlstrup/rat

"""
import os
import socket
import base64
import random
import datetime
import time
from functions import *
import threading
import sys
from queue import Queue
import struct
import signal

#Welcome
print("[+] Welcome to Lukas Alstrup's Remote Access tool")
print("""  _     _    _ _  __           _____            _       _____ _______ _____  _    _ _____
 | |   | |  | | |/ /    /\    / ____|     /\   | |     / ____|__   __|  __ \| |  | |  __ \
 | |   | |  | | ' /    /  \  | (___      /  \  | |    | (___    | |  | |__) | |  | | |__) |
 | |   | |  | |  <    / /\ \  \___ \    / /\ \ | |     \___ \   | |  |  _  /| |  | |  ___/
 | |___| |__| | . \  / ____ \ ____) |  / ____ \| |____ ____) |  | |  | | \ \| |__| | |
 |______\____/|_|\_\/_/    \_\_____/  /_/    \_\______|_____/   |_|  |_|  \_\\____/|_|

                                                                                """)

host = "0.0.0.0"
port = 8080

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()

clients = []
addresses = []
names = []

def listen():
    while True:
        client, address = server.accept()
        names.append(client.recv(1024).decode())
        clients.append(client)
        addresses.append(address)
        print(f"\nConnected with {addresses[-1][0]}")

def control():
    while True:
        control_command = input("Command: ")

        if control_command == "list":
            print("---Clients----")

            for client in range(len(clients)):
                print(str(client) + " " + str(addresses[client][0]) + " " + str(names[client]))

            print("---Clients----")

        elif control_command[0:7] == "connect":
            clientID = int(input("Client ID: "))

            conn = clients[clientID]
            ip = addresses[clientID]
            name = names[clientID]
            while True:
                #username.decode()) + "@" + str(addr[0])+ " :~# "
                command = input(name + "@" + str(ip[0]) + " :~# ")
                if command == "quit":
                    #Shut down the socket
                    conn.send("SHUTDOWN".encode())
                    conn.close()
                    conn = ""
                    del clients[clientID]
                    del addresses[clientID]
                    break
                check_command(conn=conn,command=command)
        else:
            print("Unkown command : Check your syntax please")

#listen forever and append new clients to clients' list
listener_thread = threading.Thread(target=listen)
listener_thread.start()

control()

"""#Listen
s = socket.socket()
#host = socket.gethostname()
host = "0.0.0.0"
port = 8080

s.bind((host, port))
print("[+] The listener has been started...")
print("[+] LHOST = ", host)
print("[+] LPORT = ", port)
print("[+] Waiting for incomming connections")
s.listen(1)
conn, addr = s.accept()

print("[+] ", addr, "has connected to the server successfully")
print("")

username = conn.recv(10000000)

name = str(str(username.decode()) + "@" + str(addr[0])+ " :~# ")

while True:
    command = str(input(name))
    check_command(conn,command)
"""


import os
import json
from S3utility.s3_notification_info import parse_activity_data
from provider.storage_provider import storage_context
from provider import digest_provider, download_helper
import provider.utils as utils
from activity.objects import Activity

"""
DepositDigestIngestAssets.py activity
"""

class activity_DepositDigestIngestAssets(Activity):
    def __init__(self, settings, logger, client=None, token=None, activity_task=None):
        super(activity_DepositDigestIngestAssets, self).__init__(
            settings, logger, client, token, activity_task
        )

        self.name = "DepositDigestIngestAssets"
        self.pretty_name = "Deposit Digest Ingest Assets"
        self.version = "1"
        self.default_task_heartbeat_timeout = 30
        self.default_task_schedule_to_close_timeout = 60 * 5
        self.default_task_schedule_to_start_timeout = 30
        self.default_task_start_to_close_timeout = 60 * 5
        self.description = "Deposit Assets for a Digest (Pre-Ingest)"

        # Track some values
        self.input_file = None
        self.digest = None
        self.dest_resource = None

        # Local directory settings
        self.directories = {
            "TEMP_DIR": os.path.join(self.get_tmp_dir(), "tmp_dir"),
            "INPUT_DIR": os.path.join(self.get_tmp_dir(), "input_dir"),
        }

        # Track the success of some steps
        self.build_status = None

    def do_activity(self, data=None):
        "do the work"
        if self.logger:
            self.logger.info("data: %s" % json.dumps(data, sort_keys=True, indent=4))

        # Create output directories
        self.make_activity_directories()

        # parse the data with the digest_provider
        real_filename, bucket_name, bucket_folder = parse_activity_data(data)
        # Download from S3
        self.input_file = download_helper.download_file_from_s3(
            self.settings,
            real_filename,
            bucket_name,
            bucket_folder,
            self.directories.get("INPUT_DIR"),
        )
        # Parse input and build digest
        digest_config = digest_provider.digest_config(
            self.settings.digest_config_section, self.settings.digest_config_file
        )
        self.build_status, self.digest = digest_provider.build_digest(
            self.input_file,
            self.directories.get("TEMP_DIR"),
            self.logger,
            digest_config,
        )

        if not self.build_status:
            self.logger.info(
                "Failed to build the Digest in Deposit Digest Ingest Assets for %s",
                real_filename,
            )
            return self.ACTIVITY_PERMANENT_FAILURE

        # check if there is an image and if not return True
        if not digest_provider.has_image(self.digest):
            self.logger.info(
                "Digest for file %s has no images to deposit", real_filename
            )
            return self.ACTIVITY_SUCCESS

        # bucket name
        cdn_bucket_name = (
            self.settings.publishing_buckets_prefix + self.settings.digest_cdn_bucket
        )

        # deposit the image file to S3
        self.deposit_digest_image(self.digest, cdn_bucket_name)

        return self.ACTIVITY_SUCCESS

    def image_dest_resource(self, digest, cdn_bucket_name):
        "concatenate the S3 bucket object path we copy the file to"
        msid = utils.msid_from_doi(digest.doi)
        article_id = utils.pad_msid(msid)
        # file name from the digest image file
        file_name = digest.image.file.split(os.sep)[-1]
        new_file_name = digest_provider.new_file_name(file_name, msid)
        storage_provider = self.settings.storage_provider + "://"
        dest_resource = (
            storage_provider + cdn_bucket_name + "/" + article_id + "/" + new_file_name
        )
        return dest_resource

    def deposit_digest_image(self, digest, cdn_bucket_name):
        "deposit the image file from the digest to the bucket"
        self.dest_resource = self.image_dest_resource(digest, cdn_bucket_name)
        storage = storage_context(self.settings)
        self.logger.info("Depositing digest image to S3 key %s", self.dest_resource)
        # set the bucket object resource from the local file
        metadata = {"ContentType": utils.content_type_from_file_name(digest.image.file)}
        storage.set_resource_from_filename(
            self.dest_resource, digest.image.file, metadata
        )
        self.logger.info("Deposited digest image %s to S3", digest.image.file)
        return True


"""
Typical rock, paper, scissor game
The computer vs user
Once user choose to quit the game, the score will be shown
"""
import random

user_wins = 0          #tracking scores by creating this two variables
computer_wins = 0

options = ["rock", "paper", "scissor"]
options[0]

while True:            #while loop
    user_input = input("Type Rock/Paper/Scissor or Q to quit: ").lower()
    if user_input == 'q':
        break

    if user_input not in ["rock", "paper", "scissor"]: #if user didn't key in either of these three input
        continue                                       #keep looping again at the while statement

    random_number =random.randint(0, 2)                #rock:0, paper:1, scissor: 2
    computer_pick = options[random_number]
    print("Computer picked", computer_pick + ".")

    if user_input == "rock" and computer_pick == "scissor":
        print("You won!")
        user_wins += 1
        continue

    elif user_input == "paper" and computer_pick == "rock":
        print("You won!")
        user_wins += 1
        continue

    elif user_input == "scissor" and computer_pick == "paper":
        print("You won!")
        user_wins += 1
        continue

    elif user_input == "rock" and computer_pick == "rock":
        print("Deuce!")
        continue

    elif user_input == "paper" and computer_pick == "paper":
        print("Deuce!")
        continue

    elif user_input == "scissor" and computer_pick == "scissor":
        print("Deuce!")
        continue

    else:
        print("You lose!")
        computer_wins += 1

print("You won", user_wins, "times.")
print("The computer won", computer_wins, "times.")
print("Goodbye")


#!/usr/bin/env python3
#
# An HTTP server that's a message board.
# PRG(Post-Redirect-Get) design pattern : HTTP application의 매우 자주 사용되는 패턴임
# 실행 순서
# 1. localhost:8000/ 접속하면 do_GET을 call => html form내용이 화면에 보여짐
#    ==> web browser에서 server를 call할 때 method의 default값은 GET 방식임
# 2. textarea에 데이터 입력하고 submit button누르면 do_POST가 불러지고,
#    textarea에서 입력된 데이터가 memory에 저장됨 => redirect (303)을 통해 다시 do_GET이 불리어짐
#    ==> redirect할 때 default method가 GET이기 때문에 do_GET call함
# 3. do_GET이 불려지면 textarea에서 입력되고 submit된 데이터 리스트가 보여짐

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs

memory = []

form = '''<!DOCTYPE html>
  <title>Message Board</title>
  <form method="POST">
    <textarea name="message"></textarea>

    <button type="submit">Post it!</button>
  </form>

{}

'''

class MessageHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # How long was the message?
        length = int(self.headers.get('Content-length', 0))

        # Read and parse the message
        data = self.rfile.read(length).decode()
        message = parse_qs(data)["message"][0]

        # Escape HTML tags in the message so users can't break world+dog.
        # '<' 를 &lt로 바꾸어 html을 인식하지 못하게 한다.
        message = message.replace("<", "<")

        # Store it in memory. memory 변수의 data type : list
        memory.append(message)

        # Send a 303 back to the root page
        # 303의 의미 : redirect via GET,
        # 1. server가 303을 인식하면, client인 web browser로 보내는 것이 아니라
        #    Location으로 지정된 server 주소로 다시 재전송됨
        # 2. redirect할 때는 response body에 데이터를 넣지 않음
        self.send_response(303)
        # Location이 '/'라는 의미는 root 주소를 말함, 즉 localhost:8000/을 말함
        self.send_header('Location', '/') # web brower에 데이터를 보내기 위해, Location을 '/'로 설정하고 실행한다.
        self.end_headers()
        # 다시 do_GET을 부르게 되어 있다.

    def do_GET(self):
        # First, send a 200 OK response.
        self.send_response(200)

        # Then send headers.
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()

        # Send the form with the messages in it.
        # format 메소드는 string instance안에 있는 것으로
        # form 문자열 안에 { } 자리에, "\n".join(memory)결과값이 들어감
        # "\n".join(memory)를 하기 때문에 memory에 합쳐서 들어간다.
        mesg = form.format("\n".join(memory))
        self.wfile.write(mesg.encode())

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MessageHandler)
    httpd.serve_forever()

Standard Web Library/1. Standard Web Library/5_MessageboardPartThree/MessageboardPartThree.py


import utils

def get_relaunch_hits(tasks, args):
    knowledge = utils.get_knowledge_file(args)
    round_num = utils.get_round(args)

    one_assignment_tasks, two_assignment_tasks = [], []
    for task in tasks:
        image_name = task['url']
        if image_name not in knowledge:
            two_assignment_tasks.append(task)
            continue

        task_knowledge = knowledge[image_name]['stage_'+str(args.stage)][task['task_name']]
        round_knowledge = task_knowledge['round_' + str(round_num)]
        has_w1, has_w2 = 'worker_1' in round_knowledge , 'worker_2' in round_knowledge
        if has_w1 and has_w2: continue

        if int(not has_w1) + int(not has_w2) == 1:
            one_assignment_tasks.append(task)
        else:
            two_assignment_tasks.append(task)

    assert len(one_assignment_tasks) + len(two_assignment_tasks) != 0, 'Stage 2 round %d initial launch done' % round_num

    one_assignment_hits = utils.get_hits_from_tasks(one_assignment_tasks, args)
    two_assignment_hits = utils.get_hits_from_tasks(two_assignment_tasks, args)

    hits = one_assignment_hits + two_assignment_hits
    assignments = [1 for _ in one_assignment_hits] + [2 for _ in two_assignment_hits]

    return hits, assignments

def prepare_launch(args):
    assert utils.stage_1_round_is_done(args), 'You must finish stage 2 round %d first' % utils.get_round(args)

    tasks = utils.get_stage_2_tasks(args)
    if utils.is_relaunch(args):
        hits, assignments = get_relaunch_hits(tasks, args)
    else:
        hits = utils.get_hits_from_tasks(tasks, args)
        assignments = [2 for _ in hits]

    rewards = [utils.get_reward(args) for _ in hits]
    return hits, rewards, assignments


from flask import Flask, jsonify, render_template, request
import numpy as np
import pandas as pd
import sklearn as sk
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.model_selection import train_test_split

app = Flask(__name__)

model = pickle.load(open('model_mnb.pkl','rb'))

@app.route('/', methods=['GET','POST'])
def root():
    return render_template('index.html')

@app.route('/predict', methods=['GET','POST'])
def predict():
    dataset = pd.read_csv('deceptive-opinion.csv')
    required_dataset = dataset[['verdict', 'review']]
    required_dataset.loc[required_dataset['verdict'] == 'deceptive', 'verdict'] = 0
    required_dataset.loc[required_dataset['verdict'] == 'truthful', 'verdict'] = 1
    X = required_dataset['review']
    Y = np.asarray(required_dataset['verdict'], dtype = int)
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 42) # 75% training and 25% test
    cv = CountVectorizer()
    x = cv.fit_transform(X_train)
    y = cv.transform(X_test)

    message = request.form.get('enteredinfo')
    data = [message]

    vect = cv.transform(data).toarray()
    prediction = model.predict(vect)

    return render_template('result.html', prediction_text = prediction)

@app.route('/tryagain')
def tryagain():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)


# -*- coding: utf-8 -*-

import logging
from datetime import date
from os import path

import xlsxwriter

from envios import Envio
from helpers import add_util_days, mailer, to_money
from pagamentos import Pagamento
from plataformas import PlataformaABC

logger = logging.getLogger(__name__)
CWD = path.dirname(path.abspath(__file__))
TMP = path.join(CWD, "..", "tmp")

class PedidosPagos:
    def __init__(self, plataforma: PlataformaABC, datas: list[date], email_to: list):
        self.plataforma = plataforma
        self.datas = datas
        self.email_to = email_to

    def run(self):
        logger.info(f"buscando atualizacoes entre {self.datas[0]} e {self.datas[-1]}")
        atualizacoes = self.plataforma.lista_atualizacoes_por_datas(self.datas)
        logger.info("atualizacoes obtidas com sucesso")

        pedidos_detalhados = []
        pedidos_itens = []

        for data in self.datas:
            logger.info(f"executando para a data {data}")
            atualizacoes_pedidos_pagos = atualizacoes.get(str(data), {}).get(
                "pedido_pago", []
            )

            pedidos = self.get_pedidos(atualizacoes_pedidos_pagos, data)
            pedidos_detalhados += pedidos["detalhado"]
            pedidos_itens += pedidos["itens"]

        if pedidos_detalhados:
            detalhado_xlsx_path = self.to_excel(
                pedidos_detalhados, path.join(TMP, "pedidosDetalhados.xlsx")
            )
            itens_xlsx_path = self.to_excel(
                pedidos_itens, path.join(TMP, "pedidosItens.xlsx")
            )
            self.send_mail(detalhado_xlsx_path, itens_xlsx_path)

    def get_pedidos(self, atualizacoes_pedidos_pagos, data: date):
        logger.info(f"{len(atualizacoes_pedidos_pagos)} pedidos pagos")
        pedidos_detalhados = []
        pedidos_itens = []
        total = 0

        for atualizacao in sorted(
            atualizacoes_pedidos_pagos, key=lambda at: at["numero"]
        ):
            pedido = self.plataforma.get_pedido_info(atualizacao["numero"])
            total += float(pedido["valor_total"])
            pedido["data_leitura"] = data
            pedido["detalhe_pagamento"] = Pagamento.consulta_detalhe_transacao(
                pagamento=pedido["pagamentos"][0], data=data
            )
            logger.debug(
                f"Pedido {pedido['numero']} => {to_money(pedido['valor_total'])}"
            )

            pedidos_detalhados.append(self.pedido_detalhado_mapper(pedido))
            pedidos_itens.append(self.pedido_itens_mapper(pedido))

        logger.info(f"Total {to_money(total)}")
        return {"detalhado": pedidos_detalhados, "itens": pedidos_itens}

    def pedido_itens_mapper(self, pedido):
        cliente = pedido["cliente"]
        itens = pedido["itens"]
        disponibilidade = max(
            map(lambda item: int(item["disponibilidade"]), pedido["itens"])
        )

        return {
            "Data": pedido["data_leitura"].strftime("%d/%m/%Y"),
            "Cliente": cliente["nome"],
            "Pedido": pedido["numero"],
            "Prazo de Envio": add_util_days(
                pedido["data_leitura"], disponibilidade
            ).strftime("%d/%m/%Y"),
            "Itens": [
                {
                    "SKU": it["sku"],
                    "Itens": it["nome"],
                    "QTD": float(it["quantidade"]),
                    "Fornecedor": "",
                    "Custo Real": "",
                    "Custo Site": to_money(
                        float(it["quantidade"]) * float(it["preco_custo"] or "0")
                    ),
                    "Preço Vendido": to_money(
                        float(it["quantidade"]) * float(it["preco_venda"])
                    ),
                }
                for it in itens
            ],
        }

    def pedido_detalhado_mapper(self, pedido):
        cliente = pedido["cliente"]
        envio = pedido["envios"][0]
        pagamento = pedido["pagamentos"][0]
        detalhe_pagamento = pedido["detalhe_pagamento"]

        disponibilidade = max(
            map(lambda item: int(item["disponibilidade"]), pedido["itens"])
        )

        rastreio = envio["objeto"]
        data_envio = ""
        if rastreio:
            track_json = Envio.track(rastreio)
            data_envio = (
                track_json.get("objeto", [{}])[0]
                .get("evento", [{}])[0]
                .get("dataPostagem", "")
            )

        cupom = ""
        if pedido["cupom_desconto"] is not None:
            cupom = pedido["cupom_desconto"].get("codigo", "")

        cep = pedido["endereco_entrega"]["cep"]
        if cep:
            cep = f"{cep[:5]}-{cep[5:]}"

        total_liquido = detalhe_pagamento.get("total_liquido", "")

        return {
            "Data": pedido["data_leitura"].strftime("%d/%m/%Y"),
            "Cliente": cliente["nome"],
            "Pedido": pedido["numero"],
            "Liberação do Pagamento": detalhe_pagamento.get("liberacao_pagamento", ""),
            "Pagamento": (
                f"{pagamento['forma_pagamento']['codigo']} - "
                f"{pagamento['forma_pagamento']['nome']}"
            ),
            "Código": pagamento["transacao_id"],
            "Parcelas": pagamento["parcelamento"].get("numero_parcelas", 0),
            "Cupom": cupom,
            "Data Envio": data_envio,
            "Prazo de Envio": add_util_days(
                pedido["data_leitura"], disponibilidade
            ).strftime("%d/%m/%Y"),
            "Rastreio": rastreio,
            "Frete Real": "",
            "Frete": to_money(pedido["valor_envio"]),
            "Prazo de Frete": int(envio.get("prazo") or disponibilidade)
            - disponibilidade,
            "Envio": f"{envio['forma_envio']['nome']} - {envio['forma_envio']['tipo']}",
            "CEP": cep,
            "Estado": pedido["endereco_entrega"]["estado"],
            "Subtotal": to_money(pedido["valor_subtotal"]),
            "Desconto": to_money(pedido["valor_desconto"]),
            "Total": to_money(pedido["valor_total"]),
            "Taxas": to_money(detalhe_pagamento.get("taxas", "")),
            "Total Líquido": to_money(total_liquido),
            "Situação": pedido["situacao"]["nome"],
        }

    def send_mail(self, detalhado_file_path: str, itens_file_path: str):
        logger.info("Enviando email")
        if not self.email_to:
            logger.error("Email não enviado")
            return

        br_date_i = self.datas[0].strftime("%d/%m/%Y")
        br_date_f = self.datas[-1].strftime("%d/%m/%Y")

        subject = f"Dados do dia {br_date_i}"
        body = f"Bom dia \n\nsegue em anexo os pedidos pagos do dia {br_date_i}"
        files_to_send = [
            {"name": "Site Detalhado", "file": detalhado_file_path},
            {"name": "Pedidos Site", "file": itens_file_path},
        ]

        if self.datas[0] != self.datas[-1]:
            subject += f" ao dia {br_date_f}"
            body += f" ao dia {br_date_f}"

        mailer.send(
            email_to=self.email_to,
            subject=subject,
            body=body,
            files_to_send=files_to_send,
        )
        logger.info("Email enviado com sucesso!")

    def to_excel(self, pedidos, file_path):
        workbook = xlsxwriter.Workbook(file_path)
        worksheet = workbook.add_worksheet()
        row = 1

        self._write_excel_header(workbook, worksheet, pedidos)

        for pedido in pedidos:
            itens_length = len(pedido.get("Itens", [0]))
            self._write_excel_row(
                workbook, worksheet, row, row + itens_length - 1, pedido
            )
            row += itens_length

        workbook.close()
        return file_path

    def _write_excel_row(self, workbook, worksheet, first_row, last_row, row_data):
        col = -1
        body_format = workbook.add_format(
            {
                "font_name": "Arial",
                "font_size": 9,
                "align": "center",
                "valign": "vcenter",
            }
        )

        for _, value in row_data.items():
            col += 1
            if type(value) == list:
                for i, list_item in enumerate(value):
                    sub_col = col - 1
                    for item in list_item.values():
                        sub_col += 1
                        worksheet.write(first_row + i, sub_col, item, body_format)
                col = sub_col
            else:
                if first_row == last_row:
                    worksheet.write(first_row, col, value, body_format)
                else:
                    worksheet.merge_range(
                        first_row, col, last_row, col, value, body_format
                    )

    def _write_excel_header(self, workbook, worksheet, row_data):
        header_format = workbook.add_format(
            {
                "bold": True,
                "font_name": "Arial",
                "font_size": 9,
                "bg_color": "#b7e1cd",
                "align": "center",
                "valign": "vcenter",
            }
        )

        row = 0
        headers = []
        for k, v in row_data[0].items():
            headers += v[0].keys() if type(v) == list else [k]

        for i, header in enumerate(headers):
            worksheet.write(row, i, header, header_format)


from tkinter import *
import os
import platform

import threading

from tkinter import messagebox

from rocketrecorder.open_folder import open_the_folder

if platform.system() == "Linux":
    from rocketrecorder.linux_screen_recorder import (
        record,
        stop_video_recording,
    )
else:
    from rocketrecorder.windows_screen_recorder import (
        record,
        stop_video_recording,
    )
from rocketrecorder.screenshot import make_screenshot

class RocketRecorder:
    def __init__(self):
        """
        Initialize the RocketRecorder application.
        """
        self.root = Tk()
        self.root.geometry("1200x600")
        self.root.title("rocket recorder")
        self.root.config(bg="#F8F8FF")
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.resizable(False, False)

        from . import IMG_DIR

        self.img = PhotoImage(file=os.path.join(IMG_DIR, "photo", "space.png"))
        self.bg = PhotoImage(
            file=os.path.join(IMG_DIR, "for_new_window", "wininfo.png")
        )
        self.start_btn_image = PhotoImage(
            file=os.path.join(IMG_DIR, "buttons", "start.png")
        )
        self.stop_btn_image = PhotoImage(
            file=os.path.join(IMG_DIR, "buttons", "stop.png")
        )
        self.folder_btn_image = PhotoImage(
            file=os.path.join(IMG_DIR, "buttons", "folder.png")
        )
        self.tip_btn_image = PhotoImage(
            file=os.path.join(IMG_DIR, "buttons", "tip.png")
        )
        self.scr_btn_image = PhotoImage(
            file=os.path.join(IMG_DIR, "buttons", "screen1.png")
        )

        self.app_label = Label(
            self.root,
            text="Rocket recorder",
            image=self.img,
            bg="#A9A9A9",
            font=("rockwell", 26, "bold"),
            padx=500,
            pady=32,
        )
        self.app_label.grid(columnspan=3)

        self.create_buttons()

    def create_buttons(self):
        """
        Create the buttons in the application.
        """
        record_btn = Button(
            self.root,
            command=self.start_recording,
            image=self.start_btn_image,
            bg="#F8F8FF",
            activebackground="#F8F8FF",
            bd=0,
        )
        record_btn.grid(row=5, column=0, pady=100)

        stop_btn = Button(
            self.root,
            command=self.stop_recording,
            image=self.stop_btn_image,
            bg="#F8F8FF",
            activebackground="#F8F8FF",
            bd=0,
        )
        stop_btn.grid(row=5, column=1, pady=3)

        folder_btn = Button(
            self.root,
            command=self.open_folder,
            image=self.folder_btn_image,
            bg="#F8F8FF",
            activebackground="#F8F8FF",
            bd=0,
        )
        folder_btn.grid(row=5, column=2, pady=3)

        tip_btn = Button(
            self.root,
            command=self.start_window,
            image=self.tip_btn_image,
            bg="#A9A9A9",
            bd=2,
        )
        tip_btn.place(x=1148, y=20)

        scr_btn = Button(
            self.root,
            command=make_screenshot,
            image=self.scr_btn_image,
            bg="#A9A9A9",
            bd=2,
        )
        scr_btn.place(x=50, y=60)

    def start_window(self):
        """
        Open the "Tips" window.
        """
        new_window = Toplevel(self.root)
        new_window.geometry("400x300")
        new_window.title("Tips")
        if platform.system() == "Windows":
            new_window.iconbitmap("rocketrecorder/for_new_window/icoo.ico")
        new_window.resizable(False, False)
        new_window.wm_attributes("-topmost", 1)
        label2 = Label(new_window, image=self.bg)
        label2.place(x=0, y=0)

    @staticmethod
    def start_recording():
        """
        Start the screen recording based on the platform.
        """

        threading.Thread(target=record).start()

    @staticmethod
    def stop_recording():
        """
        Stop the screen recording.
        """
        # if platform.system() == "Linux":
        #     subprocess.run(["pkill", "ffmpeg"])
        # else:
        #     stop_video_recording()
        #     free_resources()

        stop_video_recording()

    @staticmethod
    def make_screenshot():
        """
        Capture a screenshot of the screen.
        """
        make_screenshot()

    @staticmethod
    def open_folder():
        """
        Open the folder containing the recorded videos.
        """
        open_the_folder()

    def on_closing(self):
        """
        Handle the closing of the application window.
        """
        if messagebox.askokcancel(
            "Exit", "Do You want to exit the App?\n Data may be corrupted"
        ):
            self.root.destroy()

    def run(self):
        """
        Run the RocketRecorder application.
        """
        self.root.mainloop()

if __name__ == "__main__":
    app = RocketRecorder()
    app.run()


import websockets
import socket
import asyncio
import time
import glabalVal as g

temperature = "25"
humidity = "44"

def recUdp():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 创建套接字，ipv4，UDP类型
    local_addr = ("", 62436)  # 设置本地的端口，一般不写ip地址
    udp_socket.bind(local_addr)  # 绑定套接字，不绑定端口号系统会随机分配

    recv_data = udp_socket.recvfrom(4096)  # 1024表示接收的最大的字节数，可以随意更改
    result_recv_data = recv_data[0].hex()  # 接收的数据类型为Hex

    str = result_recv_data
    # 3.关闭套接字
    udp_socket.close()
    return str

if __name__ == '__main__':
    while True:
        info = recUdp()
        print(info)
        g.set_temeperature(info[0:4])
        g.set_humidity(info[4:16])
        print(g.get_temperature())
        print(g.get_humidity())
        time.sleep(2)


#mengimport library yang digunakan
from keras.models import load_model
from PIL import Image
from matplotlib import pyplot as plt
import numpy as np

#Membaca gambar menggunakan library PIL, pembaca juga
#dapat menggunakan library lain, seperti OpenCV
gambar1= Image.open("dataset/mnist/testing/0/img_108.jpg")
gambar2= Image.open("dataset/mnist/testing/1/img_0.jpg")
#mengubah ke ndarray numpy
gambar1 = np.asarray(gambar1)
gambar2 = np.asarray(gambar2)

#memanggil model yang telah ditraining sebelumnya
model = load_model('./modelLeNet5.h5')

#memprediksi gambar dg modelnya
#ingat, intensitas perlu dibagi 255 karena saat training jg dibagi 255
#kemudian format input harus (batch size,tinggi gambar, lebar, depth)
#oleh karena itu, kita gunakan reshape seperti di bawah
pred1 = model.predict_classes((gambar1/255).reshape((1,28,28,1)))
pred2 = model.predict_classes((gambar2/255).reshape((1,28,28,1)))

#mengeplot gambar beserta hasil prediksi
plt.figure('gambar1')
plt.imshow(gambar1,cmap='gray')
plt.title('pred:'+str(pred1[0]), fontsize=22)
print("prediksi gambar1:", pred1[0])

plt.figure('gambar2')
plt.imshow(gambar2,cmap='gray')
plt.title('pred:'+str(pred2[0]), fontsize=22)
print("prediksi gambar2:", pred2[0])

plt.show()

edisi2/10.5.2 Menggunakan Model yang telah ditraining.py


def f(fun, x):
    y = eval(fun)
    return y

def newton():
    fun = input("ingresa tu función")
    dfun = input("ingresa la derivada de tu función")
    x0 = float(input("ingresa el valor inicial"))
    tol = float(input("ingrese la tolerancia deseada"))
    iteraciones = int(input("ingrese el número máximo de iteraciones"))

    fx = f(fun, x0)
    dfx = f(dfun, x0)

    i = 1

    error = tol + 1

    while (error > tol and fx != 0 and dfx != 0 and i <= iteraciones):
        x1 = x0 - (fx/dfx)
        fx = f(fun, x1)
        dfx = f(dfun, x1)
        error = abs(x1-x0)
        x0 = x1

    if fx == 0:
        print(x0, " es una raíz")
    elif error < tol:
        print("no se encontró una raíz con la tolerancia indicada")
    elif dfx == 0:
        print(x0, " es una posible raíz múltiple")
    else:
        print(x0, " es una raíz con un error de ", error, " en ", iteraciones, " iteraciones")

    newton()


import numpy as np
import seaborn as sn
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
from matplotlib import pyplot
import pandas as pd
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

import data_operations
import constants

def naive_bayes(data, classes, split=70):

    train_s, train_s_class, test_s, test_s_class = data_operations.split_sets(
        data, classes, split)
    gnb = GaussianNB()
    gnb.fit(train_s, train_s_class.values.ravel())
    pred = gnb.predict(test_s)

    return metrics.accuracy_score(test_s_class, pred)

def select_features(dataframe, n_feature):

    pixels_features = []

    for n in range(10):
        df_is_class_n = pd.read_csv('../data/y_train_smpl_'+str(n)+'.csv')

        transformer = SelectKBest(score_func=chi2, k = 1)

        #new_data = transformer.fit_transform(df_pixels.values, df_is_class0)
        fit = transformer.fit(dataframe, df_is_class_n)
        scores = pd.DataFrame(fit.scores_)
        columns = pd.DataFrame(dataframe.columns)
        # concat 2 dataframes for better visualization
        featuresScore = pd.concat([columns, scores], axis=1)
        featuresScore.columns = ['Pixel', 'Score']
        pixels_features.append(
            featuresScore.nlargest(n_feature, 'Score')['Pixel'].values)

    #count ranges
    df_classes = data_operations.load_dataframe(constants.ORIGINAL_CLASSES)
    ranges = []
    start_indx = 0
    last_indx = 0
    for n in range(10):
        count = len(np.argwhere(df_classes.values.ravel() == n))
        last_indx = last_indx + count
        ranges.append((start_indx, last_indx))
        start_indx = last_indx + 1
    #empty dataframe
    df_pixels_feature = pd.DataFrame(0, index=np.arange(len(dataframe)), columns=dataframe.columns)
    indx = 0
    for features in pixels_features:
        df_pixels_feature.loc[ranges[indx][0]: ranges[indx][1],features] = dataframe.loc[ranges[indx][0]: ranges[indx][1], features]
        indx = indx + 1
    return df_pixels_feature

if __name__ == '__main__':
    sliced = data_operations.load_dataframe(constants.NORMALIZED_SLICED_SMPL)
    classes = data_operations.load_dataframe(constants.ORIGINAL_CLASSES)
    classes = data_operations.randomize_data(classes, constants.SEED)
    max_accuracy = 0.0
    current_accuracy = 0.0
    accuracy_list = []
    feat = 1
    for n in range(len(sliced.columns)):
        features_dataframe = select_features(sliced,feat)
        features_dataframe = data_operations.randomize_data(features_dataframe, constants.SEED)
        current_accuracy = naive_bayes(features_dataframe, classes)
        accuracy_list.append(current_accuracy)
        if max_accuracy < current_accuracy:
            max_accuracy = current_accuracy
        feat +=1

    pyplot.plot(range(len(accuracy_list)),accuracy_list)
    pyplot.title('Accuracy vs n Features')
    pyplot.xlabel('No of features')
    pyplot.ylabel('Accuracy')
    pyplot.show()