from ..math_basics import is_RealIntervalFieldElement # type: ignore
from ..exceptions import InsufficientPrecisionError # type: ignore

from typing import Sequence

__all__ = ['floor_as_intergers', 'SpatialDict']

def floor_as_integers(x) -> Sequence[int]:
    """
    Computes floor of a number or interval, returning a list of integers
    if evaluating floor is ambiguous.

        sage: floor_as_integers(RIF(1.8, 1.9))
        [1]
        sage: floor_as_integers(RIF(1.9, 2.1))
        [1, 2]

        >>> floor_as_integers(1.4)
        [1]
        >>> floor_as_integers(2.01)
        [1, 2]
        >>> floor_as_integers(1.99)
        [1, 2]

    """

    if is_RealIntervalFieldElement(x):
        f = x.floor()
        l = f.lower().round()
        u = f.upper().round() + 1

        n = u - l
        if n > 5:
            raise InsufficientPrecisionError(
                "Too many integers (%d) in given interval to compute floor. "
                "Increasing precision should fix it." % n)

        return list(range(l, u))
    else:
        f = x.floor()
        int_f = int(f)
        d = x - f
        if d < 0.125:
            return [ int_f - 1, int_f ]
        if d > 0.875:
            return [ int_f, int_f + 1 ]
        return [ int_f ]

class _Entry:
    """
    A helper for SpatialDict.

    The implementation of SpatialDict has the same instance of _Entry
    stored for multiple keys so that updating the value for all keys
    can be done by assigning the new value to _Entry.value only once.
    """
    def __init__(self, value):
        self.value = value

class SpatialDict:
    """
    A python dict-like object appropriate for using numerical points (e.g.,
    in the hyperboloid model) as keys. That is, look-ups return
    the same entry for points that are almost but not exactly the
    same due to rounding-errors.

    To achieve this, the points are asumed to be in some lattice
    and the minimal distance between any two points in the lattice
    must be given.
    """

    _scale = 1024

    def __init__(self, min_distance, verified):
        RF = min_distance.parent()

        self._min_distance = min_distance
        self._RF_scale = RF(self._scale)

        if verified:
            self._right_distance_value = min_distance
            self._left_distance_value = 0
        else:
            self._right_distance_value = min_distance * RF(0.125)
            self._left_distance_value = min_distance * RF(0.5)

        self._data = { }

    def setdefault(self, point, default):
        reps_and_ikeys = self._representatives_and_ikeys(point)

        for rep, ikey in reps_and_ikeys:
            for other_rep, entry in self._data.get(ikey, []):
                d = self.distance(rep, other_rep)
                if d < self._right_distance_value:
                    return entry.value
                if not (self._left_distance_value < d):
                    raise InsufficientPrecisionError(
                        "Could neither verify that the two given tiles are "
                        "the same nor that they are distinct. "
                        "Distance between basepoint translates is: %r. "
                        "Injectivty diameter about basepoint is: %r." % (
                            d, self._min_distance))

        entry = _Entry(default)
        for rep, ikey in reps_and_ikeys:
            self._data.setdefault(ikey, []).append((rep, entry))

        return default

    def distance(self, point_0, point_1):
        raise NotImplementedError()

    def representatives(self, point):
        # Applies, e.g., translation by geodesic matrix
        return [ point ]

    def float_hash(self, point):
        raise NotImplementedError()

    def _representatives_and_ikeys(self, point):
        return [
            (rep, ikey)
            for rep in self.representatives(point)
            for ikey in floor_as_integers(self._RF_scale * self.float_hash(rep)) ]


from typing import Dict, Optional, Tuple, TYPE_CHECKING

from UM.Logger import Logger
from UM.Version import Version
from cura.Backups.Backup import Backup

if TYPE_CHECKING:
    from cura.CuraApplication import CuraApplication

class BackupsManager:
    """
    The BackupsManager is responsible for managing the creating and restoring of
    back-ups.

    Back-ups themselves are represented in a different class.
    """

    def __init__(self, application: "CuraApplication") -> None:
        self._application = application

    def createBackup(self) -> Tuple[Optional[bytes], Optional[Dict[str, str]]]:
        """
        Get a back-up of the current configuration.

        :return: A tuple containing a ZipFile (the actual back-up) and a dict containing some metadata (like version).
        """

        self._disableAutoSave()
        backup = Backup(self._application)
        backup.makeFromCurrent()
        self._enableAutoSave()
        # We don't return a Backup here because we want plugins only to interact with our API and not full objects.
        return backup.zip_file, backup.meta_data

    def restoreBackup(self, zip_file: bytes, meta_data: Dict[str, str]) -> None:
        """
        Restore a back-up from a given ZipFile.

        :param zip_file: A bytes object containing the actual back-up.
        :param meta_data: A dict containing some metadata that is needed to restore the back-up correctly.
        """

        if not meta_data.get("cura_release", None):
            # If there is no "cura_release" specified in the meta data, we don't execute a backup restore.
            Logger.log("w", "Tried to restore a backup without specifying a Cura version number.")
            return

        self._disableAutoSave()

        backup = Backup(self._application, zip_file = zip_file, meta_data = meta_data)
        restored = backup.restore()

        if restored:
            # At this point, Cura will need to restart for the changes to take effect.
            # We don't want to store the data at this point as that would override the just-restored backup.
            self._application.windowClosed(save_data = False)

    def _disableAutoSave(self) -> None:
        """Here we (try to) disable the saving as it might interfere with restoring a back-up."""

        self._application.enableSave(False)
        auto_save = self._application.getAutoSave()
        # The auto save is only not created if the application has not yet started.
        if auto_save:
            auto_save.setEnabled(False)
        else:
            Logger.log("e", "Unable to disable the autosave as application init has not been completed")

    def _enableAutoSave(self) -> None:
        """Re-enable auto-save and other saving after we're done."""

        self._application.enableSave(True)
        auto_save = self._application.getAutoSave()
        # The auto save is only not created if the application has not yet started.
        if auto_save:
            auto_save.setEnabled(True)
        else:
            Logger.log("e", "Unable to enable the autosave as application init has not been completed")


from parakeet.testing_helpers import expect, run_local_tests

def sum_primes(n):
  total = 0
  count = 0
  for i in xrange(2, n):
    found_divisor = False
    for j in xrange(2,i-1):
      if i % j == 0:
        found_divisor = True
    if not found_divisor:
      total += i
      count += 1
  return total, count

def test_sum_primes():
  expect(sum_primes, [20], sum_primes(20))

if __name__ == '__main__':
  run_local_tests()


from thirtythree.decompositions import weak_decompose, Node
from collections import namedtuple
from operator import mul

'''
This constitutes a search through 3-space for a coordinate satisfying

x^3 + y^3 + z^3 = 33

Immediately we know there are no all positive or negative solutions, by brute force and a smidge of sense. This removes a fourth of the search space. There is no 2-dimensional solution, but the optimization advantage of this is vanishingly small as you traverse 3-space.

Then we are interested in a solution such that one or two of these indices are negative.

Further, we can restrict our search (without complicating traversal code) by eliminating all solutions such that the combination of the modulus of their cubes results in 0 mod 33:

32^3 = 32678
1^3 = 1
0^3 = 0

The third argument to pow is actually the modulus.
pow(32768 + 1 - 0, 1, 33) => 0

One thing to note here is that 32^3 mod 33 := 32 mod 33, this does not hold generally:
expt(7, 3, 33) => 13

But it is a surjective function from the least residue system (or any complete residue system) of 33 to the least residue system (denoted LRS) of 33, and if we restrict our input to the LRS, then it is a bijection between the LRS to itself! This again does not hold generally.

We are going to capture all the permutations in our enumeration function. Then we are free to assume any offset is permuted, and can eliminate restrictions this way.

Further we will generate the offsets for a sign and negate them, the arguments are the same either way.
'''  # noqa: E501

K = 33

def zip_offsets(unsigned_offset, signs):
    return tuple(off * sign for off, sign in zip(unsigned_offset, signs))

CASE_ONE_UNSIGNED = []
for i in reversed(range(K)):
    for decomp in weak_decompose(i, 2):
        CASE_ONE_UNSIGNED.append((i, *decomp))

# case: (+, -, -)
CASE_ONE_SIGNAGE = (1, -1, -1)
CASE_ONE = tuple(
    zip_offsets(unsigned, CASE_ONE_SIGNAGE)
    for unsigned in CASE_ONE_UNSIGNED)

# negative case: (-, +, +)
CASE_ONE_NEG_SIGNAGE = (-1, 1, 1)
CASE_ONE_NEG = tuple(
    zip_offsets(unsigned, CASE_ONE_NEG_SIGNAGE)
    for unsigned in CASE_ONE_UNSIGNED)

CASE_TWO_UNSIGNED = []
for i in reversed(range(K)):
    CASE_TWO_UNSIGNED.append((i, i, 0))

# case: (+, -, +)
CASE_TWO_SIGNAGE = (1, -1, 1)
CASE_TWO = tuple(
    zip_offsets(unsigned, CASE_TWO_SIGNAGE)
    for unsigned in CASE_TWO_UNSIGNED)

# case: (-, +, -)
CASE_TWO_NEG_SIGNAGE = (-1, 1, -1)
CASE_TWO_NEG = tuple(
    zip_offsets(unsigned, CASE_TWO_NEG_SIGNAGE)
    for unsigned in CASE_TWO_UNSIGNED)

# case three is the most complicated.
# I believe the solution is to filter everything less than i, and
# subtract i from the elements of the decomposition. but I haven't
# worked it out on paper quite yet.
CASE_THREE_UNSIGNED = []
for i in range(65, 32, -1):
    for decomp in weak_decompose(i, 2):
        pass

# case: (+, +, -)
CASE_THREE_SIGNAGE = (1, 1, -1)
CASE_THREE = tuple(
    zip_offsets(unsigned, CASE_THREE_SIGNAGE)
    for unsigned in CASE_THREE_UNSIGNED)


# search.py
# ---------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""

import util

class SearchProblem:
    """
    This class outlines the structure of a search problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the search problem.
        """
        util.raiseNotDefined()

    def isGoalState(self, state):
        """
          state: Search state

        Returns True if and only if the state is a valid goal state.
        """
        util.raiseNotDefined()

    def getSuccessors(self, state):
        """
          state: Search state

        For a given state, this should return a list of triples, (successor,
        action, stepCost), where 'successor' is a successor to the current
        state, 'action' is the action required to get there, and 'stepCost' is
        the incremental cost of expanding to that successor.
        """
        util.raiseNotDefined()

    def getCostOfActions(self, actions):
        """
         actions: A list of actions to take

        This method returns the total cost of a particular sequence of actions.
        The sequence must be composed of legal moves.
        """
        util.raiseNotDefined()

def tinyMazeSearch(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other maze, the
    sequence of moves will be incorrect, so only use this for tinyMaze.
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return [s, s, w, s, w, w, s, w]

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print("Start:", problem.getStartState())
    print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
    print("Start's successors:", problem.getSuccessors(problem.getStartState()))
    """
    "*** YOUR CODE HERE ***"
    frontier = util.Stack()  # Initialize the stack.
    closed = set()  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state into the stack.
    return execute_common_search_logic(frontier, closed, problem)

def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    frontier = util.Queue()  # Initialize the Queue.
    closed = set()  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state and empty list of actions into the queue.
    return execute_common_search_logic(frontier, closed, problem)

def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    def priority_func(path):
        return problem.getCostOfActions(path[1])

    frontier = util.PriorityQueueWithFunction(priority_func)  # Priority Queue with priority function based on
    # cost of path.
    closed = set()  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state into the Priority Queue.
    return execute_common_search_logic(frontier, closed, problem)

def nullHeuristic(state, problem=None):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem.  This heuristic is trivial.
    """
    return 0

def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    def priority_func(path):
        act_cost_gn = problem.getCostOfActions(path[1])
        est_cost_fn = heuristic(path[0], problem)
        return act_cost_gn + est_cost_fn

    frontier = util.PriorityQueueWithFunction(priority_func)  # Priority Queue with priority function based on
    # cost of path.
    closed = set()  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state into the Priority Queue.
    return execute_common_search_logic(frontier, closed, problem)

def execute_common_search_logic(frontier, closed, problem):
    while not frontier.isEmpty():
        current_node, current_action = frontier.pop()  # remove out the node(start) and actions taken by the
        # agent(n,e,w,s)
        if problem.isGoalState(current_node):
            return current_action  # Anchor condition
        if current_node not in closed:
            closed.add(current_node)  # If node not visited, add in set.
            node_successors = problem.getSuccessors(current_node)  # Get the successors of the current Node.
            for current_child in node_successors:
                # For each child node, get it's child nodes and action to get there.
                current_successor, action, _ = current_child
                # Pushing successor along with the action required to reach that successor
                frontier.push((current_successor, current_action + [action]))
    return []

# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch


# Face Recognition/Identification
import cv2 as cv
import face_recognition as fr
import os

# training data
knownFaces = [
    {
        "file": "JoeBiden.jpg",
        "name": "Joe Biden",
        "code": None,
    },
    {
        "file": "FumioKishida.jpg",
        "name": "Fumio Kishida",
        "code": None,
    },
    {
        "file": "XiJinPing.jpg",
        "name": "Xi Dada",
        "code": None,
    },
    {
        "file": "JustinTrudeau.jpg",
        "name": "Justin Trudeau",
        "code": None,
    },
]

# return the encoding of the face detected in the image file
def train(face):
    # img is using "RGB" color
    img = fr.load_image_file("face-images/known/" + face["file"])
    faceLocations = fr.face_locations(img)
    faceCodes = fr.face_encodings(img, faceLocations)

    if len(faceLocations) > 0:
        top, right, bottom, left = faceLocations[0]
        frame = cv.cvtColor(img, cv.COLOR_RGB2BGR)
        cv.rectangle(frame, (left, top), (right, bottom), (255,0,0), 2)
    cv.imshow(face['name'],frame)

    if len(faceCodes) > 0:
        return faceCodes[0]
    else:
        return None

def recognize(filePath):
    img = fr.load_image_file(filePath)
    frame = cv.cvtColor(img, cv.COLOR_RGB2BGR)

    locations = fr.face_locations(img)
    codes = fr.face_encodings(img, locations)

    knownCodes = [face['code'] for face in knownFaces]

    for loc, code in zip(locations, codes):
        top, right, bottom, left = loc
        # draw face border
        cv.rectangle(frame, (left,top), (right,bottom), (255,0,0), 2)

        # draw face name
        matches = fr.compare_faces(knownCodes, code, tolerance=0.5)
        name = "unknown"
        for i in range(len(matches)):
            if matches[i] == True:
                name = knownFaces[i]['name']
                break
        cv.putText(frame, name, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,255), 2)

    cv.imshow('face recog', frame)

# train by known faces
for face in knownFaces:
    face['code'] = train(face)
    #print(face)

# recognize unknow faces
recognize("face-images/unknown/u003.jpg")

cv.waitKey(0)


from tkinter import Tk, Label, Button, Entry, Text, messagebox
from os import environ
from source.email import Email
from dotenv import load_dotenv

#se crea la ventana
venatana = Tk()

#se pone el titulo, color y tamaño de la ventana
venatana.title("Semana 12")
venatana.geometry("500x400")
venatana.config(bg="#5F6A6A")

#se crean los parametros de los objetos de la ventana
share = Label(venatana, text="Correo: ", font=14, bg="#5F6A6A")
user = Label(venatana, text="Usuario: ", font=14, bg="#5F6A6A")

ce = Entry(venatana, font= 14, bg="white")
user2 = Entry(venatana, font= 14, bg="white")
message1= Text(venatana, font= 14, bg="white")

#Se cre la estructura para HTML
html = """
<!DOCYPE html>

Estimad@ {}

{}

"""

load_dotenv()
#Se cre la funcion para enviar el correo
def sendemail():
    correo = Email()
    correo.mandar_email([ce.get()], "Semana 12 Programacion", message_format=html.format(user2.get(), message1.get('1.0', 'end-1c')), format="html")
    messagebox.showinfo("Aviso", "El correo se ha enviado de manera sastifactoria.")

#se cre el bonton de envio
btnshare = Button(venatana, text="Enviar", command=sendemail, bg="#283747")

#se establecen los parametros de los objetos dentro de la ventana

share.place(x=50, y=10)
ce.place(x=150, y=10, width=290)
user.place(x=50, y=60)
user2.place(x=150, y=60, width=290)
message1.place(x=60, y=110, width=380, height=225)
btnshare.place(x=60, y=350, width=380, height=40)

venatana.mainloop()


from typing import Optional, List, Dict

from src.db_models import LabelGroup, LabelFormat, FieldScope, CalculatedField, Driver, DriverChange
from src.data_models import LabelFormatApi, LabelFormatApiList
from src.data_models import CalculatedFieldApi, CalculatedFieldApiList
from src.data_models import DriverApi, DriverApiList
from src.data_models import DriverChangeApi, DriverChangeApiList

from src import db

def get_calculated_fields(field_scope_code: str) -> CalculatedFieldApiList:
    field_scope: Optional[FieldScope] = FieldScope.query.filter_by(code=field_scope_code).first()
    if not field_scope:
        raise ValueError(f"invalid scope code: {field_scope_code}")

    fields = CalculatedField.query.filter_by(scope_id=field_scope.id).order_by(CalculatedField.order_key).all()
    wrapper = CalculatedFieldApiList(title=field_scope.title, items=[])
    for field in fields:
        wrapper.items.append(CalculatedFieldApi.from_orm(field))
    return wrapper

def save_calculated_fields(field_scope_code: str, req_data: CalculatedFieldApiList) -> int:
    from src import db

    field_scope: Optional[FieldScope] = FieldScope.query.filter_by(code=field_scope_code).first()

    if not field_scope:
        field_scope = FieldScope(code=field_scope_code, title=req_data.title)
        db.session.add(field_scope)
    else:
        field_scope.title = req_data.title
    db.session.commit()

    order_key = 1
    db_obj_list = []
    # transform to objects, add order key
    for item in req_data.items:
        db_obj = CalculatedField(**item.dict(), order_key=order_key, scope_id=field_scope.id)
        db_obj_list.append(db_obj)
        order_key += 1

    try:
        calculated_fields = CalculatedField.query.filter_by(scope_id=field_scope.id).all()
        # cleanup old records
        for cf in calculated_fields:
            db.session.delete(cf)
        db.session.commit()
        # write new records
        for obj in db_obj_list:
            db.session.add(obj)
        db.session.commit()
    except Exception as ex:
        db.session.rollback()
        raise ex
    return len(db_obj_list)

def get_calculated_fields_all() -> Dict[str, CalculatedFieldApiList]:
    field_scopes: List[FieldScope] = FieldScope.query.order_by(FieldScope.code).all()

    out = {}
    for field_scope in field_scopes:
        fields = get_calculated_fields(field_scope.code)
        out[field_scope.code] = fields
    return out

def save_calculated_fields_all(d: Dict[str, CalculatedFieldApiList]) -> int:
    res = 0
    for code, values in d.items():
        res += save_calculated_fields(code, values)
    return res

def get_label_formats(label_group_code: str) -> LabelFormatApiList:
    label_group: Optional[LabelGroup] = LabelGroup.query.filter_by(code=label_group_code).first()
    if not label_group:
        raise Exception(f"invalid label group: {label_group_code}")

    labels = LabelFormat.query.filter_by(group_id=label_group.id).order_by(LabelFormat.order_key).all()
    wrapper = LabelFormatApiList(title=label_group.title, items=[])
    for label in labels:
        wrapper.items.append(LabelFormatApi.from_orm(label))
    return wrapper

def save_label_formats(label_group_code: str, req_data: LabelFormatApiList) -> int:
    from src import db

    label_group: Optional[LabelGroup] = LabelGroup.query.filter_by(code=label_group_code).first()

    if not label_group:
        label_group = LabelGroup(code=label_group_code, title=req_data.title)
        db.session.add(label_group)
    else:
        label_group.title = req_data.title
    db.session.commit()

    order_key = 1
    db_obj_list = []
    # transform to objects, add order key
    for item in req_data.items:
        db_obj = LabelFormat(**item.dict(), order_key=order_key, group_id=label_group.id)
        db_obj_list.append(db_obj)
        order_key += 1

    try:
        label_formats = LabelFormat.query.filter_by(group_id=label_group.id).all()
        # cleanup old records
        for lf in label_formats:
            db.session.delete(lf)
        db.session.commit()
        # add new records
        for obj in db_obj_list:
            db.session.add(obj)
        db.session.commit()
    except Exception as ex:
        db.session.rollback()
        raise ex
    return len(db_obj_list)

def get_label_formats_all() -> Dict[str, LabelFormatApiList]:
    label_groups: List[LabelGroup] = LabelGroup.query.order_by(LabelGroup.code).all()
    out = {}
    for label_group in label_groups:
        formats = get_label_formats(label_group.code)
        out[label_group.code] = formats
    return out

def save_label_formats_all(d: Dict[str, LabelFormatApiList]):
    res = 0
    for code, values in d.items():
        res += save_label_formats(code, values)
    return res

def get_drivers() -> DriverApiList:
    from src.db_models import Driver
    db_drivers = Driver.query.order_by(Driver.name).all()
    wrapper = DriverApiList(__root__=[])
    for db_driver in db_drivers:
        wrapper.__root__.append(DriverApi.from_orm(db_driver))
    return wrapper

def save_drivers(req_data: DriverApiList) -> int:
    from src import db

    db_obj_list = []
    # transform to objects, add order key
    for item in req_data.__root__:
        db_obj = Driver(**item.dict())
        db_obj_list.append(db_obj)

    try:
        drivers = Driver.query.all()
        # cleanup old records
        for d in drivers:
            db.session.delete(d)
        db.session.commit()
        # add new records
        for obj in db_obj_list:
            db.session.add(obj)
        db.session.commit()
    except Exception as ex:
        db.session.rollback()
        raise ex
    return len(db_obj_list)

def get_driver_changes() -> DriverChangeApiList:
    from src.db_models import DriverChange
    db_driver_changes = DriverChange.query.order_by(DriverChange.valid_from).all()
    wrapper = DriverChangeApiList(__root__=[])
    for db_driver_change in db_driver_changes:
        wrapper.__root__.append(DriverChangeApi.from_orm(db_driver_change))
    return wrapper

def save_driver_changes(req_data: DriverChangeApiList) -> int:
    from src import db

    db_obj_list = []
    # transform to objects, add order key
    for item in req_data.__root__:
        db_obj = DriverChange(**item.dict())
        db_obj_list.append(db_obj)

    try:
        driver_changes = DriverChange.query.all()
        # cleanup old records
        for dch in driver_changes:
            db.session.delete(dch)
        # add new records
        for obj in db_obj_list:
            db.session.add(obj)
        db.session.commit()
    except Exception as ex:
        db.session.rollback()
        raise ex
    return len(db_obj_list)


from collections import deque
from sys import stdin

def bfs(x,n,visited,graph):

    queue = deque([x])

    visited[x] = 1

    while queue:

        x = queue.popleft()

        for v in graph[x]:

            if visited[v] == 0:

                visited[v] = 1
                queue.append(v)

    return True

n,m = map(int,stdin.readline().split())

graph = [[] for _ in range(n+1)]

for _ in range(m):

    u,v = map(int,stdin.readline().split())

    graph[u].append(v)
    graph[v].append(u)

visited = [0]*(n+1)

count = 0

for i in range(1,n+1):

    if visited[i] == 0:

        count += bfs(i,n,visited,graph)

print(count)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from protos import preprocess_pb2

def random_crop(image, random_crop_min_scale):
  """Random crops image according to the minimum scale requirement.

  Args:
    image: a [height, width, 3] uint8 image tensor.
    random_crop_min_scale: minimum scale.

  Returns:
    image: a [crop_height, crop_width, 3] float tensor.
  """
  height, width = tf.shape(image)[0], tf.shape(image)[1]

  min_height = tf.cast(
      tf.round(tf.cast(height, tf.float32) * random_crop_min_scale), tf.int32)
  min_width = tf.cast(
      tf.round(tf.cast(width, tf.float32) * random_crop_min_scale), tf.int32)

  target_height = tf.random_uniform(
      shape=[], dtype=tf.int32, minval=min_height, maxval=height + 1)
  target_width = tf.random_uniform(
      shape=[], dtype=tf.int32, minval=min_width, maxval=width + 1)

  offset_height = tf.random_uniform(
      shape=[], dtype=tf.int32, minval=0, maxval=height + 1 - target_height)
  offset_width = tf.random_uniform(
      shape=[], dtype=tf.int32, minval=0, maxval=width + 1 - target_width)

  image = tf.image.crop_to_bounding_box(image, offset_height, offset_width,
                                        target_height, target_width)
  return image

def preprocess_func(image, flip_left_right):
  """Preprocesses an image.

  Args:
    image: A [height, width, 3] uint8 tensor.
    flip_left_right: A boolean scalar tensor.
  """
  image = tf.cond(
      flip_left_right,
      true_fn=lambda: tf.image.flip_left_right(image),
      false_fn=lambda: image)
  return image

def preprocess_image_v2(image, options):
  """Get preprocess function based on options.

  Args:
    image: A [height, width, 3] uint8 tensor.
    options: An instance of PreprocessOptions.

  Returns:
    preprocessed_image: A [height, width, 3] uint8 tensor.

  Raises:
    ValueError: If the options is invalid.
  """
  if not isinstance(options, preprocess_pb2.Preprocess):
    raise ValueError('Options has to be an instance of Preprocess.')

  flip_left_right = tf.less(
      tf.random_uniform(shape=[]), options.random_flip_left_right_prob)
  operations = {'flip_left_right': flip_left_right}

  preprocessed_image = preprocess_func(image, flip_left_right)

  return preprocessed_image, operations

def preprocess_image(image, options):
  """Preprocesses an image.

  Args:
    image: a [height, width, 3] uint8 tensor.
    options: an instance of PreprocessOptions.

  Returns:
    preprocessed_image: a [height, width, 3] uint8 tensor.

  Raises:
    ValueError: if options is invalid
  """
  if not isinstance(options, preprocess_pb2.Preprocess):
    raise ValueError('Options has to be an instance of Preprocess.')

  # Change brightness.
  # Note: it has to be applied on uint8 image.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_brightness_prob),
      true_fn=lambda: tf.image.random_brightness(
        image, max_delta=options.random_brightness_max_delta),
      false_fn=lambda: image)

  image = tf.image.convert_image_dtype(image, dtype=tf.float32)

  # Change contrast.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_contrast_prob),
      true_fn=lambda: tf.image.random_contrast(image,
        lower=options.random_contrast_lower,
        upper=options.random_contrast_upper),
      false_fn=lambda: image)

  # Change hue.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_hue_prob),
      true_fn=lambda: tf.image.random_hue(
        image, max_delta=options.random_hue_max_delta),
      false_fn=lambda: image)

  # Change saturation.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_saturation_prob),
      true_fn=lambda: tf.image.random_saturation(image,
        lower=options.random_saturation_lower,
        upper=options.random_saturation_upper),
      false_fn=lambda: image)

  # Flip left-right.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_flip_left_right_prob),
      true_fn=lambda: tf.image.flip_left_right(image),
      false_fn=lambda: image)

  # Random crop.

  image = tf.cond(
      tf.less(tf.random_uniform(shape=[]), options.random_crop_prob),
      true_fn=lambda: random_crop(image, options.random_crop_min_scale),
      false_fn=lambda: image)

  return tf.image.convert_image_dtype(image, dtype=tf.uint8, saturate=True)

def parse_texts(tokens, offsets, lengths):
  """Parses and pads texts.

  Args:
    tokens: a [num_tokens] tf.string tensor denoting token buffer.
    offsets: a [num_texts] tf.int64 tensor, denoting the offset of each
      text in the token buffer.
    lengths: a [num_texts] tf.int64 tensor, denoting the length of each
      text.

  Returns:
    num_texts: number of texts after padding.
    text_strings: [num_texts, max_text_length] tf.string tensor.
    text_lengths: [num_texts] tf.int64 tensor.
  """
  max_text_length = tf.maximum(tf.reduce_max(lengths), 0)

  num_offsets = tf.shape(offsets)[0]
  num_lengths = tf.shape(lengths)[0]

  assert_op = tf.Assert(
      tf.equal(num_offsets, num_lengths),
      ["Not equal: num_offsets and num_lengths", num_offsets, num_lengths])

  with tf.control_dependencies([assert_op]):
    num_texts = num_offsets

    i = tf.constant(0)
    text_strings = tf.fill(tf.stack([0, max_text_length], axis=0), "")
    text_lengths = tf.constant(0, dtype=tf.int64, shape=[0])

    def _body(i, text_strings, text_lengths):
      """Executes the while loop body.

      Note, this function trims or pads texts to make them the same lengths.

      Args:
        i: index of both offsets/lengths tensors.
        text_strings: aggregated text strings tensor.
        text_lengths: aggregated text lengths tensor.
      """
      offset = offsets[i]
      length = lengths[i]

      pad = tf.fill(tf.expand_dims(max_text_length - length, axis=0), "")
      text = tokens[offset:offset + length]
      text = tf.concat([text, pad], axis=0)
      text_strings = tf.concat([text_strings, tf.expand_dims(text, 0)], axis=0)
      text_lengths = tf.concat(
          [text_lengths, tf.expand_dims(length, 0)], axis=0)
      return i + 1, text_strings, text_lengths

    cond = lambda i, unused_strs, unused_lens: tf.less(i, num_texts)
    (_, text_strings, text_lengths) = tf.while_loop(
        cond,
        _body,
        loop_vars=[i, text_strings, text_lengths],
        shape_invariants=[
            i.get_shape(),
            tf.TensorShape([None, None]),
            tf.TensorShape([None])
        ])

  return num_texts, text_strings, text_lengths


from dask.distributed import Client
import dask.dataframe as dd
from fastapi import FastAPI

client = Client()
app = FastAPI()

# Import data
opioids_data = dd.read_csv(
    "/Users/lorna/Documents/MIDS 2022/First Semester/720 Practicing Data Science/dask/arcos_2011_2012.tsv",
    sep="\t",
    usecols=["BUYER_STATE","TRANSACTION_DATE","Combined_Labeler_Name", "MME_Conversion_Factor", "CALC_BASE_WT_IN_GM"],
    dtype={"TRANSACTION_DATE": "object"}
)
opioids_data["morphine_equivalent"] = (opioids_data["CALC_BASE_WT_IN_GM"]) * (opioids_data["MME_Conversion_Factor"])
opioids_data["date"] = dd.to_datetime(opioids_data.TRANSACTION_DATE, format = "%m%d%Y")
opioids_data["year"] = opioids_data.date.dt.year

opioids_data1 = opioids_data[["BUYER_STATE","Combined_Labeler_Name","morphine_equivalent"]]
opioids_data2 = opioids_data[["BUYER_STATE","year","Combined_Labeler_Name","morphine_equivalent"]]

#get the dataset summary
@app.get("/")
def read_root():
    test = "testing root"
    return test

#BUYER States and the total they bought
@app.get("/states")
def read_state():
    total_states = opioids_data1.groupby(["BUYER_STATE"]).morphine_equivalent.sum()
    total_states_final = total_states.compute()
    return total_states_final

#enter a state and they return a total of morphine equivalent.
@app.get("/states/{state_id}")
def read_state_purchases(state_id:str):
    total_states = opioids_data2.groupby(["BUYER_STATE","year"]).morphine_equivalent.sum().reset_index()
    state = total_states.loc[total_states["BUYER_STATE"] == state_id].compute()
    return state

#Companies and how much they sold
@app.get("/companies")
def read_companies():
    total_companies = opioids_data1.groupby(["Combined_Labeler_Name"]).morphine_equivalent.sum()
    total_companies_final = total_companies.compute()
    return total_companies_final

#companies and how much they sold
@app.get("/companies/{company_name}")
def read_companies_sales(company_name:str):
    total_companies = opioids_data2.groupby(["Combined_Labeler_Name","year"]).morphine_equivalent.sum().reset_index()
    company = total_companies.loc[total_companies["Combined_Labeler_Name"]== company_name].compute()
    return company

#companies and how much they sold
@app.get("/companies/states/{company_name}")
def read_companies_states(company_name:str):
    companies = opioids_data2.groupby(["year","Combined_Labeler_Name", "BUYER_STATE"]).morphine_equivalent.sum().reset_index()
    states = companies.loc[companies["Combined_Labeler_Name"]== company_name,"BUYER_STATE"].unique().compute()
    return states


#!/usr/bin/env python
# coding: utf-8

# # COURSE: Master statistics and machine learning: Intuition, Math, code
# ##### COURSE URL: udemy.com/course/statsml_x/?couponCode=202006
# ## SECTION: The t-test family
# ### VIDEO: Mann-Whitney U test
# #### TEACHER: Mike X Cohen, sincxpress.com

# In[ ]:

# import libraries
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats

# In[ ]:

## generate the data

# the data (note the different sample sizes)
N1 = 30
N2 = 35

data1 = np.random.poisson(2,N1)
data2 = np.random.poisson(1,N2)

plt.plot(1+np.random.randn(N1)/10,data1,'ks',markerfacecolor='w')
plt.plot(2+np.random.randn(N2)/10,data2,'ro',markerfacecolor='w')

plt.xlim([0,3])
plt.xticks([1,2],labels=('data1','data2'))
plt.xlabel('Data group')
plt.ylabel('Data value')
plt.show()

# In[ ]:

## now for the test

U,p = stats.mannwhitneyu(data1,data2)

print(U,p)


import tempfile
import os
import torch
from kaner.common import save_text, save_json
from kaner.adapter.tokenizer.char import CharTokenizer

def test_chartokenizer():
    """Test the class `CharTokenizer`."""
    tokens = ["[UNK]", "[PAD]", "南", "京", "市", "长", "江", "大", "桥"]
    token_embeddings = [
        [0.0, 0.0],
        [0.0, 0.0],
        [0.9, 0.3],
        [0.7, 0.8],
        [0.21, 0.78],
        [0.51, 0.82],
        [0.23, 0.91],
        [0.39, 0.61],
        [0.98, 0.45]
    ]
    tmp_folder = tempfile.TemporaryDirectory()
    folder_name = tmp_folder.name
    save_text("\n".join(tokens), folder_name, "tokens.txt")
    torch.save(torch.tensor(token_embeddings), os.path.join(folder_name, "token_embeddings.checkpoints"))
    config = {"n_tokens": 9, "token_dim": 2}
    save_json(config, folder_name, "token_configs.json")
    tokenizer = CharTokenizer(folder_name)
    assert len(tokenizer) == 9
    config["pad_id"] = 1
    assert tokenizer.configs() == config
    assert tokenizer.unk_token == "[UNK]"
    assert tokenizer.pad_token == "[PAD]"
    assert tokenizer["南"] == 2
    assert tokenizer[3] == "京"
    assert tokenizer.tokenize("南京是好朋友") == ["南", "京", "是", "好", "朋", "友"]
    assert tokenizer.convert_tokens_to_ids(["南", "京", "是", "好", "朋", "友"]) == [2, 3, 0, 0, 0, 0]
    assert [[round(e, 2) for e in em] for em in tokenizer.embeddings().tolist()] == token_embeddings
    tmp_folder.cleanup()


#Raspberyy PI nin 2x16 LCD modulunu kullanabilmesi icin gerekli olan
#kutuphane tanimlamasi yapiliyor.

import RPi.GPIO as GPIO
import os
import time
from time import gmtime, strftime

#LCD'nin kullanacagi GPIO pinlerinin tanimi yapiliyor.
LCD_RS = 7
LCD_E  = 8
LCD_D4 = 25
LCD_D5 = 24
LCD_D6 = 23
LCD_D7 = 18

# LCD ye ait sabitler tanımlanıyor.
LCD_WIDTH = 16  # Satır basina dusen maksimum karakter sayisi
LCD_CHR = True
LCD_CMD = False

LCD_LINE_1 = 0x80 # 1. Satir için LCD yea ait RAM Adreslemesi
LCD_LINE_2 = 0xC0 # 2. Satir için LCD yea ait RAM Adreslemesi

# Zaman Sabitleri
E_PULSE = 0.0005
E_DELAY = 0.0005

#GPIO pinleri ayarlaniyor.
def pinIoAyarla():
  GPIO.setwarnings(False)
  GPIO.setmode(GPIO.BCM)       # Mod ayarlaniyor
  GPIO.setup(LCD_E, GPIO.OUT)  # E
  GPIO.setup(LCD_RS, GPIO.OUT) # RS
  GPIO.setup(LCD_D4, GPIO.OUT) # DB4
  GPIO.setup(LCD_D5, GPIO.OUT) # DB5
  GPIO.setup(LCD_D6, GPIO.OUT) # DB6
  GPIO.setup(LCD_D7, GPIO.OUT) # DB7

def main():

  #Pinler ayarlaniyor
  pinIoAyarla()

  # LCD ye ait ilk ayarlamalar (Initialise) yapiliyor
  lcd_init()

#LCD ye ait ilk tanimlamalari yapan metot
def lcd_init():
  # Initialise display
  lcd_byte(0x33,LCD_CMD)
  lcd_byte(0x32,LCD_CMD)
  lcd_byte(0x06,LCD_CMD)
  lcd_byte(0x0C,LCD_CMD)
  lcd_byte(0x28,LCD_CMD)
  lcd_byte(0x01,LCD_CMD)
  time.sleep(E_DELAY)

#LCD ye ait mod ve diger ayarlamalari yapan metot
def lcd_byte(bits, mode):

  GPIO.output(LCD_RS, mode) # RS

  #Yuksek seviyeli bitler
  GPIO.output(LCD_D4, False)
  GPIO.output(LCD_D5, False)
  GPIO.output(LCD_D6, False)
  GPIO.output(LCD_D7, False)
  if bits&0x10==0x10:
    GPIO.output(LCD_D4, True)
  if bits&0x20==0x20:
    GPIO.output(LCD_D5, True)
  if bits&0x40==0x40:
    GPIO.output(LCD_D6, True)
  if bits&0x80==0x80:
    GPIO.output(LCD_D7, True)

  # Enable pin toggle ediliyor
  lcd_toggle_enable()

  #Dusuk seviyeli bitler
  GPIO.output(LCD_D4, False)
  GPIO.output(LCD_D5, False)
  GPIO.output(LCD_D6, False)
  GPIO.output(LCD_D7, False)
  if bits&0x01==0x01:
    GPIO.output(LCD_D4, True)
  if bits&0x02==0x02:
    GPIO.output(LCD_D5, True)
  if bits&0x04==0x04:
    GPIO.output(LCD_D6, True)
  if bits&0x08==0x08:
    GPIO.output(LCD_D7, True)

  # Enable pin toggle ediliyor
  lcd_toggle_enable()

def lcd_toggle_enable():
  # Enable islemi gerceklestiriliyor
  time.sleep(E_DELAY)
  GPIO.output(LCD_E, True)
  time.sleep(E_PULSE)
  GPIO.output(LCD_E, False)
  time.sleep(E_DELAY)

#LCD ye mesaj yazdirmaya yarayan metot
def lcd_string(message,line):
  # Mesaj string e cast(donusturuluyor) ediliyor
  message = str(message)
  # Mesaj LCD ye gonderiliyor
  message = message.ljust(LCD_WIDTH," ")

  lcd_byte(line, LCD_CMD)

  for i in range(LCD_WIDTH):
    lcd_byte(ord(message[i]),LCD_CHR)

if __name__ == '__main__':

  try:
    main()
  except KeyboardInterrupt:
    pass
  finally:
    lcd_byte(0x01, LCD_CMD)
    lcd_string("Gule gule",LCD_LINE_1)
    GPIO.cleanup()


import numpy as np
from keras.models import load_model

test_images = np.load("mnist_test_images.npy")
test_labels = np.load("mnist_test_labels.npy")

network = load_model("mnist_model.h5")

# Evaluate the model
print("Evaluating...")
test_loss, test_acc = network.evaluate(test_images, test_labels)
print()
print("Test accuracy:", test_acc)
print("Test loss:", test_loss)


import torch

from torch.nn.utils.rnn import pad_sequence

class Translator:

    def __init__(self, model, dataset):

        self.model = model
        self.dataset = dataset

    def translate(self, src_strs, device="cuda"):

        src_field, trg_field = self.dataset.src, self.dataset.trg
        src_vocab, trg_vocab = src_field.vocab, trg_field.vocab
        unk_idx, pad_idx = src_vocab["<unk>"], src_vocab["<pad>"]
        sos_idx, eos_idx = trg_vocab["<sos>"], trg_vocab["<eos>"]

        def src_str_to_id(token):
            id = src_vocab.stoi.get(token)
            if id is None:
                id = unk_idx
            return id

        def trg_id_to_str(id):
            return trg_vocab.itos[id]

        src_tokens = list(map(src_field.tokenize, src_strs))
        src_idxs = [torch.tensor(list(map(src_str_to_id, tokens)), dtype=torch.int64)
                    for tokens in src_tokens]
        src_idxs = pad_sequence(src_idxs, batch_first=True, padding_value=pad_idx).to(device)

        trg_ids = self.generate_trg_idxs(src_idxs, sos_idx, eos_idx)
        trg_tokens = [list(map(trg_id_to_str, ids)) for ids in trg_ids]
        return trg_tokens

    @torch.no_grad()
    def generate_trg_idxs(self, src, sos_idx, eos_idx, stopping_len=64):

        batch_size, _ = src.shape
        trg = sos_idx * torch.ones(batch_size, 1, dtype=torch.int64).to(src.device)

        idxs = [i for i in range(batch_size)]
        trg_idxs = [None for _ in range(batch_size)]
        len_counter = 0

        while True:
            logits = self.model(src, trg)
            pred_idxs = torch.argmax(logits, dim=-1)
            next_idxs = pred_idxs[:, -1].unsqueeze(-1)
            trg = torch.cat((trg, next_idxs), dim=-1)

            eos_mask = (next_idxs == eos_idx).squeeze(-1)

            for i, stop in reversed(list(enumerate(eos_mask))):
                if not stop:
                    continue
                idx = idxs[i]
                trg_idxs[idx] = trg[i, 1:-1].tolist()
                del idxs[i]

            src = src[eos_mask == 0]
            trg = trg[eos_mask == 0]

            if len(src) == 0:
                break

            len_counter += 1
            if len_counter >= stopping_len:
                for i in range(len(trg)):
                    idx = idxs[i]
                    trg_idxs[idx] = trg[i, 1:].tolist()
                break

        return trg_idxs


from __future__ import division, print_function
import os
import pandas as pd
import numpy as np
from parse_files import parse_quakes

def instrumental_fit(time_lapse=1, min_pga=0.039):
    quakes = parse_quakes()
    foo = 0
    fname = '../Results/Instrumental/Domains.csv'
    if os.path.isfile(fname):
        foo = 1
    for code, quake in quakes.viewitems():
        if quake.__class__.__name__ == 'DomainEarthquake':
            if foo == 1:
                outputs = pd.read_csv(fname, header=0)
                compiled_codes = list(np.unique(outputs['Code']))
            else:
                compiled_codes = []
            if code not in compiled_codes:
                print(code, quake, quake.proc, quake.mag, quake.shape)
                summary = quake.sesm(time_lapse, min_pga)
                if not summary.empty:
                    # print(list(summary))
                    print(summary)
                    if foo == 1:
                        outputs = outputs.append(summary)
                    else:
                        outputs = summary
                        foo = 1
                    outputs.to_csv('../Results/Instrumental/Domains.csv', index=False)

#instrumental_fit(time_lapse=1, min_pga=0.039)


OPENING_CHARS = '([{<'
CLOSING_CHARS = ')]}>'
CHAR_ERROR_SCORES = {')':3,']':57,'}':1197,'>':25137}
CHAR_ERROR_SCORES_SECOND = {')':1,']':2,'}':3,'>':4}

def line_corrupted(line):
    closing_chars = []

    for idx in range(len(line)):
        if(line[idx] in OPENING_CHARS):
            closing_chars.append(CLOSING_CHARS[OPENING_CHARS.index(line[idx])])
        elif(closing_chars[-1] != line[idx]):
            # Corrupted line - add to score
            score = CHAR_ERROR_SCORES.get(line[idx])
            return score, True, []
        else:
            closing_chars = closing_chars[:-1]

    return 0, False, closing_chars

def solver_first(lines):
    score = 0
    for line in lines:
        line_score, corrupted, _ = line_corrupted(line)

        if corrupted:
            score += line_score

    return score

def solver_second(lines):
    scores = []
    for line in lines:
        closing_chars = []
        score = 0
        corrupted_line = False

        for idx in range(len(line)):
            _, corrupted, closing_chars = line_corrupted(line)

            if corrupted:
                corrupted_line = True

        if not corrupted_line:
            for idx in reversed(closing_chars):
                score = score * 5 + CHAR_ERROR_SCORES_SECOND.get(idx)
            scores.append(score)

    scores.sort()
    return scores[int(len(scores) / 2)]

if __name__ == '__main__':
    lines = open('input.txt','r').read().split('\n')

    first_result = solver_first(lines)
    second_result = solver_second(lines)

    print(first_result, second_result)


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

#
### Test y axis from -1 to 1 under webcam
#

#TO DELETE
def normalize_labels(data, screen_width, screen_height):
    # Top Centered webcam

    # Screen
    data['x'] = (data['x']/screen_width*2)-1
    data['y'] = (data['y']/screen_height*2)-1

# TO DELETE
def normalize_data(data, webcam_width, webcam_height):
    # Top Centered webcam

    # Imgs
    cols_x = ['eye_right_x','eye_left_x','face_x']  # Range [-1,1]
    for col in cols_x:
        data[col] = data[col]/webcam_width*2-1

    cols_width = ['eye_right_width','eye_left_width','face_width']  # Range [0,2]
    for col in cols_width:
        data[col] = data[col]/webcam_width*2

    cols_y = ['eye_right_y','eye_left_y','face_y']  # Range [-1,1]
    for col in cols_y:
        data[col] = data[col]/webcam_height*2-1

    cols_height = ['eye_right_height','eye_left_height','face_height'] # Range [0,2]
    for col in cols_height:
        data[col] = data[col]/webcam_height*2

def normalize_features02(data, features, webcam_width, webcam_height):
    # X coord, range [-1,1]
    for col in [x for x in features if x.endswith('x')]:
        data[col] = data[col]/webcam_width*2-1
    # Width, range [0,2]
    for col in [x for x in features if x.endswith('width')]:
        data[col] = data[col]/webcam_width*2
    # Y coord, range [-1,1]
    for col in [x for x in features if x.endswith('y')]:
        data[col] = data[col]/webcam_height*2-1
    # Height, range[0,2]
    for col in [x for x in features if x.endswith('height')]:
        data[col] = data[col]/webcam_height*2


import heapq
def dijkstra(k):
    dp[k] = 0
    heapq.heappush(heap, [0, k])
    while heap:
        w, n = heapq.heappop(heap)
        for n_n, weight in graph[n]:
            n_w = weight + w
            if n_w < dp[n_n]:
                dp[n_n] = n_w
                heapq.heappush(heap, [n_w, n_n])

v, e = map(int, input().split())
k = int(input())
graph = [[] for _ in range(v+1)]
inf = 1e9
dp = [inf] * (v+1)
heap = []

for i in range(e):
    u, v, w = map(int, input().split())
    graph[u].append([v, w])
dijkstra(k)

for i in dp[1:]:
    print(i if i != inf else "INF")


import os
from PyQt5.QtCore import QObject,pyqtSignal,pyqtSlot
import pyautogui
from time import sleep

class Worker(QObject):
    'Object managing the simulation'
    finished = pyqtSignal()
    sbMessage = pyqtSignal(list)

    def __init__(self):
        super(Worker, self).__init__()

    def control(self,action):
        cd = {"X Coordinate":"int","Y Coordinate":"int","Relative X":"int","Relative Y":"int","Clicks":"int","Times":"int",
              "Button":["left","middle","right"], "Overwrite":["yes","no"], "Search Until Find":["yes","no"], "Press After Found":["yes","no"],"Fast Find":["yes","no"],
              "Duration":"float","Interval":"float", "Presses":"int","Wait":"float","Miliseconds":"int",
              "Text":"str", "Key":"key", "Hotkey":"multiKey","Dir Path":"str","File Name":"str","File Path":"str"}
        keys = pyautogui.KEYBOARD_KEYS
        j=0
        for i in range(1,len(action)):
            setting_ = action[i+j:i+j+2]
            if cd[setting_[0]] == "int":
                try:int(setting_[1])
                except: return [False,i]
            if setting_[0] == "Button":
                if not setting_[1] in cd[setting_[0]]: return [False,i]
            if cd[setting_[0]] == "float":
                try: float(setting_[1])
                except: return [False,i]
            if cd[setting_[0]] == "key":
                if not setting_[1] in keys: return [False,i]
            if cd[setting_[0]] == "multiKey":
                for _ in setting_[1].split():
                    if not _ in keys: return [False,i]
            if setting_[0] == "Dir Path":
                if not os.path.isdir(setting_[1]): return [False,"{} , no directory.".fotmat(i)]
            if setting_[0] == "File Path":
                if not os.path.isfile(setting_[1]): return [False,"{} , no file.".fotmat(i)]
            if setting_[0] == "File Name":
                if setting_[1] == "" or None: return [False,"{} , no file name.".fotmat(i)]
            if cd[setting_[0]] == ["yes","no"]:
                if not setting_[1] in ["yes","no"]: return [False,i]

            if i+j+2 == len(action):
                return [True]
            j+=1

    def run(self):
        for action in self._actions:
            if not self._running:
                self.sbMessage.emit(["Program stopped.",4000])
                self.finished.emit()
                break
            if action[0] ==  "Delay":
                delay = int(action[2])
                sleep(delay/1000)
# =============================================================================
#                 loop = QEventLoop()
#                 QTimer.singleShot(delay, loop.quit)
#                 loop.exec_()
# =============================================================================
                ##ÿQTest.qWait(delay)

            # MOUSE
            if action[0] ==  "Move To":
                x,y,duration = int(action[2]),int(action[4]),float(action[6])
                pyautogui.moveTo(x,y,duration)
            if action[0] ==  "Move Relative":
                x,y,duration = int(action[2]),int(action[4]),float(action[6])
                pyautogui.moveRel(x,y,duration)
            if action[0] ==  "Drag To":
                x,y,duration = int(action[2]),int(action[4]),float(action[6])
                pyautogui.dragTo(x,y,duration)
            if action[0] ==  "Drag Relative":
                x,y,duration = int(action[2]),int(action[4]),float(action[6])
                pyautogui.dragRel(x,y,duration)
            if action[0] ==  "Click To":
                x,y,button,clicks,interval,duration = int(action[2]),int(action[4]),action[6],int(action[8]),float(action[10]),float(action[12])
                pyautogui.click(x=x,y=y,button=button,clicks=clicks,interval=interval,duration=duration)
            if action[0] ==  "Click":
                button,clicks,interval,duration = action[2],int(action[4]),float(action[6]),float(action[8])
                pyautogui.click(button=button,clicks=clicks,interval=interval,duration=duration)
            if action[0] ==  "Scroll":
                clicks = int(action[2])
                pyautogui.scroll(clicks=clicks)

            # KEYBOARD
            if action[0] ==  "Write":
                interval,text = float(action[2]),action[4]
                pyautogui.typewrite(text,interval=interval)
            if action[0] ==  "Press":
                presses,interval,text = int(action[2]),float(action[4]),action[6]
                pyautogui.press(text,interval=interval,presses=presses)
            if action[0] ==  "Hotkey":
                hotkey = action[2].split()
                pyautogui.hotkey(*hotkey)
            if action[0] ==  "Key Down":
                hotkey = action[2]
                pyautogui.keyDown(hotkey)
            if action[0] ==  "Key Up":
                hotkey = action[2]
                pyautogui.keyUp(hotkey)

            # SCREEN
            if action[0] ==  "Screenshot":
                overwrite,dir_path,file_name = action[2],action[4],action[6]
                if overwrite == "yes":
                    path = os.path.join(dir_path,file_name)+".png"
                    pyautogui.screenshot(path)
                if overwrite == "no":
                    path = os.path.join(dir_path,file_name)
                    path = self.notOverwrite(path)
                    pyautogui.screenshot(path)

            if action[0] ==  "Find Image":
                cb1,cb2,cb3,wait,path = action[2],action[4],action[6],float(action[8]),action[10]

                if cb1 == "yes":
                    while self._running:
                        a = None
                        try:
                            if cb3:
                                a = pyautogui.locateCenterOnScreen(path,grayscale=True)
                            else:
                                a = pyautogui.locateCenterOnScreen(path)
                        except:pass
                        if a:
                             break
                        sleep(wait)
                    if cb2 == "yes" and a:
                         pyautogui.click(a[0],a[1])
                if cb1 == "no":
                    a = None
                    try:
                        if cb3:
                            a = pyautogui.locateCenterOnScreen(path,grayscale=True)
                        else:
                            a = pyautogui.locateCenterOnScreen(path)
                    except:pass
                if cb2 == "yes" and a:
                    pyautogui.click(a[0],a[1])

    @pyqtSlot()
    def start(self,steps,actions,loop):
        self._step = 0
        self._running = True
        self._maxSteps = steps
        self._actions = actions

        for i,action in enumerate(self._actions):
            c = self.control(action)
            if c[0] == False:
                self.sbMessage.emit(["Error at {},{}".format(i+1,c[1]),5000])
                self._running == False

        if loop == False:
            while self._step  < self._maxSteps  and self._running == True:
                self._step += 1
                self.sbMessage.emit(["Running... {}".format(self._step)])
                self.run()

        if loop == True:
            while self._running == True:
                self._step += 1
                self.sbMessage.emit(["Running... {}".format(self._step)])
                self.run()

        if self._running == True:
            self.sbMessage.emit(["Successfully end.",4000])
            self.finished.emit()
        else:
            self.sbMessage.emit(["Program stopped.",4000])
            self.finished.emit()

    def stop(self):
        self.finished.emit()
        self._running = False

    def notOverwrite(self,path):
        if not os.path.isfile(path+".png"):
            return path+".png"

        for i in range(1,100000):
            path2 = path+"({})".format(i)
            if not os.path.isfile(path2+".png"):
                return path2+".png"


# Integer to English Words: https://leetcode.com/problems/integer-to-english-words/
# Convert a non-negative integer num to its English words representation.

# After writting down a few examples I think the best way to do this is by sections of 3
# every time we go up by 3 we actually add a height word to the end ie (null, hundred, thousand, million, billion)
# then we have the following per 3
#  Number  hundred  Number+tensplace (seventy/sixty) number (height)

# I forgot eleven tweleve ...

# Create an enum/dict then follow the above pattern?

class Solution:
    # Initial thought but this is rough
    # def __init__(self):
    #     self.height = {0: None, 1: 'Hundred', 2: 'Thousand', 3: 'Million', 4: 'Billion'}
    #     self.tens = {''}
    #     self.ten = {''}
    #     self.ones = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine',}

    def numberToWords(self, num: int) -> str:
        # Convert all the types of numbers
        def one(num):
            switcher = {
                1: 'One',
                2: 'Two',
                3: 'Three',
                4: 'Four',
                5: 'Five',
                6: 'Six',
                7: 'Seven',
                8: 'Eight',
                9: 'Nine'
            }
            return switcher.get(num)

        def two_less_20(num):
            switcher = {
                10: 'Ten',
                11: 'Eleven',
                12: 'Twelve',
                13: 'Thirteen',
                14: 'Fourteen',
                15: 'Fifteen',
                16: 'Sixteen',
                17: 'Seventeen',
                18: 'Eighteen',
                19: 'Nineteen'
            }
            return switcher.get(num)

        def ten(num):
            switcher = {
                2: 'Twenty',
                3: 'Thirty',
                4: 'Forty',
                5: 'Fifty',
                6: 'Sixty',
                7: 'Seventy',
                8: 'Eighty',
                9: 'Ninety'
            }
            return switcher.get(num)

        def two(num):
            # Given some numbers like
            # 00 -> ''
            # 9 -> Nine (pass to one)
            # 19 -> Nineteen (pass to two less than 20)
            # 29 -> Figure out special ten values
            if not num:
                return ''
            elif num < 10:
                return one(num)
            elif num < 20:
                return two_less_20(num)
            else:
                # Grab tens place to make Twenty, Thirty etc
                tenner = num // 10
                # Pass the rest to one as we have Twenety Five
                # or rest is nothing and we just pass back then tens place
                rest = num - tenner * 10
                return ten(tenner) + ' ' + one(rest) if rest else ten(tenner)

        def three(num):
            # If there are 3 values then we need to add a 'Hundred'
            hundred = num // 100
            # Then get the rest and pass it down
            rest = num - hundred * 100
            # 233 -> Two Hundred and rest
            # 023 -> rest (twenty three) (height)
            # 200 -> Two Hundred (height)
            if hundred and rest:
                return one(hundred) + ' Hundred ' + two(rest)
            elif not hundred and rest:
                return two(rest)
            elif hundred and not rest:
                return one(hundred) + ' Hundred'

        # Take our number and reduce each piece
        # From top down since we don't care about negative numbers as we go down we just remove that much
        # Alternatively we could go by length and reduce it but that is more comlex
        billion = num // 1000000000
        million = (num - billion * 1000000000) // 1000000
        thousand = (num - billion * 1000000000 - million * 1000000) // 1000
        rest = num - billion * 1000000000 - million * 1000000 - thousand * 1000

        # If we remove all the
        if not num:
            return 'Zero'

        # Build the result up
        result = ''
        if billion:
            # If there is a billions place call out to however many billions we have
            result = three(billion) + ' Billion'
        if million:
            # Then add the millions (Add space if we have previous)
            result += ' ' if result else ''
            result += three(million) + ' Million'
        if thousand:
            # Then add the thousand (Add space if we have previous)
            result += ' ' if result else ''
            result += three(thousand) + ' Thousand'
        if rest:
            # Then add the rest (Add space if we have previous)
            result += ' ' if result else ''
            result += three(rest)
        return result

# Score Card
# Did I need hints? Ish
# Did you finish within 30 min? N
# Was the solution optimal? The result ends up parsing in O(N) but it is divide and conquer
# Were there any bugs? So many edge cases for english
#  2 1 4 2 = 2.25


import logging.config
import logging.handlers

def set_logging(project_name, logging_path='mylog.log'):
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    logger = logging.getLogger(project_name)
    logger.setLevel(logging.DEBUG)

    filehandler = logging.handlers.TimedRotatingFileHandler(filename=logging_path, when='D', backupCount=7)
    filehandler.setLevel(logging.INFO)
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)

    streamhandler = logging.StreamHandler()
    streamhandler.setLevel(logging.DEBUG)
    streamhandler.setFormatter(formatter)
    logger.addHandler(streamhandler)

    logger.info("Logger started")


# Port Scanner

import socket
# https://docs.python.org/3/library/socket.html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#host = "137.74.187.100" # you can get this number by entering "ping 'website URL'" in the CLI
#port = 443 # could check ports 443, 80, 21, etc

host = input("Please enter the IP address you want to scan: ")
port = int(input("Please enter the port you want to scan: "))

def portScanner(port):
    if s.connect_ex((host, port)):
        print("The port is closed")
    else:
        print("The port is open")

portScanner(port)


from add import add_account as a
from delete import delete_account as d
from disp import display as l
from banking import accounting as acc
from deposit import depositing as dep
from summary import details as s
while 1:
    print('\n\n\n     Welcome to IIIT DHARWAD BANK ')
    print('\n\t Select your choice')
    print('\n 0. Account Summary \n 1. All account details \n 2. cash withdrawl \n 3. cash deposit \n 4. Add account \n 5. delete account \n 6. Exit')
    ch=int(input(' \n Enter your choice : '))
    if ch==0:
        s()
    elif ch==1:
        l()
    elif ch==2:
        acc()
    elif ch==3:
        dep()
    elif ch==4:
        a()
    elif ch==5:
        d()
    elif ch==6:
        break
    else:
        print(' \n Wrong Choice!')


import openpyxl
wb = openpyxl.load_workbook('NUMBER_PLATE_LIST (Autosaved)1.xlsx')
ws=wb.active
count=0
i=0
first=ws['C']
second=ws['D']
a=[]
for(cell,cell_1) in zip(first,second):
    if str(cell.value) == str(cell_1.value).split()[-1]:
        count=count+1
    if str(cell.value) != str(cell_1.value).split()[-1]:
        count=count+1
        a.append(count)
        i=i+1

f=open("vehicle_list_day_footage.txt","r")
f1=open("out.txt","w")
count=0
i=0
x=0
for lines in f:
    count=count+1
    if(count == a[i]):
        print(lines)
        i=i+1
        f1.write(lines)
        continue


#!/usr/bin/env python3
# dpw@Darryls-iMac.localdomain
# 2023-03-10 21:45:37
#

# @see https://schedule.readthedocs.io/

import threading
import time

import schedule

# no input args; with args, use functools.partial to define
def job():
    print(
        f"working at {time.time()} on thread {threading.current_thread()}", flush=True
    )

def run_threaded(func):
    jthread = threading.Thread(target=func)
    jthread.start()

schedule.every(5).seconds.do(run_threaded, job)  # or job, *args, **kwargs)

n = 60
while n > 0:
    schedule.run_pending()
    time.sleep(1)
    n -= 1


#!/usr/bin/env python3
import csv

_MAJOR = 'Major Program Name'
_CIP_CODE = 'CIP# Only'

def tag(cip, mpn, d):
    try:
        d[cip][mpn] += 1
    except:
        try:
            d[cip][mpn] = 1
        except:
            d[cip] = { mpn : 1 }

def make_into_fn(majors):
    def fn(row):
        newr = row.copy()
        try:
            newr[_MAJOR] = majors[newr[_CIP_CODE]]
        except:
            newr[_MAJOR] = "Unknown"
        return newr
    return fn

if __name__ == '__main__':
    majors = {}
    with open('NCWIT_DataV2_RawData.csv', 'rU') as csvfile:
        csvreader = csv.DictReader(csvfile)
        fieldnames = csvreader.fieldnames
        rdr = list(csvreader)
    for line in rdr:
        mpn = line[_MAJOR]
        cip = line[_CIP_CODE]
        if cip != '' and mpn != '':
            tag(cip, mpn, majors)
    print(majors)
    actualmajors = {}
    for key in majors.keys():
        majorkeys = list(majors[key].keys())
        maxkey = majorkeys[0]
        maxcnt = majors[key][maxkey]
        for majorkey in majorkeys:
            if majors[key][majorkey] > maxcnt:
                maxcnt = majors[key][majorkey]
                maxkey = majorkey
        actualmajors[key] = maxkey
    print(actualmajors)
    with open('NCWIT_DataV2_NormalizedMajors.csv', 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
        writer.writeheader()
        writer.writerows(map(make_into_fn(actualmajors), rdr))
    print("All done!")


from collections import deque

# 각 노드가 연결된 정보를 표현(2차원 리스트)
n, m = map(int, input().split(' '))

graph = [[] for _ in range(n+1)]
for i in range(m):
    a,b = map(int,input().split(' '))
    graph[a].append(b) # 서로 마주하기 때문에 해당 인덱스의 리스트에 값을 추가한다.
    graph[b].append(a)

#print(graph)

def bfs(start) :
    # 큐(Queue) 구현을 위해 deque 라이브러리 사용
    queue = deque([start])
    # 현재 노드를 방문 처리
    visited[start] = 1

    while queue: # 큐가 없을때 까지 계속 수행
        # 큐에서 하나의 원소를 뽑아 출력하기
        v = queue.popleft()
        # 아직 방문하지 않은 인접한 원소들을 큐에 삽입
        for i in graph[v]:
            if not visited[i] :
                visited[i] = visited[v] + 1
                queue.append(i)

result = []

for i in range(1, n+1) :
    visited = [0] * (n+1) # 방문횟수는 친구의 수 + 1
    bfs(i)
    result.append(sum(visited))

# 가장 작은 케빈 베이컨의 수를 가지고 있는 사람의 인덱스 + 1 을 해주어 출력한다.
print(result.index(min(result)) + 1)

백준/Silver/1389. 케빈 베이컨의 6단계 법칙/케빈 베이컨의 6단계 법칙.py

케빈 베이컨의 6단계 법칙.py


import os, shutil
from datetime import datetime
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint, ProgbarLogger, TerminateOnNaN

# endregion: Imports

class BaseTrainer:
    def __init__(self, config):
        self.config = config
        self.dataset = None
        self.dataset_iterator = None
        self.model = None
        self.loss_ops = None
        self.optimizer = None
        self.metrics_ops = None
        self.max_steps = 0
        self.max_epoch = 0

        self.name = None
        self.batch_size = 0
        self.save_steps = 0
        self.test_steps = 0
        self.summary_steps = 0
        self.verbose = 0
        self.callbacks = None
        self.logdir = None
        self.tensorboard_dir = None
        self.checkpoint_path = None

    def prepare_dataset(self):
        print("Preparing Dataset .........")
        self.dataset = self.config.DATA_CONFIG.DATASET
        print("Preparing Dataset Iterator .........")
        self.dataset_iterator = self.config.DATA_CONFIG.ITERATOR

    def prepare_model(self):
        print("Preparing Model .........")
        self.model = self.config.MODEL_CONFIG.NETWORK(self.config, self.config.DATA_CONFIG.DATASET.num_classes)
        input_shape = tuple([None] + self.config.DATA_CONFIG.IMAGE_SIZE + [self.config.DATA_CONFIG.CHANNELS])
        self.model.build(input_shape=input_shape)
        print("Preparing Loss .........")
        self.loss_ops = self.config.MODEL_CONFIG.LOSS(**self.config.MODEL_CONFIG.LOSS_KWARGS)
        print("Preparing Optimizer .........")
        self.optimizer = self.config.MODEL_CONFIG.OPTIMIZER(**self.config.MODEL_CONFIG.OPTIMIZER_KWARGS)
        print("Preparing Training Metrics ..........")
        self.metrics_ops = self.config.MODEL_CONFIG.METRICS
        print("Compiling Model ..........")
        self.model.compile(**self.config.MODEL_CONFIG.COMPILE_KWARGS)
        print("Building Model ...........")

    def prepare_training(self):
        self.name = self.config.PROJECT_CONFIG.NAME
        self.batch_size = self.config.PROJECT_CONFIG.BATCH_SIZE
        self.max_epoch = self.config.PROJECT_CONFIG.MAX_EPOCHS
        self.save_steps = self.config.PROJECT_CONFIG.SAVE_STEPS
        self.test_steps = self.config.PROJECT_CONFIG.TEST_STEPS
        self.summary_steps = self.config.PROJECT_CONFIG.SUMMARY_STEPS
        self.verbose = self.config.PROJECT_CONFIG.TRAINING_VERBOSE
        if self.config.PROJECT_CONFIG.LOG_DIR:
            self.logdir = self.config.PROJECT_CONFIG.LOG_DIR
            self.tensorboard_dir = self.config.PROJECT_CONFIG.TENSORBOARD_DIR
            self.checkpoint_path = self.config.PROJECT_CONFIG.CHECKPOINT_PATH
            self.callbacks = self.config.PROJECT_CONFIG.CALLBACKS
            os.makedirs(os.path.dirname(self.tensorboard_dir), exist_ok=True)
            os.makedirs(os.path.dirname(self.checkpoint_path), exist_ok=True)

    def prepare_network(self):
        self.prepare_dataset()
        self.prepare_model()
        self.prepare_training()


from utils import *

if __name__ == '__main__':
    trainloader, _ , _ = build_datasets()

    for epoch in range(2):  # 데이터셋을 수차례 반복합니다.
        for i, data in enumerate(trainloader, 0):
            # 입력을 받은 후,
            inputs, labels = data
            imshow(torchvision.utils.make_grid(inputs))


from pylab import figure, rand, setp, show

contig_names = ['AAB0008r'] * 10
fig = figure()
ax = fig.add_subplot(111)
ax.plot(rand(10))
ax.set_xticks(range(10))
ax.set_xticklabels(contig_names)
setp(ax.get_xticklabels(), fontsize=10, rotation='vertical')
# fig.autofmt_xdate()
show()


#!/usr/bin/env python
import sys
import string
import xml.dom.minidom

class NamedElement:
	def __init__(self, xml_element):
		name_element = xml_element.getElementsByTagName('name')[0]
		self.name = name_element.firstChild.data.strip()

class DocumentedElement:
	def __init__(self, xml_element):
		doc_element = xml_element.getElementsByTagName('documentation')[0]
		self.documentation = doc_element.firstChild.data.strip()

class TypedElement:
	def __init__(self, xml_element):
		self.type = []

		type_element = xml_element.getElementsByTagName('type')[0]

		choices = [e for e in type_element.childNodes
		           if e.nodeType == e.ELEMENT_NODE]
		node = choices[0]

		while node:
			if node.nodeName == 'enum-value':
				enum = node.getAttribute('name')
				self.type.append(('enum-value', enum))
			else:
				self.type.append(node.nodeName)

			choices = [e for e in node.childNodes
			           if e.nodeType == e.ELEMENT_NODE]
			node = (choices or [None])[0]

class IpcFoo:
	def __init__(self, xml_element):
		self.version = int(xml_element.getAttribute('version'))
		self.objects = []
		self.constants = {}
		self.enums = {}

		constant_elements = xml_element.getElementsByTagName('constant')
		for constant_element in constant_elements:
			constant = IpcConstant(constant_element)
			self.constants[constant.name] = constant

		enum_elements = xml_element.getElementsByTagName('enum')
		for enum_element in enum_elements:
			enum = IpcEnum(enum_element, self.constants)
			self.enums[enum.name] = enum

		object_elements = xml_element.getElementsByTagName('object')
		object_id = 1 # ID 0 is reserved for signal voodoo

		for object_element in object_elements:
			object = IpcObject(object_element)

			object.id = object_id
			object_id += 1

			self.objects.append(object)

class IpcEnum(NamedElement):
	def __init__(self, xml_element, constants):
		NamedElement.__init__(self, xml_element)

		member_elements = xml_element.getElementsByTagName('member')
		members = {}

		current_value = 0
		for member_element in member_elements:
			name = member_element.firstChild.data.strip()
			ref_val = member_element.getAttribute('ref-value')
			ref_type = member_element.getAttribute('ref-type')
			if ref_type == 'constant' and ref_val != '':
				current_value = constants[ref_val].value
			elif ref_val != '':
				current_value = members[ref_val]
			members[name] = current_value
			current_value += 1
		self.members = members

class IpcConstant(NamedElement):
	def __init__(self, xml_element):
		NamedElement.__init__(self, xml_element)
		value_element = xml_element.getElementsByTagName('value')[0]
		val_type = value_element.getAttribute('type')
		raw_value = value_element.firstChild.data.strip()
		if val_type == 'integer':
			self.value = int(raw_value)
		else:
			self.value = raw_value

class IpcObject(NamedElement):
	def __init__(self, xml_element):
		NamedElement.__init__(self, xml_element)

		self.id = 0
		self.methods = []
		self.broadcasts = []
		self.signals = []

		method_elements = xml_element.getElementsByTagName('method')
		method_id = 32 # IDs 0..31 are reserved for voodoo use

		for method_element in method_elements:
			method = IpcMethod(method_element)

			method.id = method_id
			method_id += 1

			self.methods.append(method)

		signal_elements = xml_element.getElementsByTagName('signal')

		for signal_element in signal_elements:
			self.signals.append(IpcSignalOrBroadcast(signal_element))

		broadcast_elements = xml_element.getElementsByTagName('broadcast')

		for broadcast_element in broadcast_elements:
			self.broadcasts.append(IpcSignalOrBroadcast(broadcast_element))

class IpcMethod(NamedElement, DocumentedElement):
	def __init__(self, xml_element):
		NamedElement.__init__(self, xml_element)
		DocumentedElement.__init__(self, xml_element)

		self.id = 0
		self.arguments = []
		self.return_value = None

		argument_elements = xml_element.getElementsByTagName('argument')

		for argument_element in argument_elements:
			self.arguments.append(IpcMethodArgument(argument_element))

		return_value_elements = xml_element.getElementsByTagName('return_value')
		if return_value_elements:
			self.return_value = IpcReturnValue(return_value_elements[0])

class IpcMethodArgument(NamedElement, DocumentedElement, TypedElement):
	def __init__(self, xml_element):
		NamedElement.__init__(self, xml_element)
		DocumentedElement.__init__(self, xml_element)
		TypedElement.__init__(self, xml_element)

class IpcReturnValue(DocumentedElement, TypedElement):
	def __init__(self, xml_element):
		DocumentedElement.__init__(self, xml_element)
		TypedElement.__init__(self, xml_element)

class IpcSignalOrBroadcast(NamedElement, DocumentedElement):
	def __init__(self, xml_element):
		NamedElement.__init__(self, xml_element)
		DocumentedElement.__init__(self, xml_element)

		self.id = 0
		self.return_value = None

		# id_element = xml_element.getElementsByTagName('id')[0]
		# self.id = int(id_element.firstChild.data.strip())

		return_value_elements = xml_element.getElementsByTagName('return_value')
		self.return_value = IpcReturnValue(return_value_elements[0])

def parse_xml(file):
    #load the xml file
    doc = xml.dom.minidom.parse(file)
    ipc_element = doc.getElementsByTagName('ipc')[0]
    return IpcFoo(ipc_element)


# Python program to create a list of tuples from given list having number and its cube in each tuple

'''
Input: list = [9, 5, 6]
Output: [(9, 729), (5, 125), (6, 216)]
'''

test_list = [9, 5, 6]

res_list = [ (n, pow(n,3)) for n in test_list]
print(res_list)


#!/usr/bin/env python
__author__ = 'MidnightInAPythonWorld'

# Check for Python3
import sys
if sys.version_info[0] != 3:
    print("[-] This script requires Python 3")
    print("[-] Exiting script")
    exit()

# stdlib
import json,os,requests,argparse

# Check for Pandas
try:
    import pandas as pd
except:
    print("[-] This script requires Pandas to be installed.")
    print("[-] Exiting script")
    exit()

def query_grey_noise(api_key,api_params):
    """
    This function will accept API Key (provided via argpaser) and Params from user input.
    Documentation for this API are located here: https://docs.greynoise.io/#greynoise-api-gnql
    """
    api_headers = {
            'Accept' : 'application/json' ,
            'Accept-Language' : 'en-US' ,
            'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko' ,
            'Accept-Encoding' : 'gzip, deflate' ,
            'Connection' : 'Keep-Alive' ,
            'key' : api_key ,
            }
    url = 'https://api.greynoise.io/v2/experimental/gnql'
    try:
        print('[*] Attempting GreyNoise API request for query: ' , api_params['query'] )
        api_requests = requests.get(url, headers = api_headers, params=api_params, timeout=15.000, verify=True)
        api_json = api_requests.json()
        print('[*] Successfully queried GreyNoise API.')
    except:
        print("[!] Failed to fetch GreyNoise API with base URL of: ", url)
    if api_json['count'] >=1:
        return api_json
    else:
        return None

def write_results_to_csv(api_data,filename):
    ''' This function will parse the data that is returned from API.
        Function is using Pandas as a quick way to write to CSV.
    '''
    for item in api_data['data']:
        del item['raw_data']
    df = pd.DataFrame(api_data['data'])
    # if file does not exist write header
    if not os.path.isfile(filename):
        df.to_csv(filename)
    else: # else it exists so append without writing the header
        df.to_csv(filename, mode='a', header=False)
    print('[*] Successfully created file: ', filename)

def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('api_key', help='The API key used to query Grey Noise API.')
    args=parser.parse_args()
    api_key = args.api_key
    api_params = {}
    api_params['query'] = input("Enter query string in GNQL format: ")
    api_params['size'] = int(input("Enter Size (max is 10000): "))
    filename = input("Enter filename to write results to: ")
    api_data = query_grey_noise(api_key,api_params)
    if api_data:
        print("[!] Search had " + str(api_data['count']) + " matches.")
        write_results_to_csv(api_data,filename)
    else:
        print("[!] Search had 0 matches.")

if __name__== "__main__":
  main()

exit()


# -*- coding: utf-8 -*-
# @Author: Jeremiah
# @Date:   2017-05-26 23:27:33
# @Last Modified by:   jemarks
# @Last Modified time: 2017-05-31 20:13:15

#This file exists in order to provider some basic objects for SRs, SPs, Stores, and backstop reports.

import datetime
import os
import pandas
import collections
from petm_teams import teams
from emails import team_email
import file_man

sftp_format_string = "Petsmart_Backstop_%m-%d-%Y_at_%H.%M.xlsx"

colsInOrder = ["SR #", "Date Opened", "Days Since Open", "Priority", "SR Substatus", "SR Short Description", "LOS", "Site Area", "City", "State", "Site #", "SC Name", "TL", "SR/Activity Last Update "]
Stats = collections.namedtuple('Stats', ['new', 'continued', 'closed'])

class ServiceRequest(object):
	"""docstring for ServiceRequest"""
	def __init__(self, line_of_data, bs_ts = None):
		super(ServiceRequest, self).__init__()
		self.line_of_data = line_of_data
		self.sr = line_of_data['SR #']
		self.site = line_of_data['Site #']
		self.sp = line_of_data['SC Number']
		self.sp_name = line_of_data['SC Name']
		self.date_opened = line_of_data['Date Opened']
		self.time_open = line_of_data["Days Since Open"]
		self.priority = line_of_data["Priority"]
		self.tl = line_of_data["TL"]
		self.los = line_of_data["LOS"]
		self.short_description = line_of_data["SR Short Description"]
		self.status = line_of_data["SR Substatus"]
		self.nte = line_of_data["NTE"]
		self.ot = line_of_data['Overtime Allowed ']
		self.backstop_timestamp = bs_ts

	def __eq__(self, otherobject):
		if (type(otherobject) == type(" ")):
			return otherobject == self.sr
		else:
			return otherobject.sr == self.sr

class BackStopReport(object):
	"""docstring for BackStopReport"""
	def __init__(self, path):
		super(BackStopReport, self).__init__()
		self.path = path
		self.srs = {}
		self.backstop_timestamp = datetime.datetime.strptime(os.path.basename(self.path), sftp_format_string)
		self.jdate = file_man.get_julian_stamp(self.path)
		self.load()

	def load(self):
		self.raw_file = pandas.read_excel(self.path, sheetname=1).to_dict(orient='records')
		for record in self.raw_file:
			self.srs[record['SR #']] = ServiceRequest(record, self.backstop_timestamp)

	def compare(self, previous_backstop, further_backstops=[]):
		mysrs = list(self.srs.keys())
		previous_srs = list(previous_backstop.srs.keys())
		stats_all = self.compare_subset(mysrs, previous_srs)
		mycrits = [x.sr for x in self.srs.values() if x.priority == "Critical"]
		previous_crits = [x.sr for x in previous_backstop.srs.values() if x.priority == "Critical"]
		stats_crits = self.compare_subset(mycrits, previous_crits)
		stats_tl = collections.defaultdict(list)
		crits_tl = collections.defaultdict(list)
		for teamlead in teams:
			this_tl = [x.sr for x in self.srs.values() if x.tl == teamlead]
			previous_tl = [x.sr for x in previous_backstop.srs.values() if x.tl == teamlead]
			this_tl_crits = [x.sr for x in self.srs.values() if x.tl == teamlead and x.priority == "Critical"]
			previous_tl_crits = [x.sr for x in previous_backstop.srs.values() if x.tl == teamlead and x.priority == "Critical"]
			stats_tl[teamlead] = self.compare_subset(this_tl, previous_tl)
			crits_tl[teamlead] = self.compare_subset(this_tl_crits, previous_tl_crits)
		# print(team_email.overviewTable(stats_all, stats_crits, stats_tl, crits_tl))
		return stats_all, stats_crits, stats_tl, crits_tl

	def compare_subset(self, subset1, subset2):
		# subset1 = list(subset1.keys())
		# subset2 = list(subset2.keys())
		srs_continued=[]
		srs_closed=[]
		srs_new=[]
		for each_sr in subset1:
			if each_sr in subset2:
				srs_continued.append(each_sr)
			else:
				srs_new.append(each_sr)
		for each_sr in subset2:
			if each_sr not in subset1:
				srs_closed.append(each_sr)

		return Stats(new=srs_new, continued=srs_continued, closed=srs_closed)


import tornado.ioloop
import tornado.web
import requests
import argparse

class MainHandler(tornado.web.RequestHandler):
	def get(self, slug):
		url = "http://osu.ppy.sh/api/{}?".format(slug)

		# Build URL with all get params
		for i in self.request.arguments:
			url += "{}={}&".format(i, self.get_argument(i))

		# Remove last &/? if needed
		url = url[:len(url)-1]

		# Send request to osu!api and get response
		try:
			resp = requests.get(url).text
			print("API request: api/{}".format(slug))
			self.write(resp)
		except:
			self.send_error()
			print("Error while getting osu!api response")
			raise

class GeneralHandler(tornado.web.RequestHandler):
	def get(self, what, slug):
		# Build URL
		url = "http://osu.ppy.sh/{}/{}".format(what, slug)

		# Send request to osu!api and get response
		try:
			resp = requests.get(url).text
			self.write(resp)
			print("General request: {}/{}".format(what, slug))
		except:
			self.send_error()
			print("Error while getting web response")
			raise

if __name__ == "__main__":
	# CLI stuff
	__author__ = "Nyo"
	parser = argparse.ArgumentParser(description="osu!api proxy for local ripple servers")
	parser.add_argument('-p','--port', help="osu!api proxy server port", required=False)
	args = parser.parse_args()

	# Get port from arguments
	if (args.port != None):
		serverPort = args.port
	else:
		serverPort = 5003

	# Start server
	print("osu!api proxy listening on 127.0.0.1:{}...".format(serverPort))
	app = tornado.web.Application([(r"/api/(.*)", MainHandler), (r"/(.*)/(.*)", GeneralHandler)])
	app.listen(serverPort)
	tornado.ioloop.IOLoop.current().start()