from osmclient.common import utils
from osmclient.common.exceptions import ClientException
from osmclient.common.exceptions import NotFound
import yaml
import json

class Vim(object):
    def __init__(self, http=None, client=None):
        self._http = http
        self._client = client
        self._apiName = '/admin'
        self._apiVersion = '/v1'
        self._apiResource = '/vim_accounts'
        self._apiBase = '{}{}{}'.format(self._apiName,
                                        self._apiVersion, self._apiResource)
    def create(self, name, vim_access, sdn_controller=None, sdn_port_mapping=None):
        if 'vim-type' not in vim_access:
            #'openstack' not in vim_access['vim-type']):
            raise Exception("vim type not provided")

        vim_account = {}
        vim_account['name'] = name
        vim_account = self.update_vim_account_dict(vim_account, vim_access)

        vim_config = {}
        if 'config' in vim_access and vim_access['config'] is not None:
            vim_config = yaml.safe_load(vim_access['config'])
        if sdn_controller:
            sdnc = self._client.sdnc.get(sdn_controller)
            vim_config['sdn-controller'] = sdnc['_id']
        if sdn_port_mapping:
            with open(sdn_port_mapping, 'r') as f:
                vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
        if vim_config:
            vim_account['config'] = vim_config
            #vim_account['config'] = json.dumps(vim_config)

        http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
                                       postfields_dict=vim_account)
        #print 'HTTP CODE: {}'.format(http_code)
        #print 'RESP: {}'.format(resp)
        if http_code in (200, 201, 202, 204):
            if resp:
                resp = json.loads(resp)
            if not resp or 'id' not in resp:
                raise ClientException('unexpected response from server - {}'.format(
                                      resp))
            print(resp['id'])
        else:
            msg = ""
            if resp:
                try:
                    msg = json.loads(resp)
                except ValueError:
                    msg = resp
            raise ClientException("failed to create vim {} - {}".format(name, msg))

    def update(self, vim_name, vim_account, sdn_controller, sdn_port_mapping):
        vim = self.get(vim_name)

        vim_config = {}
        if 'config' in vim_account:
            if vim_account.get('config')=="" and (sdn_controller or sdn_port_mapping):
                raise ClientException("clearing config is incompatible with updating SDN info")
            if vim_account.get('config')=="":
                vim_config = None
            else:
                vim_config = yaml.safe_load(vim_account['config'])
        if sdn_controller:
            sdnc = self._client.sdnc.get(sdn_controller)
            vim_config['sdn-controller'] = sdnc['_id']
        if sdn_port_mapping:
            with open(sdn_port_mapping, 'r') as f:
                vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
        vim_account['config'] = vim_config
        #vim_account['config'] = json.dumps(vim_config)
        http_code, resp = self._http.put_cmd(endpoint='{}/{}'.format(self._apiBase,vim['_id']),
                                       postfields_dict=vim_account)
        #print 'HTTP CODE: {}'.format(http_code)
        #print 'RESP: {}'.format(resp)
        if http_code in (200, 201, 202, 204):
            if resp:
                resp = json.loads(resp)
            if not resp or 'id' not in resp:
                raise ClientException('unexpected response from server - {}'.format(
                                      resp))
            print(resp['id'])
        else:
            msg = ""
            if resp:
                try:
                    msg = json.loads(resp)
                except ValueError:
                    msg = resp
            raise ClientException("failed to update vim {} - {}".format(vim_name, msg))

    def update_vim_account_dict(self, vim_account, vim_access):
        vim_account['vim_type'] = vim_access['vim-type']
        vim_account['description'] = vim_access['description']
        vim_account['vim_url'] = vim_access['vim-url']
        vim_account['vim_user'] = vim_access['vim-username']
        vim_account['vim_password'] = vim_access['vim-password']
        vim_account['vim_tenant_name'] = vim_access['vim-tenant-name']
        return vim_account

    def get_id(self, name):
        """Returns a VIM id from a VIM name
        """
        for vim in self.list():
            if name == vim['name']:
                return vim['uuid']
        raise NotFound("vim {} not found".format(name))

    def delete(self, vim_name, force=False):
        vim_id = vim_name
        if not utils.validate_uuid4(vim_name):
            vim_id = self.get_id(vim_name)
        querystring = ''
        if force:
            querystring = '?FORCE=True'
        http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
                                         vim_id, querystring))
        #print 'HTTP CODE: {}'.format(http_code)
        #print 'RESP: {}'.format(resp)
        if http_code == 202:
            print('Deletion in progress')
        elif http_code == 204:
            print('Deleted')
        else:
            msg = ""
            if resp:
                try:
                    msg = json.loads(resp)
                except ValueError:
                    msg = resp
            raise ClientException("failed to delete vim {} - {}".format(vim_name, msg))

    def list(self, filter=None):
        """Returns a list of VIM accounts
        """
        filter_string = ''
        if filter:
            filter_string = '?{}'.format(filter)
        resp = self._http.get_cmd('{}{}'.format(self._apiBase,filter_string))
        if not resp:
            return list()
        vim_accounts = []
        for datacenter in resp:
            vim_accounts.append({"name": datacenter['name'], "uuid": datacenter['_id']
                        if '_id' in datacenter else None})
        return vim_accounts

    def get(self, name):
        """Returns a VIM account based on name or id
        """
        vim_id = name
        if not utils.validate_uuid4(name):
            vim_id = self.get_id(name)
        resp = self._http.get_cmd('{}/{}'.format(self._apiBase,vim_id))
        if not resp or '_id' not in resp:
            raise ClientException('failed to get vim info: '.format(
                                  resp))
        else:
            return resp
        raise NotFound("vim {} not found".format(name))


# -*- coding:utf-8 -*-
# title           :岩石
# description     :岩石
# author          :Python超人
# date            :2023-02-11
# link            :https://gitcode.net/pythoncr/
# python_version  :3.8
# ==============================================================================
from objs.obj import Obj

class Rock(Obj):
    """
    岩石
    """

    def __init__(self, name="岩石", mass=5.97237e24,
                 init_position=[0, 0, 0],
                 init_velocity=[0, 0, 0],
                 texture="rock1.png", size_scale=1.0, distance_scale=1.0,
                 ignore_mass=False, density=1e3, color=(7, 0, 162),
                 trail_color=None, show_name=False,
                 model="rock1.obj", rotation=(0, 0, 0),
                 parent=None, gravity_only_for=[]):
        params = {
            "name": name,
            "mass": mass,
            "init_position": init_position,
            "init_velocity": init_velocity,
            "density": density,
            "color": color,
            "texture": texture,
            "size_scale": size_scale,
            "distance_scale": distance_scale,
            "ignore_mass": ignore_mass,
            "trail_color": trail_color,
            "show_name": show_name,
            "parent": parent,
            "rotation": rotation,
            "gravity_only_for": gravity_only_for,
            "model": model
        }
        super().__init__(**params)

# 对岩石进行缩放，保证 create_rock 保证创建的岩石大小差异不会过大
ROCK_SIZE_SCALE_FACTOR = {
    6: 0.5,
    7: 1e-2
}

def create_rock(no: int = None, **kwargs):
    if no is not None:
        kwargs["model"] = f"rock{no}.obj"
        kwargs["texture"] = f"rock{no}.png"
    if "size_scale" in kwargs:
        kwargs["size_scale"] = kwargs["size_scale"] * ROCK_SIZE_SCALE_FACTOR.get(no, 1.0)
    else:
        kwargs["size_scale"] = ROCK_SIZE_SCALE_FACTOR.get(no, 1.0)

    rock = Rock(**kwargs)
    # print(rock)
    return rock

if __name__ == '__main__':
    for i in range(10):
        rock = create_rock(no=i % 8 + 1, name=f'岩石{i + 1}')
        print(rock)


import numpy.ctypeslib as ctl
import ctypes
import numpy as np
import cv2
import time
import glob

displayRes = 1
pygears_impl = True

libname = 'detect.so'
libdir = './'
lib = ctl.load_library(libname, libdir)

filenames = [img for img in glob.glob("dataset/resized/*jpg")]
img_num = 0
res = np.zeros(shape=(1, 1024), dtype='u4')

stop_time = 0
exec_time = 0
for img_index, img_fn in enumerate(filenames):
    start_time = time.time()
    img = cv2.imread(img_fn, 0)
    img = img.astype('u4')
    img[-1][-1] = 65535
    pos = []

    detect = lib.detect

    detect.argtypes = [
        ctl.ndpointer(np.uint32, flags='aligned, c_contiguous'),
        ctl.ndpointer(np.uint32, flags='aligned, c_contiguous')
    ]

    stop_time = time.time()
    # print("--- SW Time --------- %s s ---" % (stop_time - start_time))
    start_time = time.time()
    res_num = detect(img, res)
    stop_time = time.time()
    # print("IMG number ", img_index)
    # print(res[0,:res_num-1])
    exec_time += stop_time - start_time
    print(f"---{img_num} HW Time --------- %s s ---" % (stop_time - start_time))
    img_num += 1

    for val in res[0,:res_num-1]:
        if pygears_impl is True:
            scale = (val & 0x0000000F)
            pos_x = (val & 0x00003FF0) >> 4
            pos_y = (val & 0x00FFC000) >> 14
        else:
            pos_y = (val & 0x000001FF)
            pos_x = (val & 0x0001FE00) >> 9
            scale = (val & 0x001E0000) >> 17

        # print(scale, pos_y, pos_x)
        pos.append((scale, pos_y, pos_x))

        if pygears_impl is False:
            pos = pos[:-2]

    if displayRes:
        img_clr = cv2.imread(img_fn)
        for val in pos:
            scale_tmp = 1.33**val[0]
            cv2.rectangle(img_clr, (int(val[1]*scale_tmp), int(val[2]*scale_tmp)),
                        (int(val[1]*scale_tmp) + int(25*scale_tmp), int(val[2]*scale_tmp) + int(25*scale_tmp)),
                        (0, 255, 0), 2)

    cv2.imshow('img', img_clr)
    c = cv2.waitKey(0)
    if c == 27:
        break
    cv2.destroyAllWindows()

print("--- TOTAl Time --------- %s s ---" % (exec_time))
print("--- AVG Time --------- %s ms ---" % (exec_time / img_num * 1000))
print("---- FPS ------- %.2f  fps ----" % float(img_num / float(exec_time)))


"""
Defines an explicit solver supporting various methods

.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""

from typing import Callable, Tuple

import numpy as np

from ..fields.base import FieldBase
from ..pdes.base import PDEBase
from ..tools.numba import jit
from .base import SolverBase

class ExplicitSolver(SolverBase):
    """class for solving partial differential equations explicitly"""

    name = "explicit"

    dt_min = 1e-10
    dt_max = 1e10

    def __init__(
        self,
        pde: PDEBase,
        scheme: str = "euler",
        backend: str = "auto",
        adaptive: bool = False,
        tolerance: float = 1e-4,
    ):
        """
        Args:
            pde (:class:`~pde.pdes.base.PDEBase`):
                The instance describing the pde that needs to be solved
            scheme (str):
                Defines the explicit scheme to use. Supported values are 'euler' and
                'runge-kutta' (or 'rk' for short).
            backend (str):
                Determines how the function is created. Accepted  values are 'numpy` and
                'numba'. Alternatively, 'auto' lets the code decide for the most optimal
                backend.
            adaptive (bool):
                When enabled, the time step is adjusted during the simulation using the
                error tolerance set with `tolerance`.
            tolerance (float):
                The error tolerance used in adaptive time stepping. This is used in
                adaptive time stepping to choose a time step which is small enough so
                the truncation error of a single step is below `tolerance`.
        """
        super().__init__(pde)
        self.scheme = scheme
        self.backend = backend
        self.adaptive = adaptive
        self.tolerance = tolerance

    def _make_fixed_euler_stepper(
        self, state: FieldBase, dt: float
    ) -> Callable[[np.ndarray, float, int], Tuple[float, float]]:
        """make a simple Euler stepper with fixed time step

        Args:
            state (:class:`~pde.fields.base.FieldBase`):
                An example for the state from which the grid and other information can
                be extracted
            dt (float):
                Time step of the explicit stepping.

        Returns:
            Function that can be called to advance the `state` from time `t_start` to
            time `t_end`. The function call signature is `(state: numpy.ndarray,
            t_start: float, steps: int)`
        """
        # obtain post-step action function
        modify_after_step = jit(self.pde.make_modify_after_step(state))

        if self.pde.is_sde:
            # handle stochastic version of the pde
            rhs_sde = self._make_sde_rhs(state, backend=self.backend)

            def stepper(
                state_data: np.ndarray, t_start: float, steps: int
            ) -> Tuple[float, float]:
                """compiled inner loop for speed"""
                modifications = 0.0
                for i in range(steps):
                    # calculate the right hand side
                    t = t_start + i * dt
                    evolution_rate, noise_realization = rhs_sde(state_data, t)
                    state_data += dt * evolution_rate
                    if noise_realization is not None:
                        state_data += np.sqrt(dt) * noise_realization
                    modifications += modify_after_step(state_data)

                return t + dt, modifications

            self.info["stochastic"] = True
            self._logger.info(
                f"Initialized explicit Euler-Maruyama stepper with dt=%g", dt
            )

        else:
            # handle deterministic version of the pde
            rhs_pde = self._make_pde_rhs(state, backend=self.backend)

            def stepper(
                state_data: np.ndarray, t_start: float, steps: int
            ) -> Tuple[float, float]:
                """compiled inner loop for speed"""
                modifications = 0
                for i in range(steps):
                    # calculate the right hand side
                    t = t_start + i * dt
                    state_data += dt * rhs_pde(state_data, t)
                    modifications += modify_after_step(state_data)

                return t + dt, modifications

            self.info["stochastic"] = False
            self.info["adaptive"] = False
            self._logger.info(f"Initialized explicit Euler stepper with dt=%g", dt)

        return stepper

    def _make_adaptive_euler_stepper(
        self, state: FieldBase, dt: float
    ) -> Callable[[FieldBase, float, float], float]:
        """make a simple adaptive Euler stepper

        Args:
            state (:class:`~pde.fields.base.FieldBase`):
                An example for the state from which the grid and other information can
                be extracted
            dt (float):
                Initial time step of the explicit stepping.

        Returns:
            Function that can be called to advance the `state` from time `t_start` to
            time `t_end`. The function call signature is `(state: numpy.ndarray,
            t_start: float, t_end: float)`
        """
        if self.pde.is_sde:
            raise RuntimeError(
                "Cannot use adaptive Euler stepper with stochastic equation"
            )

        # obtain post-step action function
        modify_after_step = jit(self.pde.make_modify_after_step(state))

        # handle deterministic version of the pde using an adaptive stepper
        rhs_pde = self._make_pde_rhs(state, backend=self.backend)
        tolerance = self.tolerance
        self.info["dt_last"] = dt
        self.info["stochastic"] = False
        self.info["adaptive"] = True

        dt_min = self.dt_min
        dt_min_err = f"Time step below {dt_min}"
        dt_max = self.dt_max

        def inner_stepper(
            state_data: np.ndarray, t_start: float, t_end: float, dt_init: float
        ) -> Tuple[float, float, int, float]:
            """compiled inner loop for speed"""
            modifications = 0.0
            dt = dt_init
            t = t_start
            steps = 0
            while t < t_end:
                # single step with dt
                rate = rhs_pde(state_data, t)
                k1 = state_data + dt * rate

                # double step with half the dt
                k2 = state_data + 0.5 * dt * rate
                k2 += 0.5 * dt * rhs_pde(k2, t + 0.5 * dt)

                # calculate maximal error
                error = 0.0
                for i in range(state_data.size):
                    error = max(error, abs(k1.flat[i] - k2.flat[i]))
                error *= dt  # error estimate should be independent of magnitude of dt

                # do the step if the error is sufficiently small
                if error <= tolerance:
                    t += dt
                    steps += 1
                    state_data[:] = k2
                    modifications += modify_after_step(state_data)

                # adjust the time step
                dt *= min(max(0.9 * (tolerance / error) ** 0.2, 0.1), 4.0)
                if dt > dt_max:
                    dt = dt_max
                elif dt < dt_min:
                    raise RuntimeError(dt_min_err)

            return t, dt, steps, modifications

        if self.info["backend"] == "numba":
            inner_stepper = jit(inner_stepper)  # compile inner stepper

        def stepper(state: FieldBase, t_start: float, t_end: float) -> float:
            """use Euler stepping to advance `state` from `t_start` to `t_end`"""
            t_last, dt, steps, modifications = inner_stepper(
                state.data, t_start, t_end, dt_init=self.info["dt_last"]
            )
            self.info["dt_last"] = dt
            self.info["steps"] += steps
            self.info["state_modifications"] += modifications
            return t_last

        self._logger.info(f"Initialized adaptive Euler stepper with dt_0={dt}")
        return stepper

    def _make_rk45_stepper(
        self, state: FieldBase, dt: float
    ) -> Callable[[np.ndarray, float, int], Tuple[float, float]]:
        """make a simple stepper for the explicit Runge-Kutta method of order 5(4)

        Args:
            state (:class:`~pde.fields.base.FieldBase`):
                An example for the state from which the grid and other information can
                be extracted
            dt (float):
                Time step of the explicit stepping.

        Returns:
            Function that can be called to advance the `state` from time `t_start` to
            time `t_end`. The function call signature is `(state: numpy.ndarray,
            t_start: float, steps: int)`
        """
        if self.pde.is_sde:
            raise RuntimeError(
                "Cannot use Runge-Kutta stepper with stochastic equation"
            )

        rhs = self._make_pde_rhs(state, backend=self.backend)
        self.info["stochastic"] = False
        self.info["adaptive"] = self.adaptive

        # obtain post-step action function
        modify_after_step = jit(self.pde.make_modify_after_step(state))

        def stepper(
            state_data: np.ndarray, t_start: float, steps: int
        ) -> Tuple[float, float]:
            """compiled inner loop for speed"""
            modifications = 0.0
            for i in range(steps):
                # calculate the right hand side
                t = t_start + i * dt

                # calculate the intermediate values in Runge-Kutta
                k1 = dt * rhs(state_data, t)
                k2 = dt * rhs(state_data + 0.5 * k1, t + 0.5 * dt)
                k3 = dt * rhs(state_data + 0.5 * k2, t + 0.5 * dt)
                k4 = dt * rhs(state_data + k3, t + dt)

                state_data += (k1 + 2 * k2 + 2 * k3 + k4) / 6
                modifications += modify_after_step(state_data)

            return t + dt, modifications

        self._logger.info(f"Initialized explicit Runge-Kutta-45 stepper with dt=%g", dt)

        return stepper

    def _make_rkf_stepper(
        self, state: FieldBase, dt: float
    ) -> Callable[[FieldBase, float, float], float]:
        """make a simple stepper for the explicit Runge-Kutta-Fehlberg method

        Args:
            state (:class:`~pde.fields.base.FieldBase`):
                An example for the state from which the grid and other information can
                be extracted
            dt (float):
                Initial time step of the explicit stepping.

        Returns:
            Function that can be called to advance the `state` from time `t_start` to
            time `t_end`. The function call signature is `(state: numpy.ndarray,
            t_start: float, t_end: float)`
        """
        if self.pde.is_sde:
            raise RuntimeError(
                "Cannot use Runge-Kutta-Fehlberg stepper with stochastic equation"
            )

        rhs = self._make_pde_rhs(state, backend=self.backend)
        self.info["stochastic"] = False
        self.info["adaptive"] = self.adaptive
        self.info["dt_last"] = dt

        # obtain post-step action function
        modify_after_step = jit(self.pde.make_modify_after_step(state))

        # use Runge-Kutta-Fehlberg method
        tolerance = self.tolerance
        dt_min = self.dt_min
        dt_min_err = f"Time step below {dt_min}"
        dt_max = self.dt_max

        # define coefficients for RK4(5), formula 2 Table III in Fehlberg
        a2 = 1 / 4
        a3 = 3 / 8
        a4 = 12 / 13
        a5 = 1.0
        a6 = 1 / 2

        b21 = 1 / 4
        b31 = 3 / 32
        b32 = 9 / 32
        b41 = 1932 / 2197
        b42 = -7200 / 2197
        b43 = 7296 / 2197
        b51 = 439 / 216
        b52 = -8.0
        b53 = 3680 / 513
        b54 = -845 / 4104
        b61 = -8 / 27
        b62 = 2.0
        b63 = -3544 / 2565
        b64 = 1859 / 4104
        b65 = -11 / 40

        r1 = 1 / 360
        # r2 = 0
        r3 = -128 / 4275
        r4 = -2197 / 75240
        r5 = 1 / 50
        r6 = 2 / 55

        c1 = 25 / 216
        # c2 = 0
        c3 = 1408 / 2565
        c4 = 2197 / 4104
        c5 = -1 / 5

        def inner_stepper(
            state_data: np.ndarray, t_start: float, t_end: float, dt_init: float
        ) -> Tuple[float, float, int, float]:
            """compiled inner loop for speed"""
            modifications = 0.0
            dt = dt_init
            t = t_start
            steps = 0
            while t < t_end:
                steps += 1

                # do the six intermediate steps
                k1 = dt * rhs(state_data, t)
                k2 = dt * rhs(state_data + b21 * k1, t + a2 * dt)
                k3 = dt * rhs(state_data + b31 * k1 + b32 * k2, t + a3 * dt)
                k4 = dt * rhs(state_data + b41 * k1 + b42 * k2 + b43 * k3, t + a4 * dt)
                k5 = dt * rhs(
                    state_data + b51 * k1 + b52 * k2 + b53 * k3 + b54 * k4, t + a5 * dt
                )
                k6 = dt * rhs(
                    state_data + b61 * k1 + b62 * k2 + b63 * k3 + b64 * k4 + b65 * k5,
                    t + a6 * dt,
                )

                # estimate the maximal error
                error = 0.0
                for i in range(state_data.size):
                    error_local = abs(
                        r1 * k1.flat[i]
                        + r3 * k3.flat[i]
                        + r4 * k4.flat[i]
                        + r5 * k5.flat[i]
                        + r6 * k6.flat[i]
                    )
                    error = max(error, error_local)  # type: ignore

                # do the step if the error is sufficiently small
                if error <= tolerance:
                    t += dt
                    state_data += c1 * k1 + c3 * k3 + c4 * k4 + c5 * k5
                    modifications += modify_after_step(state_data)

                # adjust the time step
                dt *= min(max(0.9 * (tolerance / error) ** 0.2, 0.1), 4.0)
                if dt > dt_max:
                    dt = dt_max
                elif dt < dt_min:
                    raise RuntimeError(dt_min_err)

            return t, dt, steps, modifications

        if self.info["backend"] == "numba":
            inner_stepper = jit(inner_stepper)  # compile inner stepper

        def stepper(state: FieldBase, t_start: float, t_end: float) -> float:
            """use Euler stepping to advance `state` from `t_start` to `t_end`"""
            t_last, dt, steps, modifications = inner_stepper(
                state.data, t_start, t_end, dt_init=self.info["dt_last"]
            )
            self.info["dt_last"] = dt
            self.info["steps"] += steps
            self.info["state_modifications"] += modifications
            return t_last

        self._logger.info(
            f"Initialized Runge-Kutta-Fehlberg stepper with initial dt={dt}"
        )
        return stepper

    def make_stepper(
        self, state: FieldBase, dt=None
    ) -> Callable[[FieldBase, float, float], float]:
        """return a stepper function using an explicit scheme

        Args:
            state (:class:`~pde.fields.base.FieldBase`):
                An example for the state from which the grid and other information can
                be extracted
            dt (float):
                Time step of the explicit stepping. If `None`, this solver specifies
                1e-3 as a default value.

        Returns:
            Function that can be called to advance the `state` from time `t_start` to
            time `t_end`. The function call signature is `(state: numpy.ndarray,
            t_start: float, t_end: float)`
        """
        # support `None` as a default value, so the controller can signal that
        # the solver should use a default time step
        if dt is None:
            dt = 1e-3
            if not self.adaptive:
                self._logger.warning(
                    "Explicit stepper with a fixed time step did not receive any "
                    f"initial value for `dt`. Using dt={dt}, but specifying a value or "
                    "enabling adaptive stepping is advisable."
                )

        self.info["dt"] = dt
        self.info["steps"] = 0
        self.info["scheme"] = self.scheme
        self.info["state_modifications"] = 0.0

        if self.pde.is_sde and self.adaptive:
            self._logger.warning(
                "Stochastic stepping cannot be adaptive. Using fixed time step instead."
            )

        if self.adaptive and not self.pde.is_sde:
            # create stepper with adaptive dt
            self.info["dt_adaptive"] = True

            if self.scheme == "euler":
                adaptive_stepper = self._make_adaptive_euler_stepper(state, dt)
            elif self.scheme in {"runge-kutta", "rk", "rk45"}:
                adaptive_stepper = self._make_rkf_stepper(state, dt)
            else:
                raise ValueError(
                    f"Explicit adaptive scheme {self.scheme} is not supported"
                )

            return adaptive_stepper

        else:
            # create stepper with fixed dt
            self.info["dt_adaptive"] = False

            if self.scheme == "euler":
                inner_stepper = self._make_fixed_euler_stepper(state, dt)
            elif self.scheme in {"runge-kutta", "rk", "rk45"}:
                inner_stepper = self._make_rk45_stepper(state, dt)
            else:
                raise ValueError(f"Explicit scheme {self.scheme} is not supported")

            if self.info["backend"] == "numba":
                inner_stepper = jit(inner_stepper)  # compile inner stepper

            def fixed_stepper(state: FieldBase, t_start: float, t_end: float) -> float:
                """advance `state` from `t_start` to `t_end` using fixed dt"""
                # calculate number of steps (which is at least 1)
                steps = max(1, int(np.ceil((t_end - t_start) / dt)))
                t_last, modifications = inner_stepper(state.data, t_start, steps)
                self.info["steps"] += steps
                self.info["state_modifications"] += modifications
                return t_last

            return fixed_stepper


import sys
# 주어진 시작시간과 끝나는 시간들을 이용해서 가장 많은 회의의 수를 알기 위해서는
# 빨리 끝나는 회의 순서대로 정렬을 해야 한다.
# 이유는 간단하다. 빨리 끝날수록 뒤에서 고려해볼 회의가 많기 때문이다.
# 빨리 시작하는 순서대로 정렬을 우선 한다면, 오히려 늦게 끝날 수 있기 때문이다.
N = int(input())
meeting_line = []
for i in range(N):
    meeting_line.append(list(map(int, sys.stdin.readline().split())))
meeting_line.sort(key=lambda x: [x[1], x[0]])
last = 0
result = 0
for i, j in meeting_line:
    if i >= last:
        result += 1
        last = j
print(result)

백준문제/그리디/1931_회의실 배정.py


from math import radians
import pieper as pp
import craig as cg
import numpy as np
from sympy import sin, cos

def ntu_pieper():
    # warnings.filterwarnings('ignore')
    # from inverse_kinematic import trig_equ
    dh_tbl = np.array([[0, 0, 0],
                       [radians(-90), -30, 0],
                       [0, 340, 0],
                       [radians(-90), -40, 338],
                       [radians(90), 0, 0],
                       [radians(-90), 0, 0]], dtype=np.float64)

    cg.setDhTbl(dh_tbl)

    ty = radians(-60)  # rotate y axis
    tcup_0_2s = np.array([[cos(ty), 0, sin(ty), 330], [0, 1, 0, 372],
                          [-sin(ty), 0, cos(ty), 367], [0, 0, 0, 1]], dtype=np.float64)
    Tcup_6 = np.array([[0, 0, 1, 0], [0, -1, 0, 0], [1, 0, 0, 206],
                       [0, 0, 0, 1]])

    t6_0 = tcup_0_2s @ np.linalg.inv(Tcup_6)
    # t6_0=  np.round(t6_0.astype(np.double), 3)

    p = pp.pieper(t6_0)

ntu_pieper()

"""
q3: -11.98, 178.48
q2: -64.46, 20.37
q1: 58.61
q4: 25.30, -154.70
q5: -87.13, 87.13
q6: -56.19, 123.81
"""


# Created on 2020/8/10

# This module is for analysing and classifying time series and other objects.

# Standard library imports
from datetime import datetime
from datetime import timedelta
import random as random

# Third party imports
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.cluster import KMeans
from sklearn.metrics import log_loss
from sklearn.metrics import silhouette_samples
from sklearn.model_selection._split import KFold

# Local application imports
from .. import timeseries

#---------#---------#---------#---------#---------#---------#---------#---------#---------#

# DISTANCES

def euclidean_distance(ts1, ts2):
    """
    Returns the Euclidean distance between two TimeSeries.

    Parameters
    ----------
    ts1 : TimeSeries
      First time series.
    ts2 : TimeSeries
      Second time series.

    Returns
    -------
    float
      Euclidean distance between time series.
    """

    # Checks
    try:
        assert(ts1.type=='TimeSeries' and ts2.type=='TimeSeries')
    except TypeError:
        raise TypeError("Series have to be of type TimeSeries.")

    try:
        assert(ts1.data.index.tolist() == ts2.data.index.tolist())
    except IndexError:
        raise IndexError("Time series do not have the same index.")

    # Return distance
    squares = (ts1.data - ts2.data)**2
    return np.sqrt(float(squares.sum()))

def dtw_distance(ts1, ts2, window=None):
    """
    Returns the Dynamic Time Warping (DTW) distance between two TimeSeries.
    A locality constraint can be used by specifying the size of a window.

    Parameters
    ----------
    ts1 : TimeSeries
      First time series.
    ts2 : TimeSeries
      Second time series.
    window : int
      Size of restrictive search window.

    Returns
    -------
    float
      DTW distance between time series.

    Notes
    -----
      To learn more about DTW, please refer to:
      https://en.wikipedia.org/wiki/Dynamic_time_warping

      Notice that taking a small window size may lead to
      a wrong estimate of the real dynamic time warping distance.
    """

    # Checks
    try:
        assert(ts1.type=='TimeSeries' and ts2.type=='TimeSeries')
    except TypeError:
        raise TypeError("Series have to be of type TimeSeries.")

    # Initializations
    N1 = len(ts1.data.index.tolist())
    N2 = len(ts2.data.index.tolist())
    if window is not None:
        assert(isinstance(window, int))
        w = window
    else:
        w = N2

    dtw = np.full(shape=(N1+1,N2+1), fill_value=np.inf)
    dtw[0,0] = 0

    # Loop
    for i in range(0, N1, 1):
        # for j in range(0, N2, 1):
        for j in range(max(0,int(i-w)), min(N2,int(i+w)), 1):
            square = (ts1.data.values[i] - ts2.data.values[j])**2
            dtw[i+1,j+1] = square + min(dtw[i,j+1], dtw[i+1,j], dtw[i,j])

    # Return distance
    return np.sqrt(dtw[N1, N2])

# KMEANS CLUSTERING

def kmeans_base_clustering(corr, names_features=None, max_num_clusters=10, n_init=10):
    """
    Perform base clustering with Kmeans.

    Arguments
    ---------
    corr: numpy.array
      Correlation matrix.
    names_features : list of str
      List of names for features.
    max_num_clusters: int
      Maximum number of clusters.
    n_init : int
      Initial value n_init for KMeans.

    Returns
    -------
    pd.DataFrame
      Clustered correlation matrix.
    dictionary
      List of clusters and their content.
    pd.Series
      Silhouette scores.

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """

    # Checks
    if not isinstance(max_num_clusters, int):
        raise AssertionError("max_num_clusters must be integer.")
    if not isinstance(n_init, int):
        raise AssertionError("n_init must be integer.")

    # Initializations
    corr = pd.DataFrame(data=corr, index=names_features, columns=names_features)
    silh_score = pd.Series()

    # Define the observations matrix X
    X = ((1 - corr.fillna(0))/2.)**.5

    # Loop to generate different initializations
    for init in range(n_init):

        # Loop to generate different numbers of clusters
        for i in range(2, max_num_clusters+1):

            # Define model and fit
            kmeans_ = KMeans(n_clusters=i, n_jobs=1, n_init=n_init).fit(X)

            # Compute silhouette coefficients
            silh_ = silhouette_samples(X, kmeans_.labels_)

            # Compute clustering quality q (t-statistic of silhouette score)
            stat = (silh_.mean()/silh_.std(), silh_score.mean()/silh_score.std())
            if np.isnan(stat[1]) or (stat[0]>stat[1]):
                silh_score, kmeans = silh_, kmeans_

    # Extract index according to sorted labels
    new_idx = np.argsort(kmeans.labels_)

    # Reorder rows
    clustered_corr = corr.iloc[new_idx]
    # Reorder columns
    clustered_corr = clustered_corr.iloc[:,new_idx]

    # Form clusters
    clusters = {i: clustered_corr.columns[np.where(kmeans.labels_==i)[0]].tolist() for i in np.unique(kmeans.labels_)}

    # Define a series with the silhouette score
    silh_score = pd.Series(silh_score, index=X.index)

    return clustered_corr, clusters, silh_score

def make_new_outputs(corr, clusters, clusters2):
    """
    Makes new outputs for kmeans_advanced_clustering().

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """
    clusters_new = {}
    for i in clusters.keys():
        clusters_new[len(clusters_new.keys())] = list(clusters[i])
    for i in clusters2.keys():
        clusters_new[len(clusters_new.keys())] = list(clusters2[i])

    new_idx = [j for i in clusters_new for j in clusters_new[i]]
    corr_new = corr.loc[new_idx, new_idx]
    x = ((1-corr.fillna(0))/2.)**.5

    kmeans_labels = np.zeros(len(x.columns))
    for i in clusters_new.keys():
        idxs = [x.index.get_loc(k) for k in clusters_new[i]]
        kmeans_labels[idxs] = i

    silh_new = pd.Series(silhouette_samples(x, kmeans_labels), index=x.index)

    return corr_new, clusters_new, silh_new

def kmeans_advanced_clustering(corr, names_features=None, max_num_clusters=None, n_init=10):
    """
    Perform advanced clustering with Kmeans.
    The base clustering is used first, then clusters quality is evaluated.
    For clusters whose quality less than the averaged quality,
    the clustering is reran.

    Arguments
    ---------
    corr: numpy.array
      Correlation matrix.
    names_features : list of str
      List of names for features.
    max_num_clusters: int
      Maximum number of clusters.
    n_init : int
      Initial value n_init for KMeans.

    Returns
    -------
    pd.DataFrame
      Clustered correlation matrix.
    dictionary
      List of clusters and their content.
    pd.Series
      Silhouette scores.

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """

    # Checks
    if (max_num_clusters is not None) and (not isinstance(max_num_clusters, int)):
        raise AssertionError("max_num_clusters must be integer.")
    if not isinstance(n_init, int):
        raise AssertionError("n_init must be integer.")

    # Initializations
    if max_num_clusters==None:
        max_num_clusters = corr.shape[1]-1
    # Using base clustering as initial step
    corr1, clusters, silh = kmeans_base_clustering(corr,
                                                   names_features=names_features,
                                                   max_num_clusters=min(max_num_clusters, corr.shape[1]-1),
                                                   n_init=n_init)

    # Compute t-stat for each cluster
    cluster_tstats = {i: np.mean(silh[clusters[i]]) / np.std(silh[clusters[i]]) for i in clusters.keys()}
    # Obtain the mean over clusters
    tstat_mean = sum(cluster_tstats.values()) / len(cluster_tstats)
    # Select the clusters which have a t-stat below the mean
    redo_clusters = [i for i in cluster_tstats.keys() if cluster_tstats[i] < tstat_mean]

    # Only one cluster
    if len(redo_clusters)<=1:
        return corr1, clusters, silh
    # More than one cluster
    else:
        keys_redo = [j for i in redo_clusters for j in clusters[i]]
        corr_tmp = corr.loc[keys_redo, keys_redo]
        tstat_mean = np.mean([cluster_tstats[i] for i in redo_clusters])
        corr2, clusters2, silh2 = kmeans_advanced_clustering(corr_tmp, max_num_clusters=min(max_num_clusters, corr_tmp.shape[1]-1), n_init=n_init)

        # Make new outputs, if necessary
        corr_new, clusters_new, silh_new = make_new_outputs(corr, {i: clusters[i] for i in clusters.keys() if i not in redo_clusters}, clusters2)
        new_tstat_mean = np.mean([ np.mean(silh_new[clusters_new[i]]) / np.std(silh_new[clusters_new[i]]) for i in clusters_new.keys() ])

        if new_tstat_mean <= tstat_mean:
            return corr1, clusters, silh
        else:
            return corr_new, clusters_new, silh_new

# FEATURE IMPORTANCE

def generate_random_classification(n_features, n_informative, n_redundant, n_samples, random_state=0, sigma_std=0.):
    """
    Generate a random dataset for a classification problem.

    Arguments
    ---------
    n_features : int
      Total number of features.
    n_informative : int
      Number of informative features.
    n_redundant : int
      Number of redundant features.
    n_samples : int
      Number of samples.
    random_state : int
      See random state.
    sigma_std: float
      Standard deviation of added noise.

    Returns
    -------
    pandas.DataFrame
      Data Frame with features as columns and samples as rows.
    pandas.Series
      Series containing class membership.

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """

    # Checks
    for arg in [('n_features',n_features), ('n_informative',n_informative), ('n_redundant',n_redundant),
                ('n_samples',n_samples), ('random_state',random_state)]:
        if not isinstance(arg[1],int):
            raise AssertionError(arg[0] + " must be integer.")
    if not isinstance(arg[1], float) and not isinstance(arg[1], int):
        raise AssertionError("sigma_std must be float.")

    # Initializations
    np.random.seed(random_state)

    # Generate classification
    X, y = make_classification(n_samples = n_samples,
                               n_features = n_features - n_redundant,
                               n_informative = n_informative,
                               n_redundant = 0,
                               shuffle = False,
                               random_state = random_state)

    # Informed explanatory variables
    cols = ['I_' + str(i) for i in range(n_informative)]

    # Noise explanatory variables
    cols += ['N_' + str(i) for i in range(n_features - n_informative - n_redundant)]

    X = pd.DataFrame(X, columns=cols)
    y = pd.Series(y)
    i = np.random.choice(range(n_informative), size=n_redundant)

    # Redundant explanatory variables
    for k, j in enumerate(i):
        X['R_' + str(k)] = X['I_' + str(j)] + np.random.normal(size=X.shape[0]) * sigma_std

    return X, y

def feature_importance_pvalues(fit, plot=False, figsize=(10,10)):
    """
    Plot the p-values of features from a fit.

    Arguments
    ---------
    fit : fit model
      Fit already apply on data.
    plot : bool
      Option to plot feature importance.
    figsize : (float, float)
      Dimensions of the plot.

    Returns
    -------
    pandas.DataFrame
      Data frame with features importance.
    """

    # Extract p-values and sort them
    pvals = fit.pvalues.sort_values(ascending=False)

    # Plot
    if plot is True:
        plt.figure(figsize=figsize)
        plt.title("P-values of features.")
        plt.barh(y=pvals.index, width=pvals.values)
        plt.show()

    # Make DataFrame
    pvals_df = pd.DataFrame(pvals)
    pvals_df.index.name = "Feature"
    pvals_df.columns = ["Importance"]

    return pvals_df

def feature_importance_mdi(classifier, X, y, plot=False, figsize=(10,10)):
    """
    Feature importance based on in-sample Mean-Decrease Impurity (MDI).

    Arguments
    ---------
    classifier : tree classifier
      Tree classifier to apply on data.
    X : pandas.DataFrame
      Data Frame with features as columns and samples as rows.
    y : pandas.Series
      Series containing class membership.
    plot : bool
      Option to plot feature importance.
    figsize : (float, float)
      Dimensions of the plot.

    Returns
    -------
    pandas.DataFrame
      Data frame with features importance.

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """

    # Checks
    if not isinstance(X, pd.DataFrame):
        raise AssertionError("X must be pandas.DataFrame.")
    if not isinstance(y, pd.Series):
        raise AssertionError("y must be pandas.Series.")

    # Fit
    fit = classifier.fit(X,y)

    # Extract feature importance
    df0 = {i: tree.feature_importances_ for i, tree in enumerate(fit.estimators_)}

    # Make Data Frame
    df0 = pd.DataFrame.from_dict(df0, orient='index')
    df0.columns = X.columns
    df0 = df0.replace(0, np.nan)
    fimp_df = pd.concat( {'Importance Mean': df0.mean(), 'Importance Std': df0.std() * df0.shape[0]**(-0.5)}, axis=1)
    fimp_df /= fimp_df['Importance Mean'].sum()
    fimp_df.index.name = "Feature"

    # Sort values
    sorted_fimp = fimp_df.sort_values(by='Importance Mean')

    # Plot
    if plot is True:
        plt.figure(figsize=figsize)
        plt.title("Feature importance based on in-sample Mean-Decrease Impurity (MDI).")
        plt.barh(y=sorted_fimp.index, width=sorted_fimp['Importance Mean'], xerr=sorted_fimp['Importance Std'])
        plt.show()

    return fimp_df

def feature_importance_mda(classifier, X, y, n_splits=10, plot=False, figsize=(10,10)):
    """
    Feature importance based out-of-sample Mean-Decrease Accuracy (MDA).

    Arguments
    ---------
    classifier : tree classifier
      Tree classifier to apply on data.
    X : pandas.DataFrame
      Data Frame with features as columns and samples as rows.
    y : pandas.Series
      Series containing class membership.
    plot : bool
      Option to plot feature importance.
    figsize : (float, float)
      Dimensions of the plot.

    Returns
    -------
    pandas.DataFrame
      Data frame with features importance.

    Notes
    -----
      Function adapted from "Machine Learning for Asset Managers",
      Marcos López de Prado (2020).
    """

    # Checks
    if not isinstance(X, pd.DataFrame):
        raise AssertionError("X must be pandas.DataFrame.")
    if not isinstance(y, pd.Series):
        raise AssertionError("y must be pandas.Series.")

    # Generate K-fold cross validation
    cv_gen = KFold(n_splits=n_splits)
    scr0 = pd.Series()
    scr1 = pd.DataFrame(columns=X.columns)

    # Loop over the folds:
    for i, (train, test) in enumerate(cv_gen.split(X=X)):

        # Train/Test split
        X0, y0 = X.iloc[train,:], y.iloc[train]
        X1, y1 = X.iloc[test,:], y.iloc[test]

        # Fit
        fit = classifier.fit(X=X0, y=y0)

        # Prediction before shuffling
        prob = fit.predict_proba(X1)
        scr0.loc[i] = -log_loss(y1, prob, labels=classifier.classes_)

        for j in X.columns:
            X1_ = X1.copy(deep=True)

            # Shuffle one column
            np.random.shuffle(X1_[j].values)

            # Prediction after shuffling
            prob = fit.predict_proba(X1_)
            scr1.loc[i,j] = -log_loss(y1, prob, labels=classifier.classes_)

    fimp_df = (-1*scr1).add(scr0, axis=0)
    fimp_df = fimp_df / (-1*scr1)
    fimp_df = pd.concat({'Importance Mean': fimp_df.mean(), 'Importance Std': fimp_df.std()*fimp_df.shape[0]**-.5}, axis=1)

    # Sort values
    sorted_fimp = fimp_df.sort_values(by='Importance Mean')

    # Plot
    if plot is True:
        plt.figure(figsize=figsize)
        plt.title("Feature importance based on out-of-sample Mean-Decrease Accuracy (MDA).")
        plt.barh(y=sorted_fimp.index, width=sorted_fimp['Importance Mean'], xerr=sorted_fimp['Importance Std'])
        plt.show()

    return sorted_fimp

#---------#---------#---------#---------#---------#---------#---------#---------#---------#


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import msgpack

# pip install py-algorand-sdk
from algosdk.future.transaction import PaymentTxn

from config import account_mnemonic
from connect import algod_client
from account import Account

def wait_for_confirmation(client, txid):
    """
    Utility function to wait until the transaction is confirmed before
    proceeding.
    """
    last_round = client.status().get("last-round")
    txinfo = client.pending_transaction_info(txid)

    while not txinfo.get("confirmed-round", -1) > 0:
        print(f"Waiting for transaction {txid} confirmation.")
        last_round += 1
        client.status_after_block(last_round)
        txinfo = client.pending_transaction_info(txid)

    print(f"Transaction {txid} confirmed in round {txinfo.get('confirmed-round')}.")
    return txid, txinfo

def send_transaction(sender, receiver, client):
    params = client.suggested_params()
    params.flat_fee = True
    params.fee = 1000  # microalgos

    note = msgpack.packb({"eventType": "PyRoma", "greeting": "Hello, you all!"})

    amount = 42  # microalgos
    unsigned_txn = PaymentTxn(
        sender.address,
        params,
        receiver.address,
        amount,
        close_remainder_to=None,
        note=note,
    )

    signed_txn = unsigned_txn.sign(sender.private_key)  # Sign txn
    client.send_transactions([signed_txn])  # Send txn

    tx_id = signed_txn.transaction.get_txid()
    return wait_for_confirmation(client, tx_id)

def main():
    sender = Account.from_mnemonic(account_mnemonic)
    receiver = sender  # This will be a transaction to self âž°

    txid, _ = send_transaction(sender, receiver, algod_client)
    print(f"ðŸŒŽ Explore it here: https://testnet.algoexplorer.io/tx/{txid}")

if __name__ == "__main__":
    main()


from sqlalchemy import MetaData, Table, Column, String, PrimaryKeyConstraint
from optimus_db.db_connect import create_db_session

# Create a MetaData instance
metadata = MetaData()

# Create a table
env_variables = Table(
   'env_variables', metadata,
   Column('ninja_key', String),
   Column('ninja_value', String),
   PrimaryKeyConstraint('ninja_key', name='ninja_key')
)

if __name__ == "__main__":
    with create_db_session() as session:
        metadata.create_all(session.get_bind())


# Exercise

# Define a class Student
# With instance variable names below
# rollno, name, semester, branch

class Student:

    def __init__(self, name):
        self.name = name;

name = input("Enter student name:")
s1 = Student(name)
print("Student name is",s1.name)


from typing import List, TypedDict

import torch

class ModelInputs(TypedDict):
    input_ids: torch.Tensor
    attention_mask: torch.Tensor

def split(inputs: ModelInputs, n_microbatches: int) -> List[ModelInputs]:
    assert n_microbatches > 0, f"n_microbatches must be greater than 0, got {n_microbatches}"
    assert "input_ids" in inputs, f"inputs must have 'input_ids' key, got {inputs.keys()}"
    assert "attention_mask" in inputs, f"inputs must have 'attention_mask' key, got {inputs.keys()}"
    assert (
        inputs["input_ids"].size(0) % n_microbatches == 0
    ), f"The batch size must be divisible by n_microbatches, got {inputs['input_ids'].size(0)} and {n_microbatches}"

    input_ids_microbatches = torch.split(inputs["input_ids"], n_microbatches)
    attention_mask_microbatches = torch.split(inputs["attention_mask"], n_microbatches)

    microbatches = []
    for input_ids, attention_mask in zip(input_ids_microbatches, attention_mask_microbatches):
        microbatches.append(ModelInputs(input_ids=input_ids, attention_mask=attention_mask))

    return microbatches


class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        # f = defaultdict(dict)
        # vis = [0] * n
        # for s,d,c in flights:
        #     f[s][d] = c
        # heap = [(0,src,k+1)]
        # while heap:
        #     total, s, k = heapq.heappop(heap)
        #     if s == dst:
        #         return total
        #     if vis[s] != 0:
        #         continue
        #     vis[s] = k
        #     for inside_dic in f[s]:
        #         heapq.heappush(heap, (total+f[s][inside_dic], inside_dic, k - 1))
        # return -1
        graph = collections.defaultdict(list)
        pq = []
        visited = [0] * n
        for u, v, w in flights:
            graph[u].append((w, v))

        heapq.heappush(pq, (0, k+1, src))
        while pq:
            price, stops, city = heapq.heappop(pq)

            if city is dst:
                return price
            if visited[city] >=stops:
                continue
            visited[city] = stops
            if stops>0:
                for price_to_nei, nei in graph[city]:
                    heapq.heappush(pq, (price+price_to_nei, stops-1, nei))
        return -1


numbers = []

while True:
    num = int(input())
    if num == 0:
        break
    numbers.append(num)

# Print the numbers in reverse order
for i in range(len(numbers)-1, -1, -1):
    print(numbers[i])


from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from crowdfunding.models import ProjectInvestment
from crowdfunding.tasks import handle_add_campaign
from bot.tests.tweet import main
import logging

logger = logging.getLogger(__name__)

def count():
    total = ProjectInvestment.objects.count()
    if not total:
        return "Table ProjectInvestment is empty."
    has_campaign = ProjectInvestment.objects.filter(
        campaign__isnull=False
    ).count()
    has_campaign_percent = round(has_campaign/total*100)
    return (
        f'Total:{total}\n'
        f'Campaign set:{has_campaign} ({has_campaign_percent}%)\n'
        f'Campaign empty:{total-has_campaign} ({100-has_campaign_percent}%)\n'
    )

class Command(BaseCommand):
    help = "Add the correct Campaign field to all ProjectInvestment objects."

    def handle(self, *args, **options):
        self.stdout.write(self.style.WARNING(f'{count()}'))
        for pi in ProjectInvestment.objects.all():
            handle_add_campaign(str(pi.uuid))
        self.stdout.write(self.style.SUCCESS(f'{count()}'))


from __future__ import unicode_literals

from django.db import models

from flows.models import Flow

from .constants import ProjectStates

class Project(models.Model):
    '''
    This represents a single project. Each project can have multiple flows.
    with multiple nesting. The outcome of each flow will define the next
    flow that needs to be executed for a particular task.
    '''
    name        = models.CharField(max_length=128)
    entry       = models.ForeignKey(Flow, blank=True, null=True, related_name='entry_for')
    state       = models.CharField(max_length=3,
            choices=ProjectStates.choices(), default=ProjectStates.NEW)
    processors  = models.ManyToManyField('Processor', related_name='projects')

    created_on  = models.DateTimeField(auto_now_add=True)
    updated_on  = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.name

class Processor(models.Model):
    name    = models.CharField(max_length=128)

    created_on  = models.DateTimeField(auto_now_add=True)
    updated_on  = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.name


from dictionary import Dictionary
import numpy as np
from sparse_code import Sparse_code
import pickle

def evaluate_model(dataset, predictions, dictionary):
	'''Gives the classification accuracy'''

	subIDX = np.unique(dataset.labels_gallery)
	n_sbj = len(subIDX)
	n_patches = dataset.n_patch

	correct = 0
	labels = dataset.labels_test
	n_imgs = len(predictions)

	for i in range(n_imgs):
		if i==0:
			lbls = labels[i*n_patches]
		else:
			lbls = np.append(lbls, labels[i*n_patches])

	for i in range(len(predictions)):
		true_label = lbls[i].astype(int)
		ID = predictions[i][0].astype(int)

		if true_label == ID:
			correct = correct + 1

	accuracy = float(correct)/len(predictions)

	return accuracy*100

# --------------------------------------- MAIN Function ----------------------------------------------------------------------

def main():

	data_path = 'data/lfw_158_sbj.pkl'
	dict_path = 'data/lfw_158_sbj_dictionary.pkl'

	print('\nLoading data from disk... ')
	with open(data_path, 'rb') as input_file:
		dataset = pickle.load(input_file)

	info = dataset.get_data_info()
	print(info)
	print('Number of sbjs considered: ' + str(dataset.num_sbj))

	# Dictionary Learning --------------------------------------------------------------------------------------------------

	print('\nBuilding Dictionaries...')
	dictionaries = Dictionary()

	dictionaries.dict_learn(Y=dataset.gallery_lda, N=dataset.num_sbj, n_patch=dataset.n_patch, max_iter=10, init_method='data', sparsity=6)

	with open(dict_path, "wb") as output_file:
		print('\nSaving Dictionary to disk...')
		pickle.dump(dictionaries, output_file, protocol=pickle.HIGHEST_PROTOCOL)
		print('Done... Saved to: ' + dict_path)

	#Classification ----------------------------------------------------------------------------------------------

	print('\nClassifying...')
	sc = Sparse_code()
	IDs = sc.klimaps_classify_learned_dict(dataset, dictionaries)

	print('\nNumber of images: ' + str(len(IDs)))

	accuracy = evaluate_model(dataset, IDs, dictionaries)

	print('\nAccuracy: ' + str(accuracy) + '%')

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import argparse
import HTSeq
import sys

## get backsplice read IDs from the
## circular_expression/circrna_analyze/counts/bks.counts.collected_reads.csv
## file with the following bash command
## grep -v read_id bks.counts.collected_reads.csv | cut -f5 -d","| sed 's/"//g'| sort | uniq >  read_ids.txt

def get_reads_by_ids(reads, ids, invert = False):
    ''' **reads must be a HTSeq.FastqReader object, **ids is simply a set of \
        strings representing the read ids you want to get. \
        Returns a list of HTSeq.SequenceWithQualities objects.\
        Set 'invert' to True if you want to exclude the given read IDs.\
    '''

    out = []
    for read in reads:

        if (read.name.split()[0].rstrip() in ids) == (not invert):
            out.append(read)

    return out

if __name__ == '__main__':

    ## Handle parameter arguments
    parser = argparse.ArgumentParser(description="Handle FASTQ files: get \
            reads in FASTQ format from a file of reads given the list of read \
            ids you want.")

    parser.add_argument('-f', '--fastq-file', action='store', dest="fastq_file",\
            required=True, type=file, help='the FASTQ file containing the reads\
            to select from')

    parser.add_argument('-l', '--ids-list-file', action='store',\
            dest="ids_list_file", required=True, type=file, help="a file \
            containing the list of read ids to select, one id per line.")

    parser.add_argument('-v', '--invert', action='store_true',\
            dest="invert", required=False, default=False,
            help="Invert the sense of matching: if set, this option cause \
            the input read IDs to be excluded from the output")

    parser.add_argument('-e','--quality-encoding', action='store',\
            dest="quality_encoding", required=False, default='phred',\
            type=str, choices=['solexa', 'solexa-old', 'phred'], help="the \
            quality encoding used in the FASTQ file")

    args = parser.parse_args()

    ## Program logic
    fastq_file = HTSeq.FastqReader(args.fastq_file, args.quality_encoding)

    ids = set([item.rstrip() for item in args.ids_list_file.readlines()])

    reads = get_reads_by_ids(fastq_file, ids, args.invert)

    for r in reads:
        r.write_to_fastq_file(sys.stdout)


# -*- ecoding: utf-8 -*-
# @ModuleName: run_ranking_example
# @Author: jeremy
# @Email: jeremydzwang@126.com
# @Time: 2022/6/20 11:40 PM

import torch
import torch.nn as nn
import torch.nn.functional as F
from ..layers import LGConv

class lightgcn(nn.Module):
    def __init__(self, num_nodes, embedding_dim, num_layers):
        super(lightgcn,self).__init__()

        self.num_nodes = num_nodes
        self.embedding_dim = embedding_dim
        self.num_layers = num_layers
        self.loss_fun = nn.MSELoss()

        alpha = 1. / (num_layers + 1)
        self.alpha = torch.tensor([alpha] * (num_layers + 1))

        self.embedding = nn.Embedding(num_nodes, embedding_dim)
        self.convs = nn.ModuleList([LGConv() for _ in range(num_layers)])
        self.decoder = torch.nn.Sequential(nn.Linear(2 * embedding_dim, embedding_dim),
                                           nn.ReLU(), nn.Linear(embedding_dim, 1))
        self.reset_parameters()

    def reset_parameters(self):
        self.embedding.reset_parameters()

    def get_embedding(self, edge_index):
        x = self.embedding.weight # 输入特征
        out = x * self.alpha[0]

        for i in range(self.num_layers):
            x = self.convs[i](x, edge_index)
            out = out + x * self.alpha[i + 1]
        return out

    def forward(self, edge_index, edge_label_index, edge_label):
        """预测节点对的rating"""
        out = self.get_embedding(edge_index) # 每个节点的embedding
        out_src = out[edge_label_index[0]] # 起始节点的embedding
        out_dst = out[edge_label_index[1]] # 终止节点的embedding
        pred = self.decoder(torch.cat([out_src, out_dst], dim=-1)).to(torch.float32)
        target = edge_label.view(-1, 1).to(torch.float32)
        loss = self.loss_fun(pred, target)

        result = dict()
        result['pred'] = pred
        result['loss'] = loss

        return result


peso = float(input("Quantos quilos de peixes: "))
multa = 4

excesso_peso = peso + multa

if peso <= 50:
    print("O peso: {}, esta acima do permitido do regulamento do estado de SP, por isso vai acrescentar o valor de: {}, valor total: {}".format(peso, multa, excesso_peso))


# Torch
import torch
from torch.utils.data import Dataset

# Torchvision
import torchvision.transforms as transforms

# General
import os
import json
import numpy as np

# Image libs
from PIL import Image, ImageOps
import matplotlib.pyplot as plt

IMAGE_FORMATS = (".png", ".PNG", ".jpg", ".JPG")

# -----------------------------------------------------------------------------
def load_json(fname):
    with open(fname) as f:
        out = json.load(f)
    return out

# -----------------------------------------------------------------------------
def clean_dir(dir_name):
    if len(os.listdir(dir_name)) > 0:
        files = os.listdir(dir_name)
        for f in files:
            os.remove(os.path.join(dir_name, f))

# -----------------------------------------------------------------------------
def dict_to_str(dict_var):
    output_str = ""
    for key, value in dict_var.items():
        if output_str:
            output_str += f"_{key}_{value}"
        else:
            output_str += f"{key}_{value}"
    return output_str

# -----------------------------------------------------------------------------
def fetch_dataset_files(dir: list, exclude_suffixes: list) -> list:
    """
    Build list of training data. Each data sample is a dict that contains the
    path to the input image and to the corresponding ground truth.
    """
    file_list = []
    for path, _, files in os.walk(dir):
        for name in files:
            filename = os.path.join(path, name)
            if name.endswith(IMAGE_FORMATS) and not any(
                map(name.__contains__, exclude_suffixes)
            ):
                file_list.append({"image": filename, "label": path.split(os.sep)[-1]})
    return file_list

# -----------------------------------------------------------------------------
def show_sample(sample, debug_fname):
    """
    Plot dataset sample.
    """
    image = np.array(transforms.ToPILImage()(sample["image"].squeeze(0))) / 255.0
    plt.figure()
    plt.imshow(image)
    plt.axis("off")
    plt.title(f"Class {sample['label_str']}")
    plt.tight_layout()
    plt.savefig(debug_fname, bbox_inches="tight", pad_inches=0)

# -----------------------------------------------------------------------------
class BirdsDataset(Dataset):
    """
    DSP dataset class.
    """

    def __init__(
        self,
        file_list: list,
        target_shape: int,
        num_classes: int,
        ordered_class_names: list,
        do_data_augmentation: bool,
    ) -> None:
        self.file_list = file_list
        self.target_shape = target_shape
        self.do_data_augmentation = do_data_augmentation
        self.num_classes = num_classes
        self.ordered_class_names = ordered_class_names

    # Returns size of dataset
    def __len__(self) -> int:
        return len(self.file_list)

    # Pre processing
    @staticmethod
    def pre_processing(img: Image, target_img_mode: str, target_shape: int) -> Image:
        if target_img_mode is not None:
            if target_img_mode == "GRAYSCALE":
                img = ImageOps.grayscale(img)
            else:
                img = img.convert(target_img_mode)

        # Resize image
        img = transforms.Resize(size=(target_shape, target_shape))(img)

        return img

    # Data augmentation
    @staticmethod
    def data_augmentation(image: Image) -> Image:
        # Color jitter
        j1 = transforms.ColorJitter(brightness=0, contrast=0, saturation=0.5, hue=0)
        j2 = transforms.ColorJitter(brightness=0, contrast=0.5, saturation=0, hue=0)
        j3 = transforms.ColorJitter(brightness=0.5, contrast=0, saturation=0, hue=0)
        jitter_transform = transforms.RandomChoice([j1, j2, j3])

        # Sharpner
        sharpner_transform = transforms.RandomAdjustSharpness(sharpness_factor=2)

        # Equalizer
        equalizer_transform = transforms.RandomEqualize()

        # Affine
        affine_transform = transforms.RandomAffine(
            degrees=(-30, 30), translate=(0.2, 0.2), shear=(-10, 10)
        )

        # Flip
        hflip_transform = transforms.RandomHorizontalFlip()
        vflip_transform = transforms.RandomVerticalFlip()

        # Apply random transforms
        applier = transforms.RandomApply(
            transforms=[
                jitter_transform,
                sharpner_transform,
                equalizer_transform,
                hflip_transform,
                vflip_transform,
                affine_transform,
            ],
            p=0.5,
        )
        image = applier(image)

        # Gaussian noise
        noise_prob = np.random.uniform(0, 1)
        if noise_prob > 0.5:
            image = (np.array(image) / 255).astype(np.float32)
            mean = 0.0
            std = 0.05
            image = image + np.random.normal(mean, std, image.shape)
            image = np.clip(image, 0, 1)  # we might get out of bounds so clip
            image = Image.fromarray(np.uint8(image * 255))

        return image

    # Gets dataset item
    def __getitem__(self, idx: int) -> dict:
        # Fetch data point
        data_pt = self.file_list[idx]

        # Read image and basic pre-processing
        image = Image.open(data_pt["image"])
        image = self.pre_processing(image, "RGB", self.target_shape)

        # Do data augmentation
        if self.do_data_augmentation:
            image = self.data_augmentation(image)

        # Fetch label
        label_id = int(self.ordered_class_names.index(data_pt["label"]))
        label_one_hot_encoded = torch.zeros(self.num_classes)
        label_one_hot_encoded[label_id] = 1

        # Create tensors
        image = transforms.ToTensor()(image)
        image = image.float()

        sample = {
            "image": image,
            "label_one_hot": label_one_hot_encoded,
            "label_str": data_pt["label"],
        }

        return sample


import logging
import mimetypes
import traceback

from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives, mail_admins
from django.db import models
from django.dispatch import receiver
from django_mailbox.signals import message_received
from rest_framework.authtoken.models import Token

from .models import TaskStore
from .tasks import process_email_message, autoconfigure_taskd

logger = logging.getLogger(__name__)

@receiver(
    models.signals.post_save,
    sender=User,
    dispatch_uid='generate_taskstore'
)
def create_taskstore_for_user(sender, instance, **kwargs):
    # This just makes sure that the task store exists.
    TaskStore.get_for_user(instance)
    Token.objects.get_or_create(user=instance)

@receiver(
    models.signals.post_save,
    sender=TaskStore,
    dispatch_uid='configure_taskstore'
)
def autoconfigure_taskstore_for_user(sender, instance, **kwargs):
    autoconfigure_taskd.apply_async(
        args=(instance.pk, ),
        countdown=5,
    )

@receiver(message_received, dispatch_uid='incoming_email')
def handle_incoming_message(sender, message, **kwargs):
    process_email_message.apply_async(args=(message.pk, ))

@receiver(message_received, dispatch_uid='forwardable_email')
def handle_incoming_forwardable_message(sender, message, **kwargs):
    for address in message.to_addresses:
        if address in settings.MAIL_FORWARDING:
            try:
                email = EmailMultiAlternatives(
                    subject=u' '.join([
                        u'[Inthe.AM]',
                        message.subject,
                        u'(%s)' % message.pk,
                    ]),
                    body=message.text,
                    to=[settings.MAIL_FORWARDING[address]],
                    reply_to=[message.from_header],
                    headers={
                        'IntheAM-Message-Id': message.pk
                    }
                )
                email.attach_alternative(
                    message.html,
                    'text/html',
                )
                for attachment in message.attachments.all():
                    email.attach(
                        attachment.get_filename(),
                        attachment.document.read(),
                        mimetypes.guess_type(
                            attachment.get_filename(),
                        )[0]
                    )
                email.send()
            except:
                mail_admins(
                    u"Error processing forwarding rule for %s" % address,
                    u"See message ID %s.\n\n%s" % (
                        message.pk,
                        traceback.format_exc(),
                    )
                )


from lxml import html
import requests
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# For SSL
port = 465

# Create a secure SSL context
context = ssl.create_default_context()

sender = "blantonswebscraper@gmail.com"
receiver = "jamesmcfadden111@gmail.com"
email = MIMEMultipart('test')
email["Subject"] = "Test email"
email["From"] = sender
email["To"] = receiver
test_str = "this string was inserted in the email body"
email_body = "This is a test " + test_str + " more email body"

email_content = MIMEText(email_body ,'html')
email.attach(email_content)
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login("blantonswebscraper@gmail.com", "")
    server.sendmail(sender, 'jamesmcfadden111@gmail.com', email.as_string())

print("email sent")


"""
Tic Tac Toe Player
"""

import math

X = "X"
O = "O"
EMPTY = None

def initial_state():
    """
    Returns starting state of the board.
    """
    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]

def player(board):
    """
    Returns player who has the next turn on a board.
    """
    countX = 0
    countO = 0
    for row in range(len(board)):
        for col in range(len(board[0])):
            if board[row][col] == X:
                countX += 1
            elif board[row][col] == O:
                countO += 1
    return X if countX == countO else O

def actions(board):
    """
    Returns set of all possible actions (i, j) available on the board.
    """
    possible_moves = set()
    for row in range(len(board)):
        for col in range(len(board[0])):
            if board[row][col] == EMPTY:
                possible_moves.add((row, col))

    return possible_moves

def result(board, action):
    """
    Returns the board that results from making move (i, j) on the board.
    """
    (x, y) = action
    # print(action)
    if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]):
        raise IndexError

    actionArray = [row[ : ] for row in board]
    actionArray[x][y] = player(board)

    return actionArray

def winner(board):
    """s
    Returns the winner of the game, if there is one.
    """
    if checkRows(board, X) or checkColumns(board, X) or checkTopToBottomDiagonal(board, X) or checkBottomToTopDiagonal(board, X):
        return X
    elif checkRows(board, O) or checkColumns(board, O) or checkTopToBottomDiagonal(board, O) or checkBottomToTopDiagonal(board, O):
        return O
    else:
        return None

def checkRows(board, player):
    for rows in range(len(board)):
        count = 0
        for col in range(len(board[0])):
            if board[rows][col] == player:
                count += 1
            if count == len(board[0]):
                return True
    return False

def checkColumns(board, player):
    for cols in range(len(board[0])):
        count = 0
        for row in range(len(board)):
            if board[row][cols] == player:
                count += 1
    return count == len(board[0])

def checkTopToBottomDiagonal(board, player):
    count = 0
    for row in range(len(board[0])):
        for col in range(len(board[0])):
            if row == col and board[row][col] == player:
                count += 1

    return count == len(board[0])

def checkBottomToTopDiagonal(board, player):
    count = 0
    for row in range(len(board)):
        for col in range(len(board[0])):
            if (len(board) - row - 1) == col and board[row][col] == player:
                count += 1

    return count == len(board[0])

def isTie(board):
    countEmpty = (len(board) * len(board[0]))
    for row in range(len(board)):
        for col in range(len(board[0])):
            if board[row][col] is not EMPTY:
                countEmpty -= 1
    return countEmpty == 0

def terminal(board):
    """
    Returns True if game is over, False otherwise.
    """
    if winner(board) or isTie(board):
        return True
    else:
        return False

def utility(board):
    """
    Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
    """
    if winner(board) == X:
        return 1
    elif winner(board) == O:
        return -1
    else:
        return 0

def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    if terminal(board):
        return None
    elif player(board) == X:
        arr = []
        for action in actions(board):
            arr.append([min_value(result(board, action)), action])
        return sorted(arr, key=lambda x: x[0], reverse=True)[0][1]
    elif player(board) == O:
        arr = []
        for action in actions(board):
            arr.append([max_value(result(board, action)), action])
        return sorted(arr, key=lambda x: x[0])[0][1]

def max_value(board):
    if terminal(board):
        return utility(board)
    v = float("-inf")
    for action in actions(board):
        v = max(v, min_value(result(board, action)))
    return v

def min_value(board):
    if terminal(board):
        return utility(board)
    v = float("inf")
    for action in actions(board):
        v = min(v, max_value(result(board, action)))
    return v


from picamera import PiCamera
import time

from grove.button import Button
from grove.grove_ryb_led_button import GroveLedButton

camera = PiCamera()

def capture():
    now = int(time.time())
    camera.capture(f'/home/pi/Pictures/{now}.jpg')

def main():
    print("Initializing")
    now = int(time.time())
    # Grove - LED Button connected to port D5
    button = GroveLedButton(16)

    def on_event(index, event, tm):
        if event & Button.EV_SINGLE_CLICK:
            print(f"Button Clicked")
            capture()

    button.on_event = on_event

    print("Registering event for button")

    while True:
        now = int(time.time())
        time.sleep(1)

if __name__ == '__main__':
    main()


import numpy as np
import bluesky as bs
from bluesky.tools import aero
from bluesky.tools.trafficarrays import TrafficArrays, RegisterElementParameters
from bluesky.traffic.performance.perfbase import PerfBase
from bluesky.traffic.performance.nap import coeff, thrust
from bluesky.traffic.performance.nap import phase as ph

class PerfNAP(PerfBase):
    """
    Open-source Nifty Aircraft Performance (NAP) Model

    Methods:
        create(): initialize new aircraft with performance parameters
        update(): update performance parameters
    """

    def __init__(self, min_update_dt=1):
        super(PerfNAP, self).__init__()

        self.min_update_dt = min_update_dt    # second, minimum update dt
        self.current_sim_time = 0       # last update simulation time
        self.ac_warning = False         # aircraft mdl to default warning
        self.eng_warning = False        # aircraft engine to default warning

        self.coeff = coeff.Coefficient()

        with RegisterElementParameters(self):
            self.engnum = np.array([])  # number of engines
            self.engthrust = np.array([])  # static engine thrust
            self.engbpr = np.array([])  # engine bypass ratio
            self.thrustratio = np.array([])  # thrust ratio at current alt spd
            self.ffidl = np.array([])  # icao fuel flows idle
            self.ffapp = np.array([])  # icao fuel flows appraoch
            self.ffco = np.array([])  # icao fuel flows climbout
            self.ffto = np.array([])  # icao fuel flows takeoff

    def create(self, n=1):
        super(PerfNAP, self).create(n)

        newactypes = []
        fficaos = []
        for actype in bs.traf.type[-n:]:
            # convert to known aircraft type
            avaliable_types = list(self.coeff.acs.keys())
            if actype not in avaliable_types:
                actype = 'A320'
            newactypes.append(actype)

            # populate fuel flow model
            es = self.coeff.acs[actype]['engines']
            e = es[list(es.keys())[0]]

            fficaos.append([e['ff_idl'], e['ff_app'], e['ff_co'], e['ff_to']])

        params = self.coeff.get_initial_values(newactypes)

        self.actype[-n:] = newactypes

        fficaos = np.array(fficaos)
        self.ffidl[-n:] = fficaos[:, 0]
        self.ffapp[-n:] = fficaos[:, 1]
        self.ffco[-n:] = fficaos[:, 2]
        self.ffto[-n:] = fficaos[:, 3]

        self.Sref[-n:] = params[:, 0]
        self.mass[-n:] = 0.5 * (params[:, 1] + params[:, 2])

        self.engnum[-n:] = params[:, 3].astype(int)
        self.engtype[-n:] = params[:, 4].astype(int)
        self.engthrust[-n:] = params[:, 5]
        self.engbpr[-n:] = params[:, 6]

    def delete(self, idx):
        super(PerfNAP, self).delete(idx)

    def update(self, simt=1):
        super(PerfNAP, self).update(simt)

        # update phase, infer from spd, roc, alt
        self.phase = ph.get(bs.traf.tas, bs.traf.vs, bs.traf.alt, unit='SI')

        # update limits, based on phase change
        limits = self.__construct_lim_matrix(self.actype, self.phase)
        self.vmin = limits[:, 0]
        self.vmax = limits[:, 1]
        self.vsmin = limits[:, 2]
        self.vsmax = limits[:, 3]
        self.hmaxalt = limits[:, 4]

        # compute thrust
        #   = number of engines x engine static thrust x thrust ratio
        self.thrustratio = thrust.compute_thrust_ratio(
            self.phase, self.engbpr, bs.traf.tas, bs.traf.alt
        )
        self.thrust = self.engnum * self.engthrust * self.thrustratio

        # compute fuel flow
        # self.fuelflow = thrust.compute_fuel_flow(
        #     self.thrustratio, self.engnum, self.ffidl, self.ffapp, self.ffco, self.ffto
        # )

        # update bank angle, due to phase change
        self.bank = np.where((self.phase==ph.TO) | (self.phase==ph.LD), 15, self.bank)
        self.bank = np.where((self.phase==ph.IC) | (self.phase==ph.CR) | (self.phase==ph.AP), 35, self.bank)

        return None

    def limits(self, indent_v, indent_vs, indent_h):
        """ apply limits on indent speed, vertical speed, and altitude """
        super(PerfNAP, self).limits(indent_v, indent_vs, indent_h)

        # if isinstance(self.vmin, np.ndarray):
        #     pass
        # else:
        #     self.update()

        indent_v = aero.vtas2cas(indent_v, indent_h)
        allow_v = np.where(indent_v < self.vmin, self.vmin, indent_v)
        allow_v = np.where(indent_v > self.vmax, self.vmax, indent_v)
        allow_v = aero.vcas2tas(indent_v, indent_h)

        allow_vs = np.where(indent_vs < self.vsmin, self.vsmin, indent_vs)
        allow_vs = np.where(indent_vs > self.vsmax, self.vsmax, indent_vs)

        allow_h = np.where(indent_h > self.hmaxalt, self.hmaxalt, indent_h)

        return allow_v, allow_vs, allow_h

    def __construct_lim_matrix(self, actypes, phases):
        """Compute limitations base on aircraft model and phases

        Args:
            actypes (String or 1D-array): aircraft type / model
            phases (int or 1D-array): aircraft flight phases

        Returns:
            2D-array: limitations [spd_min, spd_max. atl_min,
                alt_max, roc_min, roc_max]
        """

        nrow = len(actypes)
        ncol = 5

        # initialize the n_actype x 5 matrix
        limits = np.zeros((nrow, ncol))

        unique_ac_mdls = np.unique(actypes)

        for mdl in unique_ac_mdls:
            # for each aircraft type construct the speed, roc, and alt limits based on phase
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.NA), 0, limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.TO), self.coeff.limits[mdl]['vminto'], limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.IC), self.coeff.limits[mdl]['vminic'], limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & ((phases==ph.CL)|(phases==ph.CR)|(phases==ph.DE)), self.coeff.limits[mdl]['vminer'], limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.AP), self.coeff.limits[mdl]['vminap'], limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.LD), self.coeff.limits[mdl]['vminld'], limits[:, 0])
            limits[:, 0] = np.where((actypes==mdl) & (phases==ph.GD), 0, limits[:, 0])

            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.NA), self.coeff.limits[mdl]['vmaxer'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.TO), self.coeff.limits[mdl]['vmaxto'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.IC), self.coeff.limits[mdl]['vmaxic'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & ((phases==ph.CL)|(phases==ph.CR)|(phases==ph.DE)), self.coeff.limits[mdl]['vmaxer'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.AP), self.coeff.limits[mdl]['vmaxap'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.LD), self.coeff.limits[mdl]['vmaxld'], limits[:, 1])
            limits[:, 1] = np.where((actypes==mdl) & (phases==ph.GD), self.coeff.limits[mdl]['vmaxer'], limits[:, 1])

            limits[:, 2] = np.where((actypes==mdl), self.coeff.limits[mdl]['vsmin'], limits[:, 2])
            limits[:, 3] = np.where((actypes==mdl), self.coeff.limits[mdl]['vsmax'], limits[:, 3])

            limits[:, 4] = np.where((actypes==mdl), self.coeff.limits[mdl]['hmaxalt'], limits[:, 4])

        return limits

    def engchange(self, acid, engid=None):
        pass

    def acceleration(self, simdt):
        return 1.5


n = int(input("> "))
# -1 = \ ; -2 = / ; -3 = *
photo = [[0] * (2 * n + 1) for i in range(2 * n + 3)]
mid = n + 1
for i in range(0, n, 1):
    photo[mid][i * 2] = n - i
    for j in range(1, n - i + 2):
        photo[mid + j][i * 2 + j] = -1
        photo[mid - j][i * 2 + j] = -2
        if j == n - i + 1:
            photo[mid + j][i * 2 + j] = -3
            photo[mid - j][i * 2 + j] = -3

for i in range(2 * n + 3):
    for j in range(2 * n + 1):
        if photo[i][j] == 0:
            print(" ", end="")
        elif photo[i][j] == -1:
            print("\\", end="")
        elif photo[i][j] == -2:
            print("/", end="")
        elif photo[i][j] == -3:
            print("*", end="")
        else:
            print(photo[i][j], end="")
    print()


import pandas as pd
import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument('--file', type=str, required=True)
parser.add_argument('--p', type=str, default=os.getcwd())
parser.op('--file', type=str, required=True)
args = parser.parse_args()

def gettags():
    df = pd.read_csv(args.file)
    data=[]
    for i in df.values:
        data.append(i[0])
    result = ",".join(data)
    return result

print(gettags())


def fun(x):
    return x^3
print(fun(5))

z=[-4,-6,-5,-1,2,3,7,9,88]
print(z)
pos=[]
post=lambda n:n>0
for n in z:
    if(post(n)):
        pos.append(n)
        print(pos)


class Date:
    def __init__(self, day, month, year):
        """
        :param day: int
        :param month: int
        :param year: int
        """
        self.day = day
        self.month = month
        self.year = year

    def __str__(self) -> str:
        """
        :return: str
        """
        return str(self.day) + '/' + str(self.month) + '/' + str(self.year)

    def isValid(self):
        """
        :return: bool
        """
        valid = True
        if not (isinstance(self.day, int) and isinstance(self.month, int) and isinstance(self.year, int)):
            valid = False
        if (self.month in [1, 3, 5, 7, 8, 10, 12]):
            valid = self.day <= 31
        if (self.month in [4, 6, 9, 11]):
            valid = self.day <= 30
        if (self.month == 2):
            if (self.year % 4 == 0):
                valid = self.day <= 29
            else:
                valid = self.day <= 28
        if (self.month > 12):
            valid = False
        return valid

    def getNextDay(self):
        """
        :return: Date
        """
        nextDay = Date(self.day + 1, self.month, self.year)
        if (nextDay.isValid()):
            return nextDay
        else:
            nextDay = Date(1, self.month + 1, self.year)
            if (nextDay.isValid()):
                return nextDay
            else:
                return Date(1, 1, self.year + 1)

    def getNextDays(self, daysToAdd):
        """
        :param daysToAdd: int
        :return: Date
        """
        nextDays = self
        for i in range(daysToAdd):
            nextDays = nextDays.getNextDay()
        return nextDays

    def __eq__(self, obj):
        """
        :param obj: Date
        :return: bool
        """
        return self.day == obj.day and self.month == obj.month and self.year == obj.year

    def __lt__(self, obj):
        """
        :param obj: Date
        :return: bool
        """
        d1 = str(self.year).zfill(4) + str(self.month).zfill(2) + str(self.day).zfill(2)
        d2 = str(obj.year).zfill(4) + str(obj.month).zfill(2) + str(obj.day).zfill(2)
        return int(d1) < int(d2)

    def __gt__(self, obj):
        """
        :param obj: Date
        :return: bool
        """
        d1 = str(self.year).zfill(4) + str(self.month).zfill(2) + str(self.day).zfill(2)
        d2 = str(obj.year).zfill(4) + str(obj.month).zfill(2) + str(obj.day).zfill(2)
        return int(d1) > int(d2)

    def __sub__(self, obj):
        """
        :param obj: Date
        :return: int
        """
        days = 0
        found = False
        while not found:
            if self.__eq__(obj):
                found = True
            obj = obj.getNextDay()
            days = days + 1
        return days

def main():
    d = Date(31, 12, 2000)
    print(d.isValid())
    print(d.getNextDay().__str__())
    print(d.getNextDays(33).__str__())

    d1 = Date(1, 3, 2000)
    print(d.__eq__(d1))
    print(d.__lt__(d1))
    print(d.__gt__(d1))
    print(d.__sub__(d1))

if __name__ == '__main__':
    main()


class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if self.isEmpty():
            return "No items"
        return self.items.pop(0)

    def peek(self):
        if self.isEmpty():
            print("not found")
        return self.items[0]

    def size(self):
        return len(self.items)

shoes = ["Patrobas Ivan", "Ventela Public", "Compas Gazelle"]

custList = Queue()
items = Queue()

def main():
    while True:
        print("\n1. Tambah pesanan")
        print("2. Checkout")
        print("3. Cek antrian")
        print("4. Hapus antrian pertama")
        print("Masukkan pilihan anda")
        userinput = input()

        if userinput == "1":
            print("\n")
            i = 0

            while len(shoes) != i:
                print(str(i+1) + ". " + shoes[i])
                i += 1

            print("pilih pesanan")
            chooseItem = input()
            print("Masukkan nama anda")
            custName = input()
            custList.enqueue(custName)

            if chooseItem == "1":
                items.enqueue(shoes[0])
                print("Pesanan telah ditambahkan")
                main()
            elif chooseItem == "2":
                items.enqueue(shoes[1])
                print("Pesanan telah ditambahkan")
                main()
            elif chooseItem == "3":
                items.enqueue(shoes[2])
                print("Pesanan telah ditambahkan")
                main()

        elif userinput == "2":
            print("\nnama : " + custList.peek())
            print("barang : " + items.peek())
            print("Berhasil checkout....")
            main()
        elif userinput == "3":
            print("jumlah antrian saat ini : " + str(custList.size()))
            print("antrian paling depan")
            print("nama : " + custList.peek())
            print("pesanan : " + items.peek())
        elif userinput == "4":
            custList.dequeue()
            items.dequeue()
            print("berhasil menghapus antrian")
            main()

main()


from copy import deepcopy
dimension = 4
finish = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 0))

# Finds blank space
def find_zero(board):
    for i in range(dimension):
        for j in range(dimension):
            if board[i][j] == 0:
                return i, j

# Returns list of next moves
def find_next_moves(board):
    x_zero, y_zero = find_zero(board)
    moves = []
    board_list = [list(board[0]), list(board[1]), list(board[2]), list(board[3])]
    if y_zero != dimension - 1:
        list_left = deepcopy(board_list)
        list_left[x_zero][y_zero], list_left[x_zero][y_zero + 1] = \
            list_left[x_zero][y_zero + 1], list_left[x_zero][y_zero]
        tuple_left = tuple([tuple(list_left[0]), tuple(list_left[1]), tuple(list_left[2]), tuple(list_left[3])])
        moves.append(tuple_left)
    if y_zero != 0:
        list_right = deepcopy(board_list)
        list_right[x_zero][y_zero], list_right[x_zero][y_zero - 1] = \
            list_right[x_zero][y_zero - 1], list_right[x_zero][y_zero]
        tuple_right = tuple([tuple(list_right[0]), tuple(list_right[1]), tuple(list_right[2]), tuple(list_right[3])])
        moves.append(tuple_right)
    if x_zero != 0:
        list_down = deepcopy(board_list)
        list_down[x_zero - 1][y_zero], list_down[x_zero][y_zero] = \
            list_down[x_zero][y_zero], list_down[x_zero - 1][y_zero]
        tuple_down = tuple([tuple(list_down[0]), tuple(list_down[1]), tuple(list_down[2]), tuple(list_down[3])])
        moves.append(tuple_down)
    if x_zero != dimension - 1:
        list_up = deepcopy(board_list)
        list_up[x_zero + 1][y_zero], list_up[x_zero][y_zero] = \
            list_up[x_zero][y_zero], list_up[x_zero + 1][y_zero]
        tuple_up = tuple([tuple(list_up[0]), tuple(list_up[1]), tuple(list_up[2]), tuple(list_up[3])])
        moves.append(tuple_up)
    return moves

# Heuristic (manhattan distance and linear conflict)
def heuristic(board):
    score = 0
    for i in range(dimension):
        maximum = -1
        for j in range(dimension):
            value = board[i][j]
            if value != 0:
                score += abs(i - (value - 1) // dimension) + abs(j - (value - 1) % dimension)
                if ((value - 1) / dimension) == i:
                    if value > maximum:
                        maximum = value
                    else:
                        score += 2

    for i in range(dimension):
        maximum = -1
        for j in range(dimension):
            value = board[j][i]
            if value != 0 and ((value - 1) / dimension) == j:
                if value > maximum:
                    maximum = value
                else:
                    score += 2
    return score

# Check if puzzle is solved
def is_solved(board):
    return board == finish

# Returns path to the finish
def get_path(board, path):
    lead_path = [finish]

    current = finish
    while True:
        current = path[hash(current)]
        lead_path.append(current)
        if current == board:
            break

    lead_path = lead_path[::-1]
    return lead_path

# String representation of puzzle current state
def get_table_string(board):
    string = ''
    for row in board:
        for num in row:
            if len(str(num)) == 1:
                string += '   ' + str(num)
            elif len(str(num)) > 1:
                string += '  ' + str(num)
        string += '\n'
    return string


import heapq,sys
INF = sys.maxsize
def solution(n, s, a, b, fares):
    answer = INF
    graph = [[] for _ in range(n+1)]
    for fare in fares:
        x,y,fee = fare
        graph[x].append((y,fee))
        graph[y].append((x,fee))
    def dijkstra(n,s,e):
        fees = [INF] * (n+1)
        queue = []
        heapq.heappush(queue, (0, s))
        fees[s] = 0
        while queue:
            fee, start = heapq.heappop(queue)
            if fees[start] < fee:
                continue
            for g in graph[start]:
                cost = fee + g[1]
                if cost < fees[g[0]]:
                    fees[g[0]] = cost
                    heapq.heappush(queue,(cost, g[0]))
        return fees[e]
    for i in range(1,n+1):
        a_route = dijkstra(n,i,a)
        b_route = dijkstra(n,i,b)
        if i != s:
            together = dijkstra(n,s,i)
        else:
            together = 0
        answer = min(answer, a_route + b_route + together)
    return answer
# 각 인원별 최소 경로를 구한 후 공통 구간을 계산하는 방식으로는 해결 불가능
# 같이 타는 구간, 개별 구간으로 나눠서 계산해야 문제 해결 가능