import pandas as pd
import numpy as np
#import sys
import os
import io
import tempfile
import shutil
import pysyncrosim as ps
from pysyncrosim import helper
from pysyncrosim.environment import _environment

pd.set_option("max_columns", 5)

class Library(object):
    """
    A class to represent a SyncroSim Library.

    ...

    Attributes
    ----------
    session : Session
        Retrieves the Session associated with this Library.
    name : String
        Retrieves or sets the name of this Library.
    location : String
        Retrieves the file path to this Library.
    package : String
        Retrieves the package this Library is using.
    addons : pandas DataFrame
        Retrieves the addon(s) this Library is using.
    info : pandas DataFrame
        Retrieves information about this Library.
    owner : String
        Gets or sets the owner of this Library.
    readonly : String
        Gets or sets the read-only status of this Library.
    description : String
        Gets or sets the description for this Library.
    date_modified : String
        Retrieves the last date this Library was modified.

    Methods
    -------
    projects(name=None, pid=None, summary=True, overwrite=False):
        Creates or opens one or more SyncroSim Projects in the Library.
    scenarios(name=None, project=None, sid=None, pid=None, overwrite=False,
              optional=False, summary=True):
        Retrieves a Scenario or DataFrame of Scenarios in this Library.
    datasheets(name=None, summary=True, optional=False, empty=False,
               scope="Library", *ids):
        Retrieves a DataFrame of Library Datasheets.
    delete(project=None, scenario=None, force=False):
        Deletes a SyncroSim class instance.
    save_datasheet(name, data, scope="Library", *ids):
        Saves a pandas DataFrane as a SyncroSim Datasheet.
    run(scenarios=None, project=None, jobs=1):
        Runs a list of Scenario objects.
    update():
        Updates a SyncroSim Library.
    backup():
        Creates a backup of a SyncroSim Library.
    enable_addons(name):
        Enable addon package(s) of a SyncroSim Library.
    disable_addons(name):
        Disable addon package(s) of a SyncroSim Library.

    """
    __projects = None
    __scenarios = None
    __datasheets = None

    def __init__(self, location, session): # dja make the name more intuitive as well as matching the docstring name and internal consistentcy
        """
        Initializes a pysyncrosim Library instance.

        Parameters
        ----------
        loc : String
            Filepath to Library location on disk.
        session : Session
            pysyncrosim Session instance.

        Returns
        -------
        None.

        """
        self.__name = os.path.basename(location) # dja Changed to use new parameter name.  Changed to using the os.path function basename as this makes script more understandable and pythonic
        self.__session = session
        self.__location = location  # dja needed to match the name change in the class definition
        self.__addons = self.__init_addons()
        self.__info = None
        self.__package = None
        self.__owner = None
        self.__date_modified = None
        self.__readonly = None
        # All above attributes get created by below function
        self.__init_info()
        self.__description = self.__init_description()

    @property
    def session(self):
        """
        Retrieves the Session associated with this Library.

        Returns
        -------
        Session
            The Session for this Library.

        """
        return self.__session

    @property
    def name(self):
        """
        Retrieves or sets the name of this Library.

        Returns
        -------
        String
            Library name.

        """
        return self.__name

    @name.setter
    def name(self, value):
        args = ["--setprop", "--lib=%s" % self.location, "--name=%s" % value]
        self.session._Session__call_console(args)
        self.__name = value

    @property
    def location(self):
        """
        Retrieves the file path to this Library.

        Returns
        -------
        String
            Library file path.

        """
        return self.__location

    @property
    def package(self):
        """
        Retrieves the package this Library is using.

        Returns
        -------
        String
            Package name.

        """
        return self.__package

    @property
    def addons(self):
        """
        Retrieves the addon(s) this Library is using.

        Returns
        -------
        String
            Addon name(s).

        """
        return self.__addons

    @property
    def info(self):
        """
        Retrieves information about this Library.

        Returns
        -------
        pd.DataFrame
            General library information.

        """
        return self.__info

    @property
    def owner(self):
        """
        Gets or sets the owner of this Library.

        Returns
        -------
        String
            Owner of this Library.

        """
        return self.__owner

    @owner.setter
    def owner(self, value):
        if not isinstance(value, str):
            raise AttributeError("owner must be a String")
        self.__owner = value
        args = ["--setprop", "--lib=%s" % self.location, "--owner=%s" % value]
        self.session._Session__call_console(args)
        self.__owner = value

    @property
    def readonly(self):
        """
        Gets or sets the read-only status of this Library.

        Returns
        -------
        String
            "yes" if this Project is read-only, "no" otherwise.

        """
        return self.__readonly

    @readonly.setter
    def readonly(self, value):
        if not isinstance(value, bool):
            raise AttributeError("readonly must be a Logical")
        elif value is True or value == "yes":
            self.__readonly = "yes"
        elif value is False or value == "no":
            self.__readonly = "no"
        else:
            raise TypeError("value must be a Logical")
        args = ["--setprop", "--lib=%s" % self.location,
                "--readonly=%s" % self.__readonly]
        self.session._Session__call_console(args)
        self.__readonly = value

    @property
    def description(self):
        """
        Gets or sets the description for this Library.

        Returns
        -------
        String
            Library description.

        """
        return self.__description

    @description.setter
    def description(self, value):
        if not isinstance(value, str):
            raise AttributeError("description must be a String")
        self.__description = value
        args = ["--setprop", "--lib=%s" % self.location,
                "--description=%s" % value]
        self.session._Session__call_console(args)
        self.__description = self.__init_description()

    @property
    def date_modified(self):
        """
        Retrieves the last date this Library was modified.

        Returns
        -------
        String
            Last date modified.

        """
        return self.__date_modified

    def projects(self, name=None, pid=None, summary=True, overwrite=False):
        """
        Creates or opens one or more SyncroSim Projects in the Library.

        Parameters
        ----------
        name : String, optional
            Name of Project. The default is None.
        pid : Int, optional
            Project ID. The default is None.
        summary : Logical, optional
            If True, returns a DataFrame of Project information. If False,
            returns a list of Project objects. Default is True.
        overwrite : Logical, optional
            If True, then overwrites an existing Project. Default is False.

        Returns
        -------
        Project, List of Projects, or pandas.DataFrame
            DataFrame containing Project information, including ID, Name,
            Owner, Last Modified, and Read Only, or List of Projects if
            `summary=False`.

        """

        # Add unit tests for argument types later
        if name is not None and not isinstance(name, str):
            raise TypeError("name must be a String")
        if pid is not None and not isinstance(
                pid, int) and not isinstance(pid, np.int64):
            raise TypeError("pid must be an Integer")
        if not isinstance(summary, bool):
            raise TypeError("summary must be a Logical")
        if not isinstance(overwrite, bool):
            raise TypeError("overwrite must be a Logical")

        if overwrite is True:
            self.delete(project=name)

        self.__init_projects()

        # If pid provided, check that pid exists
        if pid is not None:
            if pid not in self.__projects["ID"].values:
                raise ValueError(f"Project ID {pid} does not exist")
            elif name is not None and name != self.__projects[
                    self.__projects["ID"] == pid]["Name"].values[0]:
                raise ValueError(
                    f"Project ID {pid} does not match Project name {name}")

        p = self.__get_project(name=name, pid=pid)

        if p is None:

            if summary is True:

                # Return DataFrame of Project information
                if name is not None:
                    return self.__projects[self.__projects.Name == name]
                if pid is not None:
                    return self.__projects[self.__projects.ID == pid]
                else:
                    return self.__projects

            if summary is False:

                proj_list = []

                for i in range(0, len(self.__projects)):

                    proj = ps.Project(self.__projects["ID"].loc[i],
                                      self.__projects["Name"].loc[i],
                                      self)

                    proj_list.append(proj)

                return proj_list

        elif p.empty:

            # If specified Project does not exist, then create it
            args = ["--create", "--project", "--lib=%s" % self.__location,
                    "--name=%s" % name]
            self.session._Session__call_console(args)

            # Reset Projects
            self.__projects = None
            self.__init_projects()
            p = self.__get_project(name, pid)

            # Convert np.int64 to native int
            pid = p["ID"].values[0].tolist()

            return ps.Project(pid, p["Name"].values[0], self)

        else:

            # Convert np.int64 to native int
            pid = p["ID"].values[0].tolist()

            return ps.Project(pid, p["Name"].values[0], self)

    def scenarios(self, name=None, project=None, sid=None, pid=None,
                  overwrite=False, optional=False, summary=True):
        """
        Retrieves a Scenario or DataFrame of Scenarios in this Library.

        Parameters
        ----------
        name : String, optional
            Scenario name. The default is None.
        project : Project, String, or Int, optional
            Project the Scenario belongs to. If no Project is specified when
            creating a new Scenario, the "Definitions" default Project is used.
            The default is None.
        sid : Int, optional
            Scenario ID. The default is None.
        pid : Int, optional
            Project ID. The default is None.
        overwrite : Logical, optional
            Overwrites an existing Scenario. The default is False.
        optional : Logical, optional
            Return optional information. The default is False.
        summary : Logical, optional
            When name and sid is None, if True, returns a DataFrame of
            information on existing Scenarios. Otherwise returns a list of
            Scenario class instances. The default is True.

        Returns
        -------
        Scenario, List of Scenarios, or pandas.DataFrame
            If a name or sid is specified, returns a Scenario class instance.
            If no name or sid is specified, and summary is set to False,
            returns a list of Scenario class instances. If no name or sid is
            specified and summary is set to True, returns a pandas.DataFrame
            of Scenario information for this Library.

        """
        # Check types
        if name is not None and not isinstance(name, str):
            raise TypeError("name must be a String")
        if project is not None and project.__class__.__name__ != "Project":
            if not isinstance(project, str) and not isinstance(project, int):
                raise TypeError(
                    "project must be Project instance, String, or Integer")
        if sid is not None and not isinstance(
                sid, int) and not isinstance(sid, np.int64):
            raise TypeError("sid must be an Integer")
        if pid is not None and not isinstance(
                pid, int) and not isinstance(pid, np.int64):
            raise TypeError("pid must be an Integer")
        if not isinstance(overwrite, bool):
            raise TypeError("overwrite must be a Logical")
        if not isinstance(optional, bool):
            raise TypeError("optional must be a Logical")
        if not isinstance(summary, bool):
            raise TypeError("summary must be a Logical")

        # self.__init_scenarios(pid=pid)

        if project is None and pid is None:
            self.__init_scenarios()
            if sid is not None and self.__get_scenario(sid=sid).empty is False:
                pid = self.__get_scenario(sid=sid)["Project ID"].item()
                project = self.projects(pid=pid)
            if name is not None and len(self.__get_scenario(name=name)) == 1:
                pid = self.__get_scenario(name=name)["Project ID"].item()
                project = self.projects(pid=pid)
            elif self.__projects is None or self.__projects.empty:
                project = self.projects(name = "Definitions")
                pid = project.pid
            elif len(self.__projects) == 1:
                pid = self.__projects.ID.item()
                project = self.projects(pid=pid)
            # elif "Definitions" in self.__projects.Name.values:
            #     pid = self.__projects[
            #         self.__projects.Name == "Definitions"].ID.item()
            #     project = self.projects(pid=pid)
            else:
                # project = self.projects(name = "Definitions")
                # pid = project.pid
                raise ValueError("More than one Project in Library \
                                  Please specify a Project")
        elif isinstance(project, int) or isinstance(project, np.int64):
            pid = project
        elif isinstance(project, str):
            pid = self.__projects[
                self.__projects.Name == project].ID.item()
        elif isinstance(project, ps.Project):
            pid = project.pid

        if overwrite is True:
            self.delete(project=project, scenario=name, force=True)

        # Retrieve Scenario DataFrame
        self.__init_scenarios(pid=pid)

        # If sid provided, check that sid exists
        if sid is not None:
            if self.__get_scenario(sid=sid).empty:
                raise ValueError(f"Scenario ID {sid} does not exist")
            elif name is not None and name != self.__get_scenario(
                    sid=1).Name.item():
                raise ValueError(
                    f"Scenario ID {sid} does not match Scenario name {name}")

        s = self.__get_scenario(name=name, sid=sid)

        if s is None:

            # Retrieve DataFrame of available Scenarios
            if summary is True:

                if optional is False:
                    return self.__scenarios[['Scenario ID',
                                             'Project ID',
                                             'Name',
                                             'Is Result']]

                elif name is not None:
                    return self.__scenarios[self.__scenarios.Name == name]
                elif sid is not None:
                    return self.__scenarios[self.__scenarios[
                        "Scenario ID"] == sid]
                else:
                    return self.__scenarios

            # Return list of Scenario objects
            if summary is False:

                s_summary = self.__scenarios
                s_summary = s_summary[s_summary["Is Result"] == "No"]

                if not isinstance(project, ps.Project):
                    project = self.projects(pid=pid)

                scn_list = []

                for i in range(0, len(s_summary)):

                    scn = ps.Scenario(s_summary["Scenario ID"].loc[i],
                                      s_summary["Name"].loc[i],
                                      project, self)

                    scn_list.append(scn)

                return scn_list

        # Create a Scenario
        if s.empty:

            if isinstance(project, int):
                pid = project
            elif isinstance(project, str):
                self.__init_projects()
                p = self.__get_project(name=project)
                pid = p["ID"].values[0]
            elif isinstance(project, ps.Project):
                pid = project.pid

            # Create Scenario using console
            args = ["--create", "--scenario", "--pid=%d" % pid,
                    "--lib=%s" % self.__location, "--name=%s" % name]
            self.session._Session__call_console(args)

            # Reset Scenarios
            self.__scenarios = None
            self.__init_scenarios()
            s = self.__get_scenario(name=name, sid=sid)

            if not isinstance(project, ps.Project):
                project = self.projects(pid=pid)

            return ps.Scenario(s["Scenario ID"].values[0],
                               s["Name"].values[0], project, self)

        # Open a Scenario
        else:

            # Retrieve the name of a Scenario using only the sid
            pid = s["Project ID"].values[0].tolist()

            if not isinstance(project, ps.Project):
                project = self.projects(pid=pid)

            sid = s["Scenario ID"].values[0].tolist()

            return ps.Scenario(sid, s["Name"].values[0], project, self)

    def datasheets(self, name=None, summary=True, optional=False, empty=False,
                   scope="Library", *ids):
        """
        Retrieves a DataFrame of Library Datasheets.

        Parameters
        ----------
        name : String, optional
            Datasheet name. The default is None.
        summary : Logical or String, optional
            Whether to list package Datasheets or core Datasheets. The default
            is True.
        optional : Logical, optional
            Return optional columns. The default is False.
        empty : Logical, optional
            Return an empty Datasheet. The default is False.
        scope : String, optional
            Datasheet scope. Options include "Library", "Project", or
            "Scenario". The default is "Library".

        Returns
        -------
        pandas.DataFrame
            If `optional=False`, then returns a DataFrame of Datasheet
            information including Package, Name, and Display Name.
            If `optional=True`, also returns Scope, Is Single, and Is Output.

        """
        # Type checks
        if name is not None and not isinstance(name, str):
            raise TypeError("name must be a String")
        if not isinstance(summary, bool) and summary != "CORE":
            raise TypeError("summary must be a Logical or 'CORE'")
        if not isinstance(optional, bool):
            raise TypeError("optional must be a Logical")
        if not isinstance(empty, bool):
            raise TypeError("empty must be a Logical")

        self.__datasheets = None

        # Initialize base arguments
        args = ["--export", "--lib=%s" % self.__location]

        if scope == "Project" and len(ids) > 0:
            args += ["--pid=%d" % ids]

        if scope == "Scenario" and len(ids) > 0:
            args += ["--sid=%d" % ids]

        if empty is True:
            args += ["--schemaonly"]

        if name is None:

            # Return DataFrame of Datasheets
            if summary is True or summary == "CORE":
                self.__init_datasheets(scope=scope, summary=summary)
                if optional is False:
                    self.__datasheets = self.__datasheets.iloc[:, 1:4]

                return self.__datasheets

            # Return List of DataFrames
            if summary is False:

                self.__init_datasheets(scope=scope, summary=True)
                d_summary = self.__datasheets.copy()
                self.__datasheets = None

                ds_list = []

                # Add arguments
                args += ["--sheet"]

                for ds in d_summary["Name"]:
                    args[-1] = "--sheet=%s" % ds
                    self.__datasheets = None
                    self.__init_datasheets(scope=scope, summary=False,
                                           name=ds, args=args)
                    ds_list.append(self.__datasheets)

                return ds_list

        if name is not None:

            # If package is not included in name, add it
            if name.startswith(self.package) is False:
                if name.startswith("core") is False:
                    name = self.package + "_" + name

            # Add arguments
            args += ["--sheet=%s" % name]

            if name.startswith("core"):
                args += ["--includesys"]

            self.__init_datasheets(scope=scope, summary=False,
                                   name=name, args=args)

            return self.__datasheets

    def delete(self, project=None, scenario=None, force=False):
        """
        Deletes a SyncroSim class instance.

        Parameters
        ----------
        project : Project, String, or Int, optional
            If called from a Library class instance, specify the Project to
            delete. The default is None.
        scenario : Scenario, String, or Int, optional
            If called from a Scenario class instance, specify the Scenario to
            delete. The default is None.
        force : Logical, optional
            If set to True, does not ask user before deleting SyncroSim class
            instance. The default is False.

        Returns
        -------
        None.

        """
        # after delete, can still access the instance attributes - should
        # create function to set to None?
        # Also, should have method to delete list of Projects or Scenarios?

        # type checks
        if project is not None and not isinstance(project, ps.Project):
            if not isinstance(project, int) and not isinstance(
                    project, str) and not isinstance(project, np.int64):
                raise TypeError(
                    "project must be a Project instance, Integer, or String")
        if scenario is not None and not isinstance(scenario, ps.Scenario):
            if not isinstance(scenario, int) and not isinstance(
                    scenario, str) and not isinstance(scenario, np.int64):
                raise TypeError(
                    "scenario must be a Scenario instance, Integer, or String")
        if not isinstance(force, bool):
            raise TypeError("force must be a Logical")

        if project is None and scenario is None:

            helper._delete_library(name = self.name, session=self.session,
                               force=force)

        elif project is not None and scenario is None:

            # turn project into project class instance if str or int
            if type(project) is int:
                p = self.projects(pid = project)
            if type(project) is str:
                if project in self.__projects["Name"].values:
                    p = self.projects(name = project)
                else:
                    raise ValueError(f'project {project} does not exist')
            if isinstance(project, ps.Project):
                p = project

            helper._delete_project(library=self, name=p.name,
                                   pid=p.pid, session=self.session,
                                   force=force)

        elif scenario is not None:

            # turn scenario into scenario class instance if str or int
            if type(scenario) is int:
                s = self.scenarios(sid = scenario, project = project)
            if type(scenario) is str:
                if scenario in self.__scenarios["Name"].values:
                    s = self.scenarios(name = scenario, project = project)
                else:
                    raise ValueError(f'scenario {scenario} does not exist')
            if isinstance(scenario, ps.Scenario):
                s = scenario

            helper._delete_scenario(library=self, project=s.project,
                                    name=s.name, sid=s.sid,
                                    session=self.session,
                                    force=force)

    def save_datasheet(self, name, data, scope="Library", *ids):
        """
        Saves a pandas DataFrane as a SyncroSim Datasheet.

        Parameters
        ----------
        name : String
            Name of the Datasheet.
        data : pandas DataFrame
            DataFrame of Datasheet values.
        scope : String, optional
            Scope of the Datasheet. The default is "Library".
        *ids : Int
            If Project- or Scenario-scoped, requires the Project or Scenario
            IDs.

        Returns
        -------
        None.

        """
        # Type checks
        if not isinstance(name, str):
            raise TypeError("name must be a String")
        if not isinstance(data, pd.DataFrame):
            raise TypeError("data must be a pandas DataFrame")
        if not isinstance(scope, str):
            raise TypeError("scope must be a String")

        # Add package name to Datasheet name if not included
        if name.startswith(self.package) is False:
            if name.startswith("core") is False:
                name = self.package + "_" + name

        # Check if running in a SyncroSim environment from the user interface
        e = _environment()
        transfer_dir = e.transfer_directory.item()

        # If running from user interface, save data to transfer directory
        if transfer_dir is not None:
            fpath = '{}\\SSIM_OVERWRITE-{}.csv'.format(transfer_dir, name)
            data.to_csv(fpath, index=False)
            return

        # Otherwise export the data to SyncroSim
        else:
            try:
                temp_folder = tempfile.mkdtemp(prefix="SyncroSim-")
                fpath = '{}\\export.csv'.format(temp_folder)
                data.to_csv(fpath, index=False)

                if not os.path.isfile(fpath):
                    raise RuntimeError(f"file path {fpath} does not exist")

                # Specify import arguments
                args = ["--import", "--lib=%s" % self.name,
                        "--sheet=%s" % name, "--folder=%s" % temp_folder,
                        "--file=%s" % fpath]

                if scope == "Project":
                    args += ["--pid=%d" % ids]

                if scope == "Scenario":
                    args += ["--sid=%d" % ids]

                self.__session._Session__call_console(args)

            finally:
                shutil.rmtree(temp_folder, ignore_errors=True)

    def run(self, scenarios=None, project=None, jobs=1):
        """
        Runs a list of Scenario objects.

        Parameters
        ----------
        scenarios : Scenario, String, Int, or List
            List of Scenrios, SyncroSim Scenario instance, name of Scenario,
            or Scenario ID.
        project : Project, optional
            SyncroSim Project instance, name of Project, or Project ID.
        jobs : Int, optional
            Number of multiprocessors to use. The default is 1.

        Returns
        -------
        result_dict : Dictionary
            Dictionary of Results Scenarios.

        """
        # Type checks
        if scenarios is not None and not isinstance(
                scenarios, ps.Scenario) and not isinstance(
                    scenarios, int) and not isinstance(
                    scenarios, np.int64) and not isinstance(
                        scenarios, str) and not isinstance(
                            scenarios, list):
            raise TypeError(
                "scenarios must be Scenario instance, String, Integer, or List")
        if project is not None and not isinstance(
                project, ps.Project) and not isinstance(
                    project, int) and not isinstance(
                    project, np.int64) and not isinstance(project, str):
            raise TypeError(
                "project must be Project instance, String, or Integer")
        if not isinstance(jobs, int) and not isinstance(jobs, np.int64):
            raise TypeError("jobs must be an Integer")

        # Collect output in a dictionary
        result_list = []

        if scenarios is None:

            if project is None:

                if len(self.projects()) == 1:
                    project = self.projects(pid=self.__projects.ID.item())

                else:
                    raise ValueError(
                        "Must specify project when > 1 Project in the Library")

            # Convert project to Project instance
            if isinstance(project, int):
                project = self.projects(pid=project)
            if isinstance(project, str):
                project = self.projects(name=project)

            # Run all Scenarios in a Project
            result_list = [
                scn.run(
                    jobs=jobs) for scn in project.scenarios(summary=False)]

        elif scenarios is not None:

            if not isinstance(scenarios, list):
                scenarios = [scenarios]

            if isinstance(scenarios[0], int):
                scenario_list = [
                    self.scenarios(sid=scn) for scn in scenarios]
            elif isinstance(scenarios[0], str):
                scenario_list = [
                    self.scenarios(
                        name=scn, project=project) for scn in scenarios]
            else:
                scenario_list = scenarios

            result_list = [scn.run(jobs=jobs) for scn in scenario_list]

        if len(result_list) == 1:
            return result_list[0]
        else:
            return result_list

    def update(self):
        """
        Updates a SyncroSim Library.

        Returns
        -------
        None.

        """
        try:
            args = ["--update", "--lib=%s" % self.location]
            self.session._Session__call_console(args)

        except RuntimeError as e:
            print(e)

    def backup(self):
        """
        Creates a backup of a SyncroSim Library.

        Returns
        -------
        None.

        """
        ds = self.datasheets(name = "core_Backup")
        args = ["--lib=%s" % self.location, "--backup"]

        if ds.IncludeInput[0] == "Yes":
            args += ["--input"]

        if ds.IncludeOutput[0] == "Yes":
            args += ["--output"]

        self.session._Session__call_console(args)

    def enable_addons(self, name):
        """
        Enable addon package(s) of a SyncroSim Library.

        Parameters
        ----------
        name : String or List
            Name of addon(s).

        Raises
        ------
        ValueError
            addon does not exist in available addons for this Library.

        Returns
        -------
        None.

        """

        # Type checks and convert to list
        if not isinstance(name, list):
            if not isinstance(name, str):
                raise TypeError("name must be a String or List of Strings")
            else:
                name = [name]
        elif all(isinstance(x, str) for x in name) is False:
            raise TypeError("all elements in name must be Strings")

        for a in name:
            args = ["--create", "--addon", "--lib=%s" % self.location,
                    "--name=%s" % a]
            try:
                self.session._Session__call_console(args)

            # Convert SyncroSim console error to print output
            except RuntimeError as e:
                print(e)
                return

        # Reset addons
        self.__addons = self.__init_addons()

    def disable_addons(self, name):
        """
        Disable addon package(s) of a SyncroSim Library.

        Parameters
        ----------
        name : String
            Name of addon package(s).

        Raises
        ------
        ValueError
            addon does not exist in available addons for this Library.

        Returns
        -------
        None.

        """

        # Type checks and convert to list
        if not isinstance(name, list):
            if not isinstance(name, str):
                raise TypeError("name must be a String or List of Strings")
            else:
                name = [name]
        elif all(isinstance(x, str) for x in name) is False:
            raise TypeError("all elements in name must be Strings")

        for a in name:
            args = ["--delete", "--addon", "--force",
                    "--lib=%s" % self.location, "--name=%s" % a]
            try:
                self.session._Session__call_console(args)

            # Convert SyncroSim console error to print output
            except RuntimeError as e:
                print(e)
                return

        # Reset addons
        self.__addons = self.__init_addons()

    def __init_addons(self):
        # Retrieves addons information
        args = ["--list", "--addons", "--lib=%s" % self.location]
        return self.__console_to_csv(args)

    def __init_info(self):
        # Retrieves Library info
        args = ["--list", "--library", "--lib=%s" % self.location]
        lib_info = self.__console_to_csv(args)
        self.__info = lib_info

        # Set index and retrieve all properties
        lib_info = lib_info.set_index("Property")
        self.__package = lib_info.loc["Package Name:"].item()
        self.__owner = lib_info.loc["Owner:"].item()
        self.__readonly = lib_info.loc["Read Only:"].item()
        self.__date_modified = lib_info.loc["Last Modified:"].item()

    def __init_description(self):
        # Retrieves the Library description
        args = ["--list", "--description", "--lib=%s" % self.__location]
        return self.session._Session__call_console(args, decode=True)

    def __init_projects(self):
        # Retrieves a list of Projects
        args = ["--list", "--projects", "--lib=%s" % self.__location]
        self.__projects = self.__console_to_csv(args)

    def __init_scenarios(self, pid=None):
        # Retrieves a list of Scenarios
        args = ["--list", "--scenarios", "--lib=%s" % self.__location]
        if pid is not None:
            args += ["--pid=%d" % pid]
        self.__scenarios = self.__console_to_csv(args)

    def __init_datasheets(self, scope, summary, name=None, args=None):
        # Retrieves a list of Datasheets
        if self.__datasheets is None:
            if summary is True:
                args = ["--list", "--datasheets", "--lib=%s" % self.__location,
                        "--scope=%s" % scope]
            if summary == "CORE":
                args = ["--list", "--datasheets", "--lib=%s" % self.__location,
                        "--scope=%s" % scope, "--includesys"]
            self.__datasheets = self.__console_to_csv(args)

    def __get_project(self, name=None, pid=None):
        # Retrieves Project info from the name or ID
        if name is None and pid is None:
            return None
        if name is not None:
            return self.__projects[self.__projects["Name"] == name]
        else:
            return self.__projects[self.__projects["ID"] == pid]

    def __get_scenario(self, name=None, sid=None):
        # Retrieves Scenario info from the name or ID
        if name is None and sid is None:
            return None
        if name is not None:
            return self.__scenarios[self.__scenarios["Name"] == name]
        else:
            return self.__scenarios[self.__scenarios["Scenario ID"] == sid]

    def __console_to_csv(self, args, index_col=None):
        # Turns console output into a pd.DataFrame
        console_output = self.session._Session__call_console(
            args,
            decode=True,
            csv=True)

        return pd.read_csv(io.StringIO(console_output), index_col=index_col)


import requests, sys

servers = {}

# read in hosts file
if len(sys.argv) != 2:
    print("Usage: python3 detect_server.py /path/to/hostfile.txt")
    quit()
hosts = open(sys.argv[1], "r").read().splitlines()

# get Server for each page
for host in hosts:
    URL = "http://"+host+"/"

    try:
        # get response
        response = requests.request("GET", URL, timeout=4)
        headers = response.headers

        # collect Server header if present
        if 'Server' in headers:
            print(host+","+response.headers['Server'])
        else:
            print(host+",Unknown")

    except requests.exceptions.RequestException as e:
        # hostname doesn't exist, so skip
        ""


#!/usr/bin/python
# -*- coding: latin-1 -*-
from nltk.parse.stanford import StanfordDependencyParser
from corenlp import StanfordCoreNLP
import time

class Parser():
    def __init__(self):
        #corenlp_dir = "/export/data/ghpaetzold/simpatico/server_simplifiers/core_nlp/stanford-corenlp-full-2016-10-31/"
        corenlp_dir = "/export/data/cscarton/simpatico/stanford-corenlp-full-2016-10-31/"
        self.corenlp = StanfordCoreNLP(corenlp_dir, memory="4g", properties='galician.myproperties.properties')

    def process(self, sentence):
        #sentences = open(self.doc, "r").read().strip().split("\n")
        #sentences = [l.strip().split(' ') for l in f_read]
        #dep_parser = StanfordDependencyParser(model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz")
        return self.corenlp.raw_parse(sentence)['sentences'][0]

    def transform(self, parsed):
        dict_dep = {}
        for rel, _, head, word, n in parsed['dependencies']:

            n = int(n)
            head = int(head)

            if head not in dict_dep.keys():
                dict_dep[head] = {}
            if rel not in dict_dep[head].keys():
                dict_dep[head][rel] = []

            dict_dep[head][rel].append(n)

        return dict_dep


import numpy as np

	# Implémentation de l'algorithme d'intégration par trapèze selon l'équation 4.38 des notes de cours
def trapezoidIntegration(function, a, b, n):
	x, h = np.linspace(a, b, n, retstep = True)
	f = function(x)
	return h, h*(f[0] + f[-1] + 2*np.sum(f[1:-1]))/2

	# Implémentation de l'algorithme d'intégration de Romberg selon l'équation 4.41 des notes de cours
def rombergIntegration(integralArray, hArray):
	if (len(integralArray) > 1):
		return (((hArray[-2]/2)**2)*integralArray[-2] - (hArray[-2]**2)*integralArray[-1])/((hArray[-2]/2)**2 - hArray[-2]**2)
	else:
		return integralArray[0]

f1 = lambda x : 3*x/(2*np.sqrt(x + 1))
primitive1 = lambda x : (x - 2)*np.sqrt(x + 1)

error = lambda calculated, actual : np.abs(calculated - actual)

steps = np.array([10, 25])
x0, x1 = 0, 3

errorArray, hArray, integralArray = np.array([]), np.array([]), np.array([])
for i, j in enumerate(steps):
	h, integral = trapezoidIntegration(f1, x0, x1, j)
	hArray = np.append(hArray, h)
	integralArray = np.append(integralArray, integral)
	errorArray = np.append(errorArray, error(integral, (primitive1(x1) - primitive1(x0))))

integralArray = np.append(integralArray, rombergIntegration(integralArray, hArray))
errorArray = np.append(errorArray, error(integralArray[-1], (primitive1(x1) - primitive1(x0))))

print("Valeur de l’intégrale définie en 5.1")
print(f"Selon la méthode de Romberg (équation 4.41 des NDC), avec N = {steps[0]} et {steps[1]} :\n"
	  f"I = {integralArray[-1]:.8f}, avec une erreur de {errorArray[-1]:.8E}\n\n"
	  f"Selon la méthode du trapèze, avec N = {steps[1]} :\n"
	  f"I = {integralArray[1]:.8f}, avec une erreur de {errorArray[1]:.8E}")


"""empty message

Revision ID: 548924d9d900
Revises: a35f8795768a
Create Date: 2020-12-04 12:09:03.659569

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = '548924d9d900'
down_revision = 'a35f8795768a'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('product_release_info', 'initial_release_date',
               existing_type=sa.DATE(),
               nullable=True)
    op.alter_column('product_release_info', 'price',
               existing_type=sa.INTEGER(),
               nullable=True)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('product_release_info', 'price',
               existing_type=sa.INTEGER(),
               nullable=False)
    op.alter_column('product_release_info', 'initial_release_date',
               existing_type=sa.DATE(),
               nullable=False)
    # ### end Alembic commands ###


from flock import Flock
import numpy as np
from glob import glob
import h5py

name  = "periodic_boid"
dt    = 1.
steps = 1000
chkpt = 1
parts = 100
dim   = 2
boxL  = 5.
nn_radius = 1.
v0    = 0.03

etas = np.arange(0.2,5.2,0.2)

# start simulation
for eta in etas:
    print("Starting eta = {}".format(eta))
    flock = Flock(name=name,dt=dt,steps=steps,chkpt=chkpt,parts=parts,dim=dim,
                  boxL=boxL,nn_radius=nn_radius,eta=eta,v0=v0)
    flock.evolve()


from datetime import timedelta
from typing import Any, Dict, Tuple, Union, Callable, Iterable, Optional, Type

from nonebot.command import CommandSession
from nonebot.typing import CommandHandler_T, CommandName_T, Patterns_T, PermissionPolicy_T

class CommandGroup:
    basename: Tuple[str]
    base_kwargs: Dict[str, Any]

    def __init__(self, name: Union[str, CommandName_T], *,
                 permission: Union[PermissionPolicy_T, Iterable[PermissionPolicy_T]] = ...,
                 only_to_me: bool = ...,
                 privileged: bool = ...,
                 shell_like: bool = ...,
                 expire_timeout: Optional[timedelta] = ...,
                 run_timeout: Optional[timedelta] = ...,
                 session_class: Optional[Type[CommandSession]] = ...): ...

    def command(self, name: Union[str, CommandName_T], *,
                aliases: Union[Iterable[str], str] = ...,
                patterns: Patterns_T = ...,
                permission: Union[PermissionPolicy_T, Iterable[PermissionPolicy_T]] = ...,
                only_to_me: bool = ...,
                privileged: bool = ...,
                shell_like: bool = ...,
                expire_timeout: Optional[timedelta] = ...,
                run_timeout: Optional[timedelta] = ...,
                session_class: Optional[Type[CommandSession]] = ...
                ) -> Callable[[CommandHandler_T], CommandHandler_T]: ...


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/19 17:10
# @Author : Micky
# @Desc : 模型训练
# @File : detection.py
# @Software: PyCharm
import os
import numpy as np
import Config
from Network import Net

DATA_PATH = ''

if not os.path.exists('./Datas/TRAIN_X.npy'):
    raise  FileExistsError('请先运行Datasets/Image_covert_data')

train_x = np.load('./Datas/TRAIN_X.npy')
train_y = np.load('./Datas/TRAIN_Y.npy')
val_x = np.load('./Datas/VAL_X.npy')
val_y = np.load('./Datas/VAL_Y.npy')

print('训练集特征shape：{}， 验证集特征shape：{}'.format(np.shape(train_x), np.shape(val_x)))
print('训练集label shape：{}， 验证集特征label shape：{}'.format(np.shape(train_y), np.shape(val_y)))

# 定义超参数
width = Config.width
height = Config.height
channel = 3
n_classify = 42
epochs = 1000
batch_size = 16

# 定义模型对象
net = Net(width, height, channel, n_classify, epochs, batch_size)
# 开始训练
net.train(train_x, train_y, val_x, val_y)


from direct.showbase.ShowBase import ShowBase
base = ShowBase()
from Graph_bus_stop import Graph_bus_stop
from Graph_bus import Graph_bus

from panda3d.core import TextNode
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
from direct.showbase.DirectObject import DirectObject
import logging
import threading
import time
import sys
import random

class MyApp(DirectObject):

  def __init__(self):
    #ShowBase.__init__(self)

    base.setBackgroundColor(0, 0, 0)  # Set the background to black
    #base.disableMouse()  # disable mouse control of the camera
    #camera.setPos(0, 0, 45)  # Set the camera position (X, Y, Z)
    #camera.setHpr(0, -90, 0)  # Set the camera orientation
    base.trackball.node().setPos(-70, 200, -24)
    base.trackball.node().setHpr(0, 40, 0)

    # Create Ambient Light
    ambientLight = AmbientLight('ambientLight')
    ambientLight.setColor((0.01, 0.01, 0.01, 1))
    ambientLightNP = render.attachNewNode(ambientLight)
    render.setLight(ambientLightNP)

    # Directional light 01
    directionalLight = DirectionalLight('directionalLight')
    directionalLight.setColor((2,  2, 2, 1))
    directionalLightNP = render.attachNewNode(directionalLight)
    # This light is facing backwards, towards the camera.
    directionalLightNP.setHpr(-45, -45, 0)
    render.setLight(directionalLightNP)

    # Load the cartesian plane
    self.plane = loader.loadModel("models/plane")
    self.plane.setPos(100,50,0)
    self.plane.reparentTo(render)

    self.bus_stop_list = []
    for i in range (0, 10):
      for j in range (0, 9):
        bus_stop = Graph_bus_stop(100, 10 + i*20, 10 + j*10)
        self.bus_stop_list.append(bus_stop)

    self.bus = Graph_bus(50, 10, 11)

    self.accept("escape", sys.exit)
    self.accept('spam',self.OnSpam)

  def OnSpam(self, h, pos):
    #print h
    self.bus_stop_list[0].set_pass(h)
    self.bus.set_pos(pos, 11)
    self.bus.set_pass(h)
    #print base.trackball.node().getPos()
    #print base.trackball.node().getHpr()

def thread_function(name):
  h = 1
  inc = 1
  pos = 10
  while True:
    messenger.send('spam',[h, pos])
    time.sleep(0.01)
    h += inc
    pos += 0.01
    if(h >= 100):
      inc = -1
    if(h <= 0):
      inc = 1

format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
                    datefmt="%H:%M:%S")

logging.info("Main    : before creating thread")
x = threading.Thread(target=thread_function, args=(1,))
logging.info("Main    : before running thread")
x.start()
logging.info("Main    : wait for the thread to finish")
# x.join()
logging.info("Main    : all done")

w, h = 1440, 810
props = WindowProperties()
props.setSize(w, h)
base.win.requestProperties(props)

print("d1")
app = MyApp()
#messenger.send('spam',['foo','bar'])
print("d2")

base.run()


def Menu():  ##菜单主界面
    print('*' * 22)
    print("* 查看毕业生列表输入: 1 *")
    print("* 添加毕业生信息输入: 2 *")
    print("* 修改毕业生信息输入: 3 *")
    print("* 删除毕业生信息输入: 4 *")
    print("* 退出系统请输入   0 *")
    print('*' * 22)

def CheckIdisRight(StudentList, id):  ##检查学号是否在列表中
    for i in range(0, len(StudentList)):
        if ((id in StudentList[i]) == True):
            return True
    return False

def PrintStudentList(StudentList):  # 打印学生信息列表
    for i in range(0, len(StudentList)):
        print(StudentList[i])

def AddStudent(StudentList):  ##添加学生信息
    number = int((input("请输入学号：")))
    if (number < 1000000000 and CheckIdisRight(StudentList, number) == False):  ##学号判断
        print("学号输入错误&学号已存在！请重新输入：")
        number = (input("请输入学号："))
    name = input("请输入你的名字：")
    tell = input("请输入你的电话：")
    if (len(tell) != 11):
        print("请输入正确的电话号码(11)位：")
        tell = input()
    college = input("请输入你的学院名称：")
    grade = input("请输入你的年级：")
    isjob = int(input("是否就业？：是填 1 否则填0: "))
    if (isjob == 1):
        company = input("请输入你公司的名称：")
    else:
        company = 0
    arry = [number, name, tell, college, grade, isjob, company]
    StudentList.append(arry)  ##将新建的学生信息进行插入
    PrintStudentList(StudentList)  ##打印学生信息列表

def StudentPersonalMsg():  ##修改信息界面选择
    print('*' * 22)
    print("* 修改姓名请输入: 1 *")
    print("* 修改电话号码请输入: 2 *")
    print("* 修改是否就业请输入: 3 *")
    print("* 修改就业公司请输入: 4 *")
    print("* 退出修改请输入：0 *")
    print('*' * 22)

def ChangeStudent(StudentList):  ##修改学生信息模块
    ##默认学号 年级 等信息不可修改
    def changename(StudentList, arry, i):  # 修改姓名
        print(arry)
        name = input("请输入修改后的名字：")
        StudentList[i][1] = name
        print("修改后为：")
        PrintStudentList(StudentList)

    def changetell(StudentList, arry, i):  # 修改电话号码
        print(arry)
        tell = input("请输入修改后的电话号码：")
        StudentList[i][2] = tell
        print("修改后为：")
        PrintStudentList(StudentList)

    def changeisgob(StudentList, arry, i):  # 修改是否就业情况
        print(arry)
        isgob = int(input("请输入修改后的 是否工作："))
        StudentList[i][5] = isgob
        print("修改后为：")
        PrintStudentList(StudentList)

    def changcompany(StudentList, arry, i):  # 修改就业公司信息
        print(arry)
        company = input("请输入修改后的公司为：")
        StudentList[i][6] = company
        print("修改后为：")
        PrintStudentList(StudentList)

    print("请输入要修改的学生的学号：")
    id = int(input())
    i = 1
    if ((CheckIdisRight(StudentList, id)) == False):  ##判断学号是否存在
        print("学号不存在！")
    if (CheckIdisRight(StudentList, id) == True):
        while (i < len(StudentList)):  # 通过循环找到该学生的信息列表
            if (StudentList[i][0] == id):
                StudentPersonalMsg()  ##显示出修改的菜单选项
                while (1):
                    a = int(input("请输入："))
                    while (a):
                        if (a == 1):
                            ##姓名修改
                            changename(StudentList, StudentList[i], i)
                            break
                        if (a == 2):
                            ##电话号码修改
                            changetell(StudentList, StudentList[i], i)
                            break
                        if (a == 3):
                            ##是否就业状态修改
                            changeisgob(StudentList, StudentList[i], i)
                            break
                        if (a == 4 and StudentList[i][5] == 1):
                            ##就业公司修改
                            changcompany(StudentList, StudentList[i], i)
                            break
                        if (a == 4 and StudentList[i][5] == 0):
                            print("学生尚未就业，请先修改是否就业信息！")
                            break
                    if (a == 0):
                        ##按0 退出修改信息功能
                        break
                ##返回到主界面的菜单选项
                break
            i = i + 1

def DeleteStudent(StudentList):  ##删除学生信息
    print("请输入要删除的学生的学号：输入0退出！")
    id = int(input())
    i = 1
    if ((CheckIdisRight(StudentList, id)) == False):
        print("学号不存在！")
    if (CheckIdisRight(StudentList, id) == True):
        ##同样先判断学号学号是否存在
        while (i < len(StudentList)):
            if (StudentList[i][0] == id):
                del StudentList[i]
                print("删除成功！")
                break
            if (id == 0):
                break
            i = i + 1
    PrintStudentList(StudentList)  # 打印学生信息列表

def main():
    Menu()
    StudentInfo = ['学号', '姓名', '电话', '学院', '年级', '是否就业', "就业公司"]
    ##先默认插入一个用于显示的列表的列表
    StudentList = [StudentInfo]
    while (1):
        a = int(input("请输入："))
        while (a):

            if (a == 1):
                PrintStudentList(StudentList)
                Menu()
                break
            if (a == 2):
                AddStudent(StudentList)
                Menu()
                break
            if (a == 3):
                ChangeStudent(StudentList)
                Menu()
                break
            if (a == 4):
                DeleteStudent(StudentList)
                Menu()
                break
        if (a == 0):  ##按0退出进程
            exit()

main()


import cherrypy
import mako.template
import mako.lookup
import os
from datetime import datetime
from PIL import Image

from lib.tool import web
from conf.system_config import tmpl_lookup

__all__ = ["Gallery"]

class Gallery(object):

    _cp_config = {
        "error_page.404": web.handle_404_error
        }

    @cherrypy.expose
    def index(self):
        photos = [f for f in os.listdir("public/images/gallery/")
                  if (f.endswith(".jpg") or
                      f.endswith(".JPG") or
                      f.endswith(".jpeg"))]
        tmpl = mako.template.Template(
            filename="template/gallery/index.html",
            lookup=tmpl_lookup
            )
        return tmpl.render(
                current_user=web.get_current_user(),
                photos=photos
                )

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def upload(self, files=None):
        if files:
            filename = datetime.utcnow().strftime("%Y%m%d%H%M%S")
            tmp_file = "public/images/gallery/" + filename + ".orig"
            thumb_file = "public/images/gallery/thumbnails/%s.jpg" % filename
            file_up = "public/images/gallery/" + filename + ".jpg"
            with open(tmp_file, "wb") as f:
                f.write(files.file.read())
            im = Image.open(tmp_file)
            im.thumbnail((1080, 720), Image.ANTIALIAS)
            if im.mode != "RGB":
                im = im.convert("RGB")
            im.save(file_up, "jpeg")
            im.thumbnail((240, 144), Image.ANTIALIAS)
            im.save(thumb_file, "jpeg")
            os.remove(tmp_file)
            return {"files": [{
                        "name": filename + ".jpg",
                        "size": "640x310",
                        "thumbnailUrl": \
                            "/static/images/gallery/thumbnails/%s.jpg" %(
                                        filename)
                        }]
                    }


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/muntjac/test/server/data/util/object_property_test.py
# Compiled at: 2013-04-04 15:36:37
from unittest import TestCase
from muntjac.data.util.object_property import ObjectProperty

class ObjectPropertyTest(TestCase):

    def setUp(self):
        TestCase.setUp(self)
        self._super1 = TestSuperClass('super1')
        self._sub1 = TestSubClass('sub1')

    def testSimple(self):
        prop1 = ObjectProperty(self._super1, TestSuperClass)
        self.assertEquals('super1', prop1.getValue().getName())
        prop1 = ObjectProperty(self._super1)
        self.assertEquals('super1', prop1.getValue().getName())
        prop2 = ObjectProperty(self._sub1, TestSubClass)
        self.assertEquals('Subclass: sub1', prop2.getValue().getName())
        prop2 = ObjectProperty(self._sub1)
        self.assertEquals('Subclass: sub1', prop2.getValue().getName())

    def testSetValueObjectSuper(self):
        prop = ObjectProperty(self._super1, TestSuperClass)
        self.assertEquals('super1', prop.getValue().getName())
        prop.setValue(TestSuperClass('super2'))
        self.assertEquals('super1', self._super1.getName())
        self.assertEquals('super2', prop.getValue().getName())

    def testSetValueObjectSub(self):
        prop = ObjectProperty(self._sub1, TestSubClass)
        self.assertEquals('Subclass: sub1', prop.getValue().getName())
        prop.setValue(TestSubClass('sub2'))
        self.assertEquals('Subclass: sub1', self._sub1.getName())
        self.assertEquals('Subclass: sub2', prop.getValue().getName())

    def testSetValueStringSuper(self):
        prop = ObjectProperty(self._super1, TestSuperClass)
        self.assertEquals('super1', prop.getValue().getName())
        prop.setValue('super2')
        self.assertEquals('super1', self._super1.getName())
        self.assertEquals('super2', prop.getValue().getName())

    def testSetValueStringSub(self):
        prop = ObjectProperty(self._sub1, TestSubClass)
        self.assertEquals('Subclass: sub1', prop.getValue().getName())
        prop.setValue('sub2')
        self.assertEquals('Subclass: sub1', self._sub1.getName())
        self.assertEquals('Subclass: sub2', prop.getValue().getName())

    def testMixedGenerics(self):
        prop = ObjectProperty(self._sub1)
        self.assertEquals('Subclass: sub1', prop.getValue().getName())
        self.assertEquals(prop.getType(), TestSubClass)
        prop.setValue('sub2')
        self.assertEquals('Subclass: sub2', prop.getValue().getName())

class TestSuperClass(object):

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

    def getName(self):
        return self._name

    def __str__(self):
        return self.getName()

class TestSubClass(TestSuperClass):

    def __init__(self, name):
        super(TestSubClass, self).__init__('Subclass: ' + name)


class BackwardsBlockingHeuristic:

    @staticmethod
    def calculate_heuristic_value(state):
        blocking_vehicles = []
        last_car = '\0'
        my_vehicle = state.get_vehicle('X')
        x_coordinate = my_vehicle.get_x_coordinate()
        y_coordinate = my_vehicle.get_y_coordinate()
        for i in range(state.get_board_size(),y_coordinate):
            if state.get_board()[x_coordinate][i] != 'X' and state.get_board()[x_coordinate][i] != '.':
                if state.get_board()[x_coordinate][i] == last_car:
                    raise Exception("State not valid")
                blocking_vehicles.append(state.get_board()[x_coordinate][i])
                last_car = state.get_board()[x_coordinate][i]
        return len(blocking_vehicles) + 1
        # return AdvancedBlockingHeuristic.calculate_heuristic_value(state) *-1


# -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 19:16:35 2019

@author: Luis Rodriguez
"""

# Binary Classification Model

# Training and Testing Dataset

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import KFold

data_set=pd.read_csv('model_dataset_vf.csv')
print(data_set.describe())

#print(data_set)

X = data_set.drop(columns='class')
Y = data_set['class']

# We will use the 80% of the data for the training set and 20% for the testing set
# Since the accuracy of the model increased

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2,random_state = 0)

X_train.fillna(0)
X_test.fillna(0)
Y_train.fillna(0)
X_test.fillna(0)

# Logistic Regression for Binary Classification

logistic_regresion_model = linear_model.LogisticRegression()
logistic_regresion_model.fit(X_train,Y_train)

# Testing the model

Y_pred = logistic_regresion_model.predict(X_test)
lrm_score=logistic_regresion_model.score(X_test, Y_test)*100

print('The accuracy of the logistic regression classifier model on test set is: ',lrm_score,'%')

confusion_matrix = confusion_matrix(Y_test, Y_pred)
print(confusion_matrix)


#RTTs = [100, 150, 80, 75]
RTTs = [100]

a = 1/8
B = 1/4
SRTT = RTTs[0]
DevRTT = RTTs[0]/2
RTO = SRTT + 4*DevRTT

for rtt in RTTs[1:]:
    diff = rtt - SRTT
    SRTT = SRTT + a*diff
    DevRTT = DevRTT + B*(abs(diff) - DevRTT)
    RTO = SRTT + 4*DevRTT

for name, val in zip(['SRTT', 'DevRTT', 'RTO'], [SRTT, DevRTT, RTO]):
    print(name + ':', val)


import random
from numpy import mean, var, std
import matplotlib.pyplot as plt
'''
  ****************  新股申购模拟程序     *****************
  **                Ver: 0.1                            **
  **                Author: Vincent                     **
  **                Data:   2017-Dec-23                 **
  ********************************************************
'''
class CNewStockInvest:
    def __init__(self, initCapital):
        self.week = 0   #周数
        self.issuePrice = 0     #发行价
        self.lotRate = 0        #中签率
        self.subscribeNum = 0   #申购数量
        self.ticketNum = 0      #中签数量
        self.V = 0              #V
        self.marketPrice = 0    #上市价
        self.WeeklyStockIncome = [] #每周打中新股的收益（5周后才能抛出）
        if initCapital>0:
            self.InitialCapital = initCapital
        else:
            self.InitialCapital = 1000000
        self.CurrentCapital = self.InitialCapital
        self.Profit = 0     #利润
        self.ProfitRate = 0 #利润率

    def reset(self):
        self.week = 0;
        self.WeeklyStockIncome.clear()

    def setInitCapital(self, initCapital):
        if initCapital>0:
            self.InitialCapital = initCapital
        else:
            self.InitialCapital = 1000000
        self.CurrentCapital = self.InitialCapital

    def genRandIssuePrice():  #产生随机的新股发行价(5~10元)
        return 5+5*random.random()

    def genRandLotRate():#产生随机的新股中签率(0,001~0.025)
        return 0.001+0.024*random.random()

    def refreshWeeklyData(self): #每周进行打新
        self.issuePrice = CNewStockInvest.genRandIssuePrice()
        self.lotRate = CNewStockInvest.genRandLotRate()
        if 3<self.week< 52:  #第5周到52周可以抛出5周前的股票回笼资金
            self.CurrentCapital += self.WeeklyStockIncome[self.week-4]
        self.subscribeNum = self.CurrentCapital/self.issuePrice
        self.ticketNum = round((self.subscribeNum * self.lotRate)/1000)*1000  #一手1000股
        self.V = 0.5*random.random()
        self.marketPrice = (0.8+0.5/(self.lotRate*100) + self.V)*self.issuePrice
        self.WeeklyStockIncome.append(self.ticketNum*self.marketPrice)
        self.CurrentCapital -= self.issuePrice * self.ticketNum #扣去打新费用
        weeklyData = (1 + self.week,self.issuePrice,self.lotRate,self.subscribeNum,self.ticketNum,self.V,self.marketPrice,self.CurrentCapital)
        self.week += 1
        #print(weeklyData)

    def getLastFourWeekIncome(self):#最后四周的新股收益要一年后才能到账
        sum = 0
        for x in range(48,52):
            sum += self.WeeklyStockIncome[x]
        return sum

    def runOneYearTest(self):#测试一年的数据
        #print(" 周         发行价             中签率            申购数         中签数         V            上市价               剩余资金")
        for x in range(0,52):
            self.refreshWeeklyData()
        self.CurrentCapital += self.getLastFourWeekIncome()
        self.Profit = self.CurrentCapital - self.InitialCapital
        self.ProfitRate = self.Profit/self.InitialCapital
        #print("【年初资金】：%d 【年末资金】： %d 【利润】：%d 【利润率】：%0.2f%%" % (self.InitialCapital,self.CurrentCapital,self.Profit, self.ProfitRate*100))
        return self.ProfitRate*100

#主函数
def main():

    invest1 = CNewStockInvest(0)
    X =[] #利润率-投入图 X轴
    Y =[] #利润率-投入图 Y轴
    #测试初始资金10W 到 300W
    profitRateResults = []
    for x in range(0,60):#投入5W~250W,增幅为5W
        initCapital = 50000*(x+1)
        X.append(initCapital)
        for t in range(0,1000): #每组测试1000次取平均值
            invest1.reset()
            invest1.setInitCapital(initCapital)
            profitRateResults.append(invest1.runOneYearTest())
        meanProfitRate = mean(profitRateResults)
        Y.append(meanProfitRate)
        print("投入资金:%d 利润率均值:%0.2f%% 方差:%0.2f 标准差:%0.2f" % (initCapital,meanProfitRate,var(profitRateResults),std(profitRateResults)))
        print("------------------------------------------------------------");
        profitRateResults.clear()

    plt.figure()
    plt.plot(X,Y)
    plt.title("New Stock Investment")
    plt.xlabel("Invested Capital(Yuan)")
    plt.ylabel("Rate of Profit(%)")
    plt.show()
main()


import types
import pprint

def is_array(var):
    return isinstance(var, (list, tuple, dict))

def search_dicts(key, val, targets):
    for item in targets:
        if item[key] == val:
            return item

    return None

def var_dump(obj):
    pprint(dump(obj))

def dump(obj):
    '''return a printable representation of an object for debugging'''
    newobj = obj
    if isinstance(obj, list):
        newobj = []
        for item in obj:
            newobj.append(dump(item))
    elif isinstance(obj, tuple):
        temp = []
        for item in obj:
            temp.append(dump(item))
        newobj = tuple(temp)
    elif isinstance(obj, set):
        temp = []
        for item in obj:
            temp.append(str(dump(item)))
        newobj = set(temp)
    elif isinstance(obj, dict):
        newobj = {}
        for key, value in obj.items():
            newobj[str(dump(key))] = dump(value)
    elif isinstance(obj, types.FunctionType):
        newobj = repr(obj)
    elif '__dict__' in dir(obj):
        newobj = obj.__dict__.copy()
        if ' object at ' in str(obj) and not '__type__' in newobj:
            newobj['__type__']=str(obj).replace(" object at ", " #").replace("__main__.", "")
        for attr in newobj:
            newobj[attr]=dump(newobj[attr])
    return newobj


"""
Object for evaluating a model for super-resolution
"""
import logging
import os
from typing import List, Tuple, Iterator, NamedTuple

import pandas as pd

from modules.image import image_utils, image
from modules.model import models

LOG = logging.getLogger(__name__)

class ImagePairDescriptor(NamedTuple):
    """Describes an image pair for querying"""
    dataset: str
    num: int
    scale: int

class ModelEvaluatorError(Exception):
    """Error in using the ModelEvaluator"""

class ModelEvaluator:

    def __init__(self, model_config_fpath: str):
        """Initialize a model evaluator from a model configuration

        :param model_config: configuration dictionary for a model
        """
        self._model = \
            models.load_model_from_config_fpath(model_config_fpath)

    @staticmethod
    def _get_evaluation_image_paths() -> List[str]:
        """Gets all the images paths from the evaluation image directory

        Assumes this method is run from neural-image-enhance, raises an exception otherwise

        :return: List of file_paths
        """
        # TODO: either raise an exception or make this handle the filepath stuff
        evaluation_path = os.path.join('modules', 'evaluation', 'images')
        return image_utils.get_image_paths_from_dir(evaluation_path)

    @staticmethod
    def _paired_images(image_paths: List[str]) -> Iterator[Tuple[str, str]]:
        """Pairs all the images from evaluation directory to their input, output pairs

        :param image_paths: List of file_paths
        :return: A List of tuples, representing input, output pairs for each image
        """
        sorted_images = list(sorted(image_paths))
        hr_images, lr_images = sorted_images[::2], sorted_images[1::2]
        return zip(lr_images, hr_images)

    @staticmethod
    def _categorize_image_fpath_pair(
            lr_hr_pair: Tuple[str, str]) -> ImagePairDescriptor:
        """Creates an ImagePairDescriptor from a pair of image fpaths

        Raises an ModelEvaluatorError if the paths are not a valid image pair

        :param lr_hr_pair: pair of a low-res, high_res image file paths
        :return: ImagePairDescriptor of the lr_hr_pair
        """
        img1, img2 = lr_hr_pair
        img1_directory, img1_fname = os.path.split(img1)
        img2_directory, img2_fname = os.path.split(img2)

        # Handle incorrect file pair directories errors here
        if img1_directory != img2_directory:
            raise ModelEvaluatorError(
                f'Directory for image fpaths must be the same: {lr_hr_pair}'
            )

        # break up the image fnames into the descriptors
        prefix1, num1, srf1, scale1, lr = img1_fname.split('_')
        prefix2, num2, srf2, scale2, hr = img2_fname.split('_')

        # Handle the image naming convention stuff here
        errors = []
        if not (prefix1 == prefix2 == 'img'):
            errors.append(
                f'All image fnames must begin with \'img\'.'
            )

        if not (num1 == num2):
            errors.append(
                f'Image fname numbers must match.'
            )

        if not (srf1 == srf2 == 'SRF'):
            errors.append(
                f'All image fnames must contain \'SRF\'.'
            )

        if not (scale1 == scale2):
            errors.append(
                f'Image scales must match.'
            )

        if not (lr == 'LR.png' and hr == 'HR.png'):
            errors.append(
                f'Image fname ending do not properly label resolution type.'
            )

        # raise all caught errors
        if errors:
            raise (
                f'{lr_hr_pair} does not follow proper naming convention. '
                f'Errors: {errors}'
            )

        # now get the descriptor attributes
        dataset = str(img1_directory.split(os.path.sep)[-2])
        num = int(num1)
        scale = int(scale1)
        return ImagePairDescriptor(dataset=dataset, num=num, scale=scale)

    def evaluate(self) -> pd.DataFrame:
        """Evaluates an SR model

        Saves and returns a pd.dataframe formatted in the following way.

        index, dataset, num, scale, baseline, psnr

        dataset: Dataset in the evaluation folder
        num: Number of the image pair in the dataset
        scale: Scale of the enhancement
        baseline: PSNR of a naive resize
        psnr: PSNR via the model's enhance method

        :return: pd.Dataframe with complete results
        """
        evaluation_image_paths = self._get_evaluation_image_paths()
        paired_evaluation_images = self._paired_images(evaluation_image_paths)
        evaluation_results = []
        LOG.info(f'Evaluating {len(evaluation_image_paths)//2} image pairs')
        for lr_hr_pair in paired_evaluation_images:
            image_descriptor = self._categorize_image_fpath_pair(lr_hr_pair)
            lr_img = image.PILImage.open(lr_hr_pair[0]).convert_to_rgb()
            hr_img = image.PILImage.open(lr_hr_pair[1]).convert_to_rgb()

            # compute the baseline PSNR
            baseline = \
                image_utils.psnr(lr_img.resize(hr_img.size), hr_img)

            # compute the model's PSNR from enhancement
            pair_psnr = \
                image_utils.psnr(self._model.enhance(lr_img, hr_img.size), hr_img)

            # make the results row
            pair_results = [
                image_descriptor.dataset,
                image_descriptor.num,
                image_descriptor.scale,
                baseline,
                pair_psnr
            ]

            LOG.info(pair_results)

            evaluation_results.append(
                pair_results
            )

        pd.DataFrame()
        results = pd.DataFrame(
            data=evaluation_results,
            index=0,
            columns=['dataset', 'num', 'scale', 'baseline', 'psnr']
        )

        results_dir = os.path.join(
            'modules', 'evaluation', 'results', self._model.version
        )
        os.mkdir(results_dir)
        results_save_path_override = os.path.join(results_dir, 'results.csv')

        results.to_csv(results_save_path_override)

        return results

    def analyze_results(self, results: pd.DataFrame) -> pd.DataFrame:
        """Outputs results statistics

        :param results: pd.Dataframe results from evaluate (can also be fpath)
        """

        datasets = ['All'] + list(results['dataset'].unique())
        # use 0 for all scales
        scales = [0] + list(results['scale'].unique())
        analyses = []
        for dataset in datasets:
            for scale in scales:
                # get results by dataset
                results_by_dataset = results if dataset == 'All' else \
                    results[results['dataset'] == dataset]

                # get results by scale
                results_by_dataset_and_scale = \
                    results_by_dataset if not scale else \
                        results_by_dataset[results_by_dataset['scale'] == scale]

                if not results_by_dataset_and_scale.empty:
                    psnr_mean = results_by_dataset_and_scale['psnr'].mean()
                    # get the improvement over the baseline
                    psnr_improvement = \
                        results_by_dataset_and_scale['psnr'] - \
                        results_by_dataset_and_scale['baseline']

                    # make the analysis row
                    analysis = [
                        dataset,
                        f'scale_{scale}' if scale else 'All',
                        psnr_mean,
                        psnr_improvement.mean(),
                        psnr_improvement.var()
                    ]

                    LOG.info(analysis)
                    analyses.append(analysis)

        results_analysis = pd.DataFrame(
            data=analyses,
            # index=0,
            columns=[
                'dataset',
                'scale',
                'psnr_mean',
                'psnr_improvement_mean',
                'psnr_improvement_var',
            ]
        )

        results_save_path = os.path.join(
            'modules', 'evaluation', 'results', self._model.version, 'analysis.csv')

        results_analysis.to_csv(results_save_path, index_label='index')

        return results_analysis


import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from typing import Union

# in DCMW we use not random network
class BCN(tf.keras.Model):

    def __init__(self,
                 input_dim: int,
                 output_dim:int,
                 controller_dime:int=64,
                 interface_dim: int=35,
                 netsize: int=100,
                 degree: int=20,
                 k:float=2,
                 name:str='bcn')->None:

        """
        Initialize bcn object.

        Parameters
        ----------
        input_dim
            Size of input vector is free
        output_dim
            Size of output vector
        interface_dim
            size of vector to random network (and from random)
        netsize
            random network netsize
        degree
            random network connection to/from each neurons
        1/k
            random network maximum synaptic strength
        name
            Name of bcn.

        numbers pick from valiant 2009 , 2012 alpha regima and buschman 2019 ...
        """

        super(BCN,self).__init__(name=name)
        self.input_dim=input_dim
        self.output_dim=output_dim # Y = Output_dim
        self.interface_dim=interface_dim
        self.netsize=netsize
        self.degree=degree
        self.k=k
        self.neg_to_all=1/3
        self.controller_dim= controller_dime
        self.network_forget_rate=1/12 #random network forgeting data in time, see testin random network
        self.show_interface_vector=True
        self.interface_vector_processes=[]

        # Initialize Random Network States
        self.network_state=np.zeros(self.netsize)

        #Creating Random Ntwork Wieghts -- using numpy becuse its faster than tf
        self.density=self.degree/self.netsize

        self.randomnetwork=np.zeros((self.netsize,self.netsize))
        for row in range(self.netsize):
            if (row%3==0):
                for i in range(self.degree):
                    self.randomnetwork[row,row-i]=-1
            else:
                for i in range(degree):
                    self.randomnetwork[row,row-i]=1/2

        # Initialize controller output and interface vector with gaussian normal
        self.output_v = tf.random.uniform([1, self.output_dim],minval=0,maxval=1)
        self.interface = tf.random.uniform([1, self.interface_dim],minval=0,maxval=1)

        # initialise Dense layers of the controller
        self.dense1 = Dense(
                         self.controller_dim,
                         name='dcnw_controller')
        self.dense2 = Dense(
                         2*self.controller_dim,
                         name='dcnw_controller')
        self.dense3 = Dense(
                         self.controller_dim,
                         name='dcnw_controller')
        self.dense_output = Dense(
                         self.interface_dim+self.output_dim, # last_layer_of_dense_dim
                         activation='sigmoid',
                         name='dcnw_controller')

        # Derived Output and interface vector from controller last layer (dense_output)
        temp=np.zeros((self.interface_dim+self.output_dim, self.output_dim))
        temp_dim=self.interface_dim+self.output_dim
        for i in range(temp_dim):
            for j in range(self.output_dim):
                if (i==j): temp[i,j]=1
                else : temp[i,j]=0

        self.W_output = tf.Variable( #[last_layer_of_dense_dim,output_dim]
            tf.constant(temp,dtype=tf.float32),
            trainable=False,
            name='dcnw_net_output_weights'
        )

        temp=np.zeros((self.interface_dim+self.output_dim, self.interface_dim))
        temp_dim=self.interface_dim+self.output_dim
        for i in range(temp_dim):
            for j in range(self.interface_dim):
                if (i-self.output_dim==j): temp[i,j]=1
                else : temp[i,j]=0

        self.W_interface = tf.Variable(  # [last_layer_of_dense_dim,interface_dim]
            tf.constant(temp,dtype=tf.float32),
            trainable=False,
            name='dcnw_interface_weights'
        )

    # This Two functions are the same just for diferenet job!
    def Write_Vector(self):
        "Getting Write Vector from NN to RN"
        if self.show_interface_vector :
            self.interface_vector_processes.append(self.interface.numpy()[0])

    def Read_Vector(self):
        "Getting Read Vector from RN for NN"
        if self.show_interface_vector :
            self.interface_vector_processes.append(self.interface.numpy())

    def random_network_updating(self):
        """
        1- update random network states
        2- no weights change
        """

        #update fire states with interface vector
        for i in range(self.interface_dim):
            self.network_state[i]=self.network_state[i]+self.interface[0,0,i]

        for i in range(self.netsize):
            s=np.dot(self.network_state,self.randomnetwork[i])*self.network_forget_rate
            if s>0:
                self.network_state[i]=s
            else:
                self.network_state[i]=0

        #changing size
        temp=np.zeros(self.interface_dim)
        for i in range(self.interface_dim):
            temp[i]=self.network_state[i]

        self.interface=temp
        self.interface=tf.convert_to_tensor(self.interface.reshape(1,self.interface_dim))

    def step(self, x: tf.Tensor) -> tf.Tensor:
        """
        Update the controller, compute the output and interface vectors,
        write to and read from memory and compute the output.
        """

        # Read
        self.Read_Vector()
        x_in = tf.expand_dims(tf.convert_to_tensor(np.concatenate([x.numpy(), self.interface.numpy()],1)), axis=0)

        # Update controller
        y_out = self.dense_output(self.dense3(self.dense2(self.dense1(x_in))))

        # Compute output and interface vectors
        self.output_v = tf.matmul(y_out, self.W_output)  # [1,last_layer_of_dense_dim * [last_layer_of_dense_dim,output_dim] -> [1,output_dim]
        self.interface = tf.matmul(y_out, self.W_interface)  # [1,last_layer_of_dense_dim] * [last_layer_of_dense_dim,interface_dim] -> [1,interface_dim]

        # Write
        self.Write_Vector()
        self.random_network_updating()

        return self.output_v

    def call(self, x: Union[np.ndarray, tf.Tensor]) -> tf.Tensor:
        """ Unstack the input, run through the DCNW and return the stacked output. """

        y = []
        for x_seq in tf.unstack(x, axis=0):
            x_seq = tf.expand_dims(x_seq, axis=0)
            y_seq = self.step(x_seq)
            y.append(y_seq)
        if self.show_interface_vector :
            return tf.squeeze(tf.stack(y, axis=0)) , self.interface_vector_processes
        else:
            return tf.squeeze(tf.stack(y, axis=0))

Codes/2 Method/2-3 Testing other Networks/2-3-2 Ballanced but nonrandom/Generalized first-order binding/model.py


#Universidade Federal do Amazonas
#Fernanda Bonfim - 21602340

nA = int(input("Numero de habitantes A: "))
nB = int(input("Numero de habitantes B: "))
pA = float(input("Percentual de crescimento A: "))
pB = float(input("Percentual de crescimento B: "))
ano = 1

while(nA < nB):
	nA = nA + (nA * pA / 100)
	nB = nB + (nB * pB / 100)
	ano = ano + 1
print(ano)


import torch

def hebb_values_transform(tensor, on_zero):
    # create a copy of the original tensor,
    # because of the way we are replacing them.
    res = tensor.clone().data
    res[res == 0] = on_zero
    return res

def hebb_array_transform(tensor, on_zero):
    # create a copy of the original tensor,
    # because of the way we are replacing them.
    res = tensor.clone().data
    for i in range(len(on_zero)):
        res[i][res[i] == 0] = on_zero[i]
    return res

def balance_relu(x, overall_mean=False):
    if overall_mean:
        mu_x = torch.mean(x)
        x = [x_i if x_i > 0. else -mu_x for x_i in x]
    else:
        mu_x = torch.mean(x, 1)
        for i, x_i in enumerate(x):
            x_i = x[i]
            x_i[x_i == 0.] = -mu_x[i]
            x[i] = x_i

    return x

def hebb_values_transform_input(tensor, on_zero):
    # create a copy of the original tensor,
    # because of the way we are replacing them.
    res = tensor.clone().data
    res[res == 0] = on_zero
    return res

def hebb_values_transform_input2(tensor, on_zero):
    # create a copy of the original tensor,
    # because of the way we are replacing them.
    res = tensor.clone().data
    res[res == 0] = on_zero
    return res

def hebb_values_transform_conv(tensor, on_zero):
    # create a copy of the original tensor,
    # because of the way we are replacing them.
    res = tensor.clone().data
    res[res == 0] = on_zero

    res = torch.sum(res, dim=2)
    res = torch.sum(res, dim=2)
    return res

def hebb_values_negative_transform(tensor, multiplier=0.1):
    # create a copy of the original tensor,
    # because of the way they are replaced.
    res = tensor.clone().data
    res[res < 0] = multiplier * res[res < 0]
    return res

def indices_h(array):
    indices1 = []
    for ind, x in enumerate(array):
        if int(x) == 1:
            indices1.append(ind)
    return indices1

def indices_matrix(matrix):
    matrix1 = []
    for a, array in enumerate(matrix):
        indices1 = []
        for ind, x in enumerate(array):
            if int(x) == 1:
                indices1.append(ind)
        matrix1.append(indices1)
    return indices1

def indices_h_conv(array):
    indices1 = []
    for ind, x in enumerate(array):
        if x == 1:
            indices1.append(ind)
    return indices1


import torch
import numpy as np

class Pruner:
    r"""General pruning class.
        """
    def __init__(self, masked_parameters):
        self.masked_parameters = list(masked_parameters)
        self.scores = {}
        self.processed_scores = {}

    def score(self, model, loss, dataloader, device):
        r"""Scoring function.
        """
        raise NotImplementedError

    def process(self, normalize):
        r"""Normalizes scores before masking.
        """
        for k, v in self.scores.items():
            if normalize:
                mean = torch.mean(v)
                std = torch.std(v)
                v = (v - mean) / std
            self.processed_scores[k] = v

    def _global_mask(self, sparsity):
        r"""Updates masks of model with scores by sparsity level globally.
        """
        global_scores = torch.cat([torch.flatten(v) for v in self.processed_scores.values()])
        k = int((1.0 - sparsity) * global_scores.numel())
        if not k < 1:
            threshold, _ = torch.kthvalue(global_scores, k)
            for mask, param in self.masked_parameters:
                score = self.processed_scores[id(param)]
                zero = torch.tensor([0.]).to(mask.device)
                one = torch.tensor([1.]).to(mask.device)
                mask.copy_(torch.where(score <= threshold, zero, one))

    def _local_mask(self, sparsity):
        r"""Updates masks of model with scores by sparsity level parameter-wise.
        """
        for mask, param in self.masked_parameters:
            score = self.processed_scores[id(param)]
            k = int((1.0 - sparsity) * score.numel())
            if not k < 1:
                threshold, _ = torch.kthvalue(torch.flatten(score), k)
                zero = torch.tensor([0.]).to(mask.device)
                one = torch.tensor([1.]).to(mask.device)
                mask.copy_(torch.where(score <= threshold, zero, one))

    def mask(self, sparsity, scope):
        r"""Updates masks of model with scores by sparsity according to scope.
        """
        if scope == 'global':
            self._global_mask(sparsity)
        if scope == 'local':
            self._local_mask(sparsity)

    @torch.no_grad()
    def apply_mask(self):
        r"""Applies mask to prunable parameters.
        """
        for mask, param in self.masked_parameters:
            param.mul_(mask)

    def alpha_mask(self, alpha):
        r"""Set all masks to alpha in model.
        """
        for mask, _ in self.masked_parameters:
            mask.fill_(alpha)

class Rand(Pruner):
    def __init__(self, masked_parameters):
        super(Rand, self).__init__(masked_parameters)

    def score(self, model, loss, dataloader, device):
        for _, p in self.masked_parameters:
            self.scores[id(p)] = torch.randn_like(p)

class Mag(Pruner):
    def __init__(self, masked_parameters):
        super(Mag, self).__init__(masked_parameters)

    def score(self, model, loss, dataloader, device):
        for _, p in self.masked_parameters:
            self.scores[id(p)] = torch.clone(p.data).detach().abs_()

class SNIP(Pruner):
    def __init__(self, masked_parameters):
        super(SNIP, self).__init__(masked_parameters)

    def score(self, model, loss, dataloader, device):

        for batch_idx, (data, target) in enumerate(dataloader):
            data, target = data.to(device), target.to(device)
            output = model(data)
            loss(output, target).backward()

        for _, p in self.masked_parameters:
            self.scores[id(p)] = torch.clone(p.grad * p.data).detach().abs_()
            p.grad.data.zero_()

class GraSP(Pruner):
    def __init__(self, masked_parameters):
        super(GraSP, self).__init__(masked_parameters)

    def score(self, model, loss, dataloader, device):

        for batch_idx, (data, target) in enumerate(dataloader):

            data, target = data.to(device), target.to(device)
            L = loss(model(data), target)

            grad = torch.autograd.grad(L, [p for (_, p) in self.masked_parameters], create_graph=True)

            flatten = torch.cat([g.reshape(-1) for g in grad if g is not None])
            gnorm = 0.5*flatten.pow_(2).sum()
            gnorm.backward()

        for _, p in self.masked_parameters:
            self.scores[id(p)] = torch.clone(-p.grad * p.data).detach()
            p.grad.data.zero_()

class SynFlow(Pruner):
    def __init__(self, masked_parameters):
        super(SynFlow, self).__init__(masked_parameters)

    def score(self, model, loss, dataloader, device):

        @torch.no_grad()
        def linearize(model):
            signs = {}
            for name, param in model.state_dict().items():
                signs[name] = torch.sign(param)
                param.abs_()
            return signs

        @torch.no_grad()
        def nonlinearize(model, signs):
            for name, param in model.state_dict().items():
                param.mul_(signs[name])

        signs = linearize(model)

        (data, _) = next(iter(dataloader))
        input_dim = list(data[0,:].shape)
        input = torch.ones([1] + input_dim).to(device)
        output = model(input)
        torch.sum(output).backward()

        for _, p in self.masked_parameters:
            self.scores[id(p)] = torch.clone(p.grad * p).detach().abs_()
            p.grad.data.zero_()

        nonlinearize(model, signs)


import codecs
import os
import sys
try:
  from setuptools import setup
except:
  from distutils.core import setup
def read(fname):
  return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
NAME = "C-Viewer"
PACKAGES = []
DESCRIPTION = "package description."
LONG_DESCRIPTION = read("README.rst")
KEYWORDS = "comic Viewer"
AUTHOR = "gaianote"
AUTHOR_EMAIL = "gaianote@163.com"
URL = "http://gaianote.github.io"
VERSION = "0.0.1"
LICENSE = "MIT"
CLASSFIERS = ['License :: OSI Approved :: MIT License','Programming Language :: Python','Intended Audience :: Developers','Operating System :: OS Independent']
setup(
  name = NAME,
  version = VERSION,
  description = DESCRIPTION,
  long_description =LONG_DESCRIPTION,
  classifiers =  CLASSFIERS,
  keywords = KEYWORDS,
  author = AUTHOR,
  author_email = AUTHOR_EMAIL,
  url = URL,
  license = LICENSE,
  packages = PACKAGES,
  include_package_data=True,
  zip_safe=True,
)


from collections import defaultdict
from typing import Dict

directions = {
    'R': 1,
    'L': -1,
    'U': 1j,
    'D': -1j
}

if __name__ == '__main__':
    grid: Dict[complex, Dict[int, int]] = defaultdict(dict)

    with open('data/day_03.txt', 'r') as f:
        for idx, wire in enumerate(f):
            steps = 0
            position = 0

            for move in wire.split(','):
                direction = directions[move[0]]
                distance = int(move[1:])

                for _ in range(distance):
                    steps += 1
                    position += direction
                    grid[position].setdefault(idx, steps)

    part1 = int(min(abs(p.real) + abs(p.imag) for p, v in grid.items() if len(v) == 2))
    print(f'Part 01: {part1}')

    part2 = min(sum(v.values()) for v in grid.values() if len(v) == 2)
    print(f'Part 02: {part2}')


# import requests
# from bs4 import BeautifulSoup
# import re
#
# url = 'https://sou.zhaopin.com/?jl=854&kw=devops&kt=3'
# headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"}
#
# response = requests.get(url).text
#
# soup = BeautifulSoup(response,"html.parser")
#
# for item1 in soup.findAll('div',{"class":"jobName"}):
#     for i in item1.attrs['title']:
#         print(i)

from datetime import timedelta
from datetime import datetime
class CarMessage(object):
    def __init__(self, num, owner, color, type, connect, money, endtime):
        # 汽车属性
        self.num = num
        self.color = color
        self.type = type
        self.owner = owner
        self.connect = connect
        self.money = money
        self.endtime = endtime

    def __str__(self):
        print('车牌号：<%s> 车主：<%s> 颜色:<%s> 车型:<%s> 联系方式：<%s> 余额：<%s> 停车时间：<%s> '
              % (self.num, self.owner, self.color, self.type, self.connect, self.money, self.endtime))

class Park(object):
    def init(self):  # 对停车场初始化车辆
        self.car_list.append(CarMessage('001', 'python', '黑', '大卡', '123456789', 34, datetime.now()))
        self.car_list.append(CarMessage('002', 'hello', '黑', '小汽车', '123456789', 87, timedelta(minutes=10)))
        self.car_list.append(CarMessage('003', 'java', '白', '小汽车', '123456789', 55, timedelta(hours=1)))
        self.car_list.append(CarMessage('004', 'westos', '黑', '小卡', '123456789', 60, timedelta(days=2)))
        self.car_list.append(CarMessage('005', 'root', '白', '中卡', '123456789', 24, timedelta(minutes=60)))

    def __init__(self):
        self.max_car = 200
        self.car_list = []
        self.cur_car = len(self.car_list)

    def pay(self):
        print(self.car_list)
            # money = car.endtime
            # print("当前余额：%s" %(money))
        # while True:
        #     if car.money >= money:  # 判断余额是否够支付
        #         car.money -= money
        #         print('自动付款%s成功' % (money))
        #         break
        #     else:
        #         print('余额不足请充值')
        #         car.money += int(input('充值金额：'))
        #         print('充值成功')

p = Park()

p.pay()


#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#   FILE: Elect2016UserMetaObj.py
#   DATE: January, 2016
#   Author: David W. McDonald
#
#   An object that mirrors the user meta data table in the database
#
#   Copyright by Author. All rights reserved. Not for reuse without
#   express permissions.
#
#
from hcde.data.db.base.userMetaObj import userMetaObj

class Elect2016UserMetaObj(userMetaObj):
    def __init__(self):
        userMetaObj.__init__(self)
        self.collect_id = -1

    def to_dict(self):
        rec = {}
        if( self.rid > 0 ):
            rec['rid'] = self.rid
        rec['user_name'] = self.user_name
        rec['screen_name'] = self.screen_name
        rec['user_id'] = self.user_id
        rec['friend_count'] = self.friend_count
        rec['follower_count'] = self.follower_count
        rec['profile_collect_dt'] = self.profile_collect_dt
        rec['friend_collect_dt'] = self.friend_collect_dt
        rec['friend_collect_resp'] = self.friend_collect_resp
        rec['follower_collect_dt'] = self.follower_collect_dt
        rec['follower_collect_resp'] = self.follower_collect_resp

        rec['collect_id'] = self.collect_id
        return rec

    def __repr__(self):
        result = "Elect2016UserMetaObj():\n\t"
        result = result+"rid: %s\n\t"%(str(self.rid))
        result = result+"user_name: %s\n\t"%(str(self.user_name))
        result = result+"screen_name: "+self.screen_name.encode('utf-8')+"\n\t"
        result = result+"user_id: %s\n\t"%(str(self.user_id))
        result = result+"friend_count: %d\n\t"%(self.friend_count)
        result = result+"friend_collect_dt: %s\n\t"%(str(self.friend_collect_dt))
        result = result+"friend_collect_resp: %s\n\t"%(self.friend_collect_resp)
        result = result+"follower_count: %d\n\t"%(self.follower_count)
        result = result+"friend_collect_dt: %s\n\t"%(str(self.follower_collect_dt))
        result = result+"follower_collect_resp: %s\n\t"%(self.follower_collect_resp)
        result = result+"collect_id: %s"%(self.collect_id)
        return result


""" uri resolver """
import uuid
from ptah import config

RESOLVER_ID = 'ptah:uri-resolver'

def resolve(uri):
    """ Resolve uri, return resolved object.

    Uri contains two parts, `schema` and `uuid`. `schema` is used for
    resolver selection. `uuid` is resolver specific data. By default
    uuid is a uuid.uuid4 string.
    """
    if not uri:
        return

    try:
        schema, data = uri.split(':', 1)
    except ValueError:
        return None

    try:
        return config.get_cfg_storage(RESOLVER_ID)[schema](uri)
    except KeyError:
        pass

    return None

def extract_uri_schema(uri):
    """ Extract schema of given uri """
    if uri:
        try:
            schema, data = uri.split(':', 1)
            return schema
        except:
            pass

    return None

def resolver(schema):
    """ Register resolver for given schema
    """
    info = config.DirectiveInfo()

    def wrapper(func):
        info.attach(
            config.Action(
                _register_uri_resolver, (schema, func),
                discriminator=(RESOLVER_ID, schema))
            )

        return func

    return wrapper

def register_uri_resolver(schema, resolver, depth=1):
    """ Register resolver for given schema

    :param schema: uri schema
    :type schema: string
    :param resolver: Callable object that accept one parameter.

    Resolver interface::

      class Resolver(object):

         def __call__(self, uri):
             return content
    """
    info = config.DirectiveInfo(depth=depth)
    info.attach(
        config.Action(
            _register_uri_resolver, (schema, resolver),
            discriminator=(RESOLVER_ID, schema))
        )

def _register_uri_resolver(cfg, schema, resolver):
    cfg.get_cfg_storage(RESOLVER_ID)[schema] = resolver

class UriFactory(object):
    """ Uri Generator

    Example::

       >> uri = UriFactory('cms-content')

       >> uri()
       'cms-content:f73f3266fa15438e94cca3621a3f2dbc'

    """

    def __init__(self, schema):
        self.schema = schema

    def __call__(self):
        """ Generate new uri using supplied schema """
        return '%s:%s' % (self.schema, uuid.uuid4().get_hex())


from __future__ import print_function

import psi4

import numpy as np
from scipy.optimize import curve_fit

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

he_dimer = """
He
--
He 1 **R**
"""

distances = [2.875, 3.0, 3.125, 3.25, 3.375, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 14.0, 16.0, 20.0, 25.0, 30.0]
energies = []
for d in distances:
    mol = psi4.geometry(he_dimer.replace('**R**', str(d)))
    en = psi4.energy('MP2/aug-cc-pVDZ', molecule=mol, bsse_type='nocp')
    en *= 219474.6
    energies.append(en)

# Lennard-Jones fit
powers = [-12, -6]
x = np.power(np.array(distances).reshape(-1, 1), powers)
coeffs = np.linalg.lstsq(x, energies)[0]
fpoints = np.linspace(2, max(distances), 100).reshape(-1, 1)
fdata = np.power(fpoints, powers)
fit_energies_lj = np.dot(fdata, coeffs)

# Buckingham fit
def buckingham(r, a, b, c):
    return a * np.exp(-b * r) - (c * r ** (-6))
popt, pcov = curve_fit(buckingham, distances, energies, method='trf')
fit_energies_buckingham = buckingham(fpoints, *popt)

# Morse fits
# def morse_2(r, a, b):
#     return a * (1 - np.exp(-b * r)) ** 2
# def morse_3(r, a, b, c):
#     return a * (1 - np.exp(-b * (r - c))) ** 2
def morse_4(r, a, b, c, d):
    return (a * (1 - np.exp(-b * (r - c))) ** 2) + d
# tstart = [1.0e+3, 1]
# popt, pcov = curve_fit(morse_2, distances, energies, method='trf', p0=tstart, maxfev=40000000)
# fit_energies_morse_2 = morse_2(fpoints, *popt)
# tstart = [3.41838629,  1.7536397,  3.32438717]
# popt, pcov = curve_fit(morse_3, distances, energies, method='trf', p0=tstart, maxfev=40000000)
# fit_energies_morse_3 = morse_3(fpoints, *popt)
tstart = [1.0e+3, 1, 3, 0]
popt, pcov = curve_fit(morse_4, distances, energies, method='trf', p0=tstart, maxfev=40000000)
fit_energies_morse_4 = morse_4(fpoints, *popt)

fig, ax = plt.subplots()
ax.set_xlim((2, max(distances)))
ax.set_ylim((-10, 2))
ax.scatter(distances, energies, color='black', label='MP2/aug-cc-pVDZ (no CP)')
ax.plot(fpoints, fit_energies_lj, label='Lennard-Jones fit')
ax.plot(fpoints, fit_energies_buckingham, label='Buckingham fit')
# ax.plot(fpoints, fit_energies_morse_2, label='Morse fit (2 param)')
# ax.plot(fpoints, fit_energies_morse_3, label='Morse fit')
ax.plot(fpoints, fit_energies_morse_4, label='Morse fit (shifted)')
ax.plot([0,10], [0,0], 'k-')
ax.set_xlabel(r'interatomic separation ($\AA{}$)')
ax.set_ylabel(r'interaction energy ($\mathrm{cm^{-1}}$)')
ax.legend(loc='best', fancybox=True, framealpha=0.50)
fig.savefig('1b_molecule_buckingham_nocp_long.pdf', bbox_inches='tight')