import pathlib
from setuptools import setup, find_packages

# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text()

setup(name='monrp',
      version='1.0',
      author="Víctor Pérez-Piqueras",
      author_email="victor.perezpiqueras@uclm.es",
      description="Multi-Ojective Next Release Problem set of algorithms",
      long_description=README,
      long_description_content_type="text/markdown",
      url="https://github.com/UCLM-SIMD/MONRP",
      license="MIT",
      classifiers=[
          "Programming Language :: Python :: 3",
          "Programming Language :: Python :: 3.8"
      ],
      packages=find_packages(exclude=("test_*",)),
      install_requires=[
          'imageio',
          "pandas",
          "numpy",
          "scipy",
          "scikit-learn",
          "matplotlib"
      ],
      python_requires=">=3.8",
      include_package_data=True,
      )


import sys
def iterate(arr, v):
	for i in range(4):
		for j in range(i + 1, 4):
			if arr[i] < arr[j]:
				v[i] += 1
				v[j] -= 1
			elif arr[i] > arr[j]:
				v[i] -= 1
				v[j] += 1
	return v

def solve(steps, positions):
	i = 0
	velocity = [[0 for k in range(4)] for j in range(3)]
	while i < steps:
		for j in range(3):
			velocity[j] = iterate(positions[j], velocity[j])
			positions[j] = [a + b for a, b in zip(positions[j], velocity[j])]
		i += 1

	ps = [0] * 4
	vs = [0] * 4
	for i in range(3):
		for j in range(4):
			ps[j] += abs(positions[i][j])
			vs[j] += abs(velocity[i][j])
	res = 0
	for a, b in zip(ps, vs):
		res += a * b
	return res

if __name__ == '__main__':
	positions = [[] for i in range(3)]
	for line in sys.stdin:
		i = 0
		for pos in line.strip('\n')[1:-1].split(', '):
			positions[i].append(int(pos[2:]))
			i += 1
	print(solve(1000, positions))

assert(solve(10, [[-1, 2, 4, 3], [0, -10, -8, 5], [2, -7, 8, -1]]) == 179)
assert(solve(100, [[-8, 5, 2, 9], [-10, 5, -7, -8], [0, 10, 3, -3]]) == 1940)
assert(solve(1000, [[19, 1, 14, 8], [-10, 2, -4, 7], [7, -3, 1, -6]]) == 6227)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun  2 16:06:27 2022

@author: Zhenzi Yu
"""

import os
import math
import numpy as np
import copy
import random
import time
import json

from pymatgen.io.cif import CifParser
from mofid.run_mofid import cif2mofid
import pymatgen.analysis.graphs as mgGraph
import pymatgen.core.bonds  as mgBond
import pymatgen.core.structure as mgStructure
from pymatgen.io.vasp.inputs import Poscar

from src.helper import CheckConnectivity, WriteStructure, CheckNeighbourMetalCluster, DebugVisualization, nodes_expansion
from src.DefectMOFStructure import DefectMOFStructure

from ase.io import read, write

class DefectMOFStructureBuilder():

    def __init__(self, cifFile_Name, output_dir = '.', sepMode = 'MetalOxo', cutoff = 12.8 ):

        self.cifFile_Name = cifFile_Name
        self.output_dir = output_dir
        self.sepMode = sepMode
        self.cutoff = cutoff

        self.original_nodes = None
        self.original_linkers, self.original_linkers_length = None, None
        self.processed_structure = None

        self.original_Structure = self.ReadStructure(self.cifFile_Name)
        self.SeperateStructure(self.cifFile_Name,linkerSepDir = os.path.join(self.output_dir,'linkerSep' ))

        return

    def ReadStructure(self,cifFile_Name):

        cifFile = CifParser(cifFile_Name)
        # bug fixed, cannot allow primitive reduction!
        structure = cifFile.get_structures(primitive=False)[0]

        return structure

    def SeperateStructure(self, cifFileName, linkerSepDir):

##############################################################################
#       Coding notes: Metal nodes append after linkers!!!!!
##############################################################################
#
#
        # use the packge to seperate the linker/nodes and read in
        t0 = time.time()
        try:
            os.mkdir(linkerSepDir)
        except:
            pass
        cif2mofid(cifFileName ,output_path = linkerSepDir)
        self.original_linkers = self.ReadStructure(os.path.join(linkerSepDir, self.sepMode, 'linkers.cif'))
        self.original_linkers_length = len(self.original_linkers.sites)
        print("SBU seperation finished, which takes %f Seconds" % (time.time()-t0))

        # Subgraph detection : linker_cluster_assignment - LCA
        linker_cluster_assignment = CheckConnectivity(self.original_linkers)

        self.original_nodes = self.ReadStructure(os.path.join(linkerSepDir, self.sepMode, 'nodes.cif'))
        # pbc expande nodes so that for linker delete step to find the right neighbour
        self.original_nodes = nodes_expansion(self.original_nodes)

        # Neighbour Metal Cluster detection : NbM
        coord_bond_array, metal_cluster_assignment, coord_bond_list = CheckNeighbourMetalCluster(self.original_linkers, self.original_nodes )
        NbM = [x + len(self.original_linkers) for x in coord_bond_array]

        # pass Subgraph detection to the mg structure;
        # NOTE: this could be combined together with the prvious step, but just for debug purposes, I seperated
        self.original_linkers.add_site_property('NbM',NbM)
        self.original_linkers.add_site_property('LCA',linker_cluster_assignment[1])
        self.original_linkers.add_site_property('NbL',[np.nan]*len(self.original_linkers))
        self.original_linkers.add_site_property('MCA',[np.nan]*len(self.original_linkers))
        self.linker_num = linker_cluster_assignment[0]

        # add property to nodes
        self.original_nodes.add_site_property('NbM',[np.nan]*len(self.original_nodes)) # add np.nan
        self.original_nodes.add_site_property('LCA',[np.nan]*len(self.original_nodes)) # add np.nan
        self.original_nodes.add_site_property('NbL',coord_bond_list) # NbL: neighbourhodd linker
        self.original_nodes.add_site_property('MCA',metal_cluster_assignment[1]) # MCA: Metal Cluster assginement
        self.original_nodes.add_site_property('is_linker',[False]*len(self.original_nodes))

        # create seperate molecules based on graph
        self.molecules = []
        indexes = []
        # detect linker type
        for i in range(self.linker_num):
            index = np.array( np.where(linker_cluster_assignment[1]==i)[0], dtype=int)
            indexes.append(index)
            sites = [ self.original_linkers[i] for i in index ]
            molecule = mgStructure.Structure.from_sites(sites)
            self.molecules.append(molecule)
        formulas = [ x.formula for x in self.molecules]
        self.linker_type = np.unique(formulas)

        # construct new MOF structure: add lable distinguishing Metal/linker, add label for linker type,
        # Step 0: add unique id for sites. In the late process, sites might be removed, so need to defined an id besides index.
        id_linkers = np.arange(len(self.original_linkers))
        self.original_linkers.add_site_property('fixed_id',id_linkers)
        id_nodes = np.arange(len(self.original_nodes))+len(self.original_linkers)
        self.original_nodes.add_site_property('fixed_id',id_nodes)

        # Step 1: label linker type
        linker_label = np.full(len(self.original_linkers),None)
        is_linker = np.full(len(self.original_linkers),True)

        for jj,molecule in enumerate(self.molecules):
            linker_type_num = np.where(self.linker_type == molecule.formula)[0]
            linker_label[indexes[jj]] = linker_type_num
        self.original_linkers.add_site_property('linker_label',linker_label)
        self.original_nodes.add_site_property('linker_label',[np.nan]*len(self.original_nodes))
        self.original_linkers.add_site_property('is_linker',is_linker)

        # Step 2 : add metal site into linker site, combined as a whole
        processed_structure_sites = []
        for site in self.original_linkers:
            processed_structure_sites.append(site)
        for site in self.original_nodes:
            processed_structure_sites.append(site)
        self.processed_structure = mgStructure.Structure.from_sites(processed_structure_sites)

        # print and summary
        # TODO: add some check function to make sure the right structure is read into the code

        print("There are %d atoms in Metal Cluster, and %d atoms in linkers, with %d linkers, %d types" \
        % ( len(self.original_nodes), len(self.original_linkers), self.linker_num, len(np.unique(formulas))))

        return None

    def _DefectDensityControl_(self):

        cell = self.original_Structure.lattice.abc
        min_index = cell.index(min(cell))
        max_index = cell.index(max(cell))
        # fix a = b = c
        if max_index==min_index:
            max_index += 1
        _mid_index = [0,1,2]
        _mid_index.remove(min_index)
        _mid_index.remove(max_index)
        mid_index = _mid_index[0]

        def assign_supercell(cellnum):
            cell = [1,1,1]
            if cellnum == 1:
                return cell
            elif cellnum ==2 or cellnum==3 or cellnum==5:
                cell[min_index] = cellnum
            elif cellnum == 6:
                cell[min_index] = 2
                cell[mid_index] = 3
            elif cellnum == 4:
                cell[min_index] = 2
                cell[mid_index] = 2
            else:
                raise "error for super cell assignment"
            return cell

        enumerate_conc = [1/2,1/3,2/3,1/4,3/4,1/5,2/5,3/5,4/5,1/6,5/6,1,2,3,4,5,6]
        corr_defect_num = [1,1,2,1,3,1,2,3,4,1,5,1,2,3,4,5,6]
        corr_cell = [2,3,3,4,4,5,5,5,5,6,6,1,1,1,1,1,1]
        original_conc = 1/self.linker_num
        desired_conc = [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]
        achived_conc = {}

        for _conc_goal_ in desired_conc:
            for i,_conc_possible_ in enumerate(enumerate_conc):
                _conc_possible2_ = original_conc*_conc_possible_
                if abs((_conc_possible2_-_conc_goal_)/_conc_goal_) < 0.3:
                    achived_conc[_conc_possible2_] = [_conc_goal_, corr_defect_num[i], corr_cell[i], assign_supercell(corr_cell[i])]
                    break

        return achived_conc

    def StructureGeneration(self, superCell, defectConc, numofdefect, linker_type):

        working_mof = copy.deepcopy(self.processed_structure)

        with open('src/charge_dict.json') as json_file:
            charge_dict = json.load(json_file)

        if self.linker_type[linker_type] in charge_dict.keys():
            charge_comp = charge_dict[self.linker_type[linker_type]]
        else:

            for molecule in self.molecules:
                if molecule.formula == self.linker_type[linker_type]:
                    vis_structure = molecule
                    break
            DebugVisualization(vis_structure)

            charge_comp = input("unseen molecular:%s, please specify charge\n"%(self.linker_type[linker_type] ))
            try:
                charge_comp = int(charge_comp)
            except:
                raise("please input num")
            charge_dict[self.linker_type[linker_type]] = charge_comp

        with open('src/charge_dict.json', 'w') as fp:
            json.dump(charge_dict, fp)

        defect_structure = DefectMOFStructure(working_mof, superCell, defectConc, numofdefect, linker_type, self.output_dir, charge_comp)
        defect_structure.Build_supercell()
        defect_structure.DefectGen()
        # defect_structure.ReverseMonteCarlo()

        return

    def LinkerVacancy(self):

        self.possible_Defect_Density = self._DefectDensityControl_()
        for i_linker,linker_type in enumerate(self.linker_type):
            for key,val in self.possible_Defect_Density.items():
                print("Currently generate linker vacancy defect with %s, at conc. of %.3f" %(linker_type,key))
                self.StructureGeneration(val[3],key,val[1], i_linker)

        return


import logging
import os
import sys
from datetime import datetime
from typing import Callable, Optional

import pytest
from pytest_embedded.plugin import multi_dut_argument, multi_dut_fixture

DEFAULT_SDKCONFIG = 'default'

@pytest.fixture(scope='session', autouse=True)
def session_tempdir() -> str:
    _tmpdir = os.path.join(
        os.path.dirname(__file__),
        'pytest_embedded_log',
        datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
    )
    os.makedirs(_tmpdir, exist_ok=True)
    return _tmpdir

@pytest.fixture
@multi_dut_argument
def config(request: pytest.FixtureRequest) -> str:
    return getattr(request, 'param', None) or DEFAULT_SDKCONFIG

@pytest.fixture
@multi_dut_fixture
def build_dir(request: pytest.FixtureRequest, app_path: str, target: Optional[str], config: Optional[str]) -> str:
    """
    Check local build dir with the following priority:

    1. build_<target>_<config>
    2. build_<target>
    3. build_<config>
    4. build

    Returns:
        valid build directory
    """
    check_dirs = []
    if target is not None and config is not None:
        check_dirs.append(f'build_{target}_{config}')
    if target is not None:
        check_dirs.append(f'build_{target}')
    if config is not None:
        check_dirs.append(f'build_{config}')
    check_dirs.append('build')

    for check_dir in check_dirs:
        binary_path = os.path.join(app_path, check_dir)
        if os.path.isdir(binary_path):
            logging.info(f'find valid binary path: {binary_path}')
            return check_dir

        logging.warning(
            'checking binary path: %s... missing... try another place', binary_path
        )

    recommend_place = check_dirs[0]
    logging.error(
        f'no build dir valid. Please build the binary via "idf.py -B {recommend_place} build" and run pytest again'
    )
    sys.exit(1)

@pytest.fixture(autouse=True)
@multi_dut_fixture
def junit_properties(test_case_name: str, record_xml_attribute: Callable[[str, object], None]) -> None:
    """
    This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
    """
    record_xml_attribute('name', test_case_name)


from django.db import models

class GlobalDB(models.Model):
    """
    Global Database includes all registered and personal contacts
    """
    phone_number = models.CharField(max_length=13, blank=False, null=True)
    country_code = models.CharField(max_length=4, blank=False, null=True)
    name = models.CharField(max_length=30, blank=False, null=True)
    email = models.EmailField(max_length=255, blank=True)
    is_registered = models.BooleanField(default=False)
    is_personal_contact = models.BooleanField(default=False)
    is_marked_as_spam = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.country_code + '-' +self.phone_number+ ': ' +self.name

    class Meta:
        ordering = [
            'id', 'name', 'is_registered', 'phone_number',
            'country_code', 'email', 'is_personal_contact', 'is_marked_as_spam'
        ]

class PersonalContact(models.Model):
    """
    Includes relation of a registered number and its personal contact
    """
    phone_number = models.CharField(max_length=13, blank=False, null=True)
    country_code = models.CharField(max_length=4, blank=False, null=True)
    contact_of = models.ForeignKey(GlobalDB,related_name='Personal2Global', blank=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.personal_contact) + ' : ' + str(self.contact_of)

class SpamDB(models.Model):
    """
    Includes number of times a number is marked as spam
    """
    phone_number = models.CharField(max_length=13, blank=False, null=True)
    country_code = models.CharField(max_length=4, blank=False, null=True)
    marked_by = models.ForeignKey(GlobalDB,related_name='Spam2Global', blank=False, on_delete=models.CASCADE)
    marked_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.spam_phone_number)+ ': ' +str(self.marked_by)


import pandas as pd
import ast
import click
from transformers import pipeline
from tqdm import tqdm

@click.command()
@click.option("--datafile", type=str, required=True, help="Path to the datafile")
@click.option(
    "--model_name_or_path",
    type=str,
    default=None,
    help="Model to be used for the generation.",
)
@click.option(
    "--output_path", type=str, required=True, help="Path to save the generations."
)
def execute(datafile, output_path, model_name_or_path=None):

    if model_name_or_path is not None:
        classifier = pipeline("zero-shot-classification", model=model_name_or_path)
    else:
        classifier = pipeline("zero-shot-classification")

    data = pd.read_csv(datafile)
    data = data.to_dict("records")

    utterances = []
    classes = []
    generations = []

    for case in tqdm(data):

        labels = ast.literal_eval(case["classes"])

        utterances.append(case["utterance"])
        classes.append(labels)

        res = classifier(case["utterance"], labels)

        label = "Unknown"
        if res["scores"][0] > 0.5:
            label = res["labels"][0]

        generations.append(label)

    df = pd.DataFrame.from_dict(
        {"utterance": utterances, "classes": classes, "snli": generations}
    )
    df.to_csv(output_path)

if __name__ == "__main__":
    execute()


def calculate():
    #taking input from user for the numbers to calculate
    a= int(input("Enter the first number: "))
    b= int(input("Enter the second number: "))
    print('''1.Addition
    2.Subtraction
    3.Multiplication
    4.Division''')
    #taking the operation as input from the user
    #using loop so that in case user has multiple operation they donot need to start over again
    while True:
        c=(input("Choose the operation(1/2/3/4/stop/restart):"))
        if c=='1':
            print( a,"+",b,"=",a+b)
        elif c=='2':
            print( a,"-",b,"=",a-b)
        elif c=='3':
            print( a,"*",b,"=",a*b)
        elif c=='4':
            print(a,"/",b,"=",a/b)
        elif c=='stop':
            break
        elif c=='restart':
            calculate()
        else:
            print("Error: invalid input.")

calculate()


import traceback
from flask import views, request, jsonify, make_response, current_app, abort
from .basehandler import BaseHandler, AuthError, LogicError, ParamsError, Dict, VerifyError, BaseError

class BaseViewHandler(views.MethodView, BaseHandler):

    @property
    def input(self):
        d = Dict(request.values.items())
        if request.is_json:
            d.update(request.json)
        return d

class ApiViewHandler(BaseViewHandler):

    def dispatch_request(self, *args, **kwargs):
        self.set_header = {}
        self.set_cookie = {}
        self.delete_cookie = []
        self.http_origin = request.environ.get('HTTP_ORIGIN', '')

        handler = getattr(self, request.method.lower(), None)

        if not callable(handler):
            if request.method == 'HEAD':
                return make_response('', 200)
            else:
                abort(405)

        return self.api_wrapper(handler, *args, **kwargs)

    def api_wrapper(self, handler, *args, **kwargs):
        code = 1000
        data = msg = None
        start_time = self.get_timestamp()
        try:
            data = handler(*args, **kwargs)
        except AuthError as e:
            code = e.code
            msg = str(e)
        except LogicError as e:
            code = e.code
            msg = str(e)
            err = traceback.format_exc()
            current_app.logger.error(err)
        except ParamsError as e:
            code = e.code
            msg = str(e)
        except VerifyError as e:
            code = e.code
            msg = str(e)
        except BaseError as e:
            code = e.code
            msg = str(e)
            err = traceback.format_exc()
            current_app.logger.error(err)
        except Exception:
            code = 5000
            msg = '系统内部错误'
            err = traceback.format_exc()
            current_app.logger.error(err)

        cost_time = self.get_timestamp() - start_time

        res = {'code': code, 'data': data, 'cost': "{0}ms".format(round(cost_time * 1000, 2))}
        if msg:
            res.update({'msg': msg})

        response = make_response(jsonify(res))

        if self.set_header:
            for k, v in self.set_header.items():
                response.headers[k] = v

        if self.set_cookie:
            for k, v in self.set_cookie.items():
                response.set_cookie(k, v)

        if self.delete_cookie:
            for k in self.delete_cookie:
                response.delete_cookie(k)

        return response


import sublime, sublime_plugin, re, urllib, random

class linkcheckCommand(sublime_plugin.TextCommand):

	def parse_url(self, url):
		request = urllib.request.Request(url)
		# request.add_header('Referer', 'https://www.google.ru/?q='+self.randomword(5))
		# request.add_header = ('User-agent', 'Googlebot/2.1 (+http://www.google.com/bot.html)')
		# urllib.request.urlcleanup()
		resorce = urllib.request.urlopen(request)
		html = resorce.read()
		return html

	def get_content(self, url):
		content = self.parse_url(url)[0]
		content_list = content.decode("utf-8").strip().splitlines()
		return content_list

	def get_response(self, url):
		req = urllib.request.Request(url)
		try:
			response = urllib.request.urlopen(req)
		except urllib.error.URLError as e:
			# print(e.reason)
			if hasattr(e, 'code'):
				return e.code
			else:
				return 0
		else:
			return 200

	def randomword(self, length):
		string = 'abcdefghijklmnopqrstuvwxyz'
		return ''.join(random.choice(string) for i in range(length))

	# Check all links in view
	def check_links(self, view):
		# Find all URL's in the view
		url_regions = view.find_all ("https?://[^\"'\s]+")

		i = 0
		for region in url_regions:
			cl = view.substr(region)

			# URL regions in selection
			if len(view.sel()[0]) > 0:
				if view.sel().contains(region):
					code = self.get_response(cl)
					view.add_regions('url'+str(i), [region], "mark", "Packages/SeoTools/icons/"+str(code)+".png", flags=sublime.DRAW_NO_FILL|sublime.DRAW_NO_OUTLINE|sublime.DRAW_SOLID_UNDERLINE)
					i = i + 1
			else:
				if len(url_regions) > 200:
					return False

				code = self.get_response(cl)
				# Region is either in the selection or there is no selection
				view.add_regions('url'+str(i), [region], "mark", "Packages/SeoTools/icons/"+str(code)+".png", flags=sublime.DRAW_NO_FILL|sublime.DRAW_NO_OUTLINE|sublime.DRAW_SOLID_UNDERLINE)
				i = i + 1
		return i

	def run(self, edit):
		logMsg = ''
		total = 0

		if not self.view.is_read_only() or self.view.size() < 1:
			total = self.check_links(self.view)

			if total > 0:
				logMsg += "Done!"
			elif total == False:
				logMsg = 'Слишком много ссылок. Выделите нужный фрагмент.'
			else:
				logMsg += "Nothing found."
		else:
			logMsg += "Empty or readonly document!"

		sublime.status_message(logMsg)
		sublime.message_dialog(logMsg)


import models

from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from playhouse.shortcuts import model_to_dict

cook = Blueprint('cooks', __name__, url_prefix='/api/v1/cooks')

@cook.route('/test', methods=["GET"])
@login_required
def index():
  print(current_user)
  return "This is a cooking app for some reason"

# Route to return users cook
@cook.route('/', methods=["GET"])
@login_required
def get_my_cook():
  try:
    cook = [model_to_dict(cook) for cook in current_user.cook]
    print(cook)
    return jsonify(data=cook, status={"code": 200, "message": "Success, here's your cook"})
  except models.DoesNotExist:
    return jsonify(data={}, status={"code": 401, "message": "Error getting your cook"})

# Get a cook by id
@cook.route('/<cookid>', methods=["GET"])
def get_some_cook(cookid):
  try:
    cook = models.Cooks.get_by_id(cookid)
    cook_dict = model_to_dict(cook)
    return jsonify(data=cook_dict, status={"code": 200, "message": "Success, have a look at your cook"})
  except models.DoesNotExist:
    return jsonify(data={}, status={"code": 401, "message": "Cook not found"})

# Create a cook
@cook.route('/', methods=["POST"])
def create_cook():
  payload = request.get_json()
  print(payload)
  print('hi')
  new_cook = models.Cooks.create(username=payload['username'], specialty=payload['specialty'], avatar=payload['avatar'], banner=payload['banner'], user=current_user.id)
  cook_dict = model_to_dict(new_cook)
  return jsonify(data=cook_dict, status={"code": 200, "message": "Cook Created"})


import os

import matplotlib.pyplot as plt
import pandas as pd

class LogParser:
    def __init__(self, input_file_name: str):
        self.input_file_name = input_file_name
        self.data = self._clean_data(self._read_file())
        self.timespan = self._get_timespan()

    def __str__(self):
        return f"Dataset: {self.input_file_name}\nSize: {self.data.shape}\nTimespan: {self.timespan}"

    def _read_file(self) -> pd.DataFrame:
        df = pd.read_csv(
            self.input_file_name, delimiter=";", low_memory=False, na_values=['=""']
        )
        return df

    def _clean_data(self, df: pd.DataFrame) -> pd.DataFrame:
        # odstranimo posebne znake
        df = df.replace('="', "", regex=True)
        df = df.replace('"', "", regex=True)
        # uredimo stolpec time
        df["Time"] = pd.to_datetime(df["Time"], format="%Y.%m.%d %H:%M:%S.%f")
        df["Original_Time"] = df["Time"]
        df = df.set_index("Time")
        # pretvorimo stolpec Type v kategorijo
        df["Type"] = df["Type"].astype("category")
        return df

    def _get_timespan(self):
        diff = self.data["Original_Time"].max() - self.data["Original_Time"].min()
        return diff

    def export_clean_data(self, export_format: str = "csv"):
        """Exports clean data to selected format (csv, json, xlsx)"""
        converted_file_name = (
            f"{os.path.splitext(self.input_file_name)[0]}-converted.{export_format}"
        )
        if export_format == "csv":
            self.data.to_csv(converted_file_name)
        elif export_format == "json":
            data_to_json = self.data.copy()
            data_to_json = data_to_json.reset_index()
            data_to_json.to_json(converted_file_name, orient="index")
        elif export_format == "xlsx":
            self.data.to_excel(converted_file_name)
        else:
            raise ValueError("Parameter export_format should be: csv, json, xlsx.")

    def type_rrep_resample_count(self, resample: int = 60) -> pd.DataFrame:
        df_log_rrep = self.data[
            self.data["Type"].str.contains("LOADNG RREP", na=False)
        ].copy()
        groups_rrep = (
            df_log_rrep["Type"]
            .resample(f"{resample}T", label="right", closed="right")
            .count()
        )
        return pd.DataFrame(groups_rrep)

    def plot_type_rrep_resample_count(self, resample=60):
        df_result = self.type_rrep_resample_count(resample)
        fig, ax = plt.subplots()
        df_result.plot(kind="bar", ax=ax, legend=False, color="red")
        ax.set_xlabel("Time")
        ax.set_ylabel("# of rrep")
        ax.set_title("rrep results")
        plt.tight_layout()
        plt.savefig(f"{self.input_file_name}_{resample}_plot.png")

if __name__ == "__main__":
    input_file = "Del_07_Generatorji/data/20200915 081812_10_2_6_26.csv"

    parser = LogParser(input_file)
    # parser.export_clean_data(export_format="json")

    # print(parser.data.head())

    print(parser.type_rrep_resample_count())
    parser.plot_type_rrep_resample_count()


import argparse

import src

def parse_args():
    parser = argparse.ArgumentParser(description="Kaggle time-series competition")
    parser.add_argument("--task", "-t", type=str)
    parser.add_argument("--config", "-c", type=str, default="conf.yaml")
    parser.add_argument("--model", "-m", type=str, default="baseline")
    parser.add_argument("--data", "-d", type=str, default="")

    args = parser.parse_args()

    return args

if __name__ == "__main__":
    args = parse_args()

    if args.task == "train":
        if args.model == "baseline":
            src.models.run_baseline()
        else:
            trainer = src.models.Trainer()

            trainer.train()
    elif args.task == "test":
        trainer = src.models.Trainer()

        trainer.test()

    elif args.task == "build_feats":
        src.features.build_feats()
    else:
        raise NotImplementedError()


import glob
import os
count = 0
for filename in glob.glob('*.png'):
	start = 'sharp_'
	count = count +1
	num = str(count)
	end = '.jpg'
	new_name = start + num + end
	os.rename(filename, new_name)


"""Color util methods."""
import logging
import math
# pylint: disable=unused-import

_LOGGER = logging.getLogger(__name__)

HASS_COLOR_MAX = 500  # mireds (inverted)
HASS_COLOR_MIN = 154
COLORS = {
    'white': (255, 255, 255), 'beige': (245, 245, 220),
    'tan': (210, 180, 140), 'gray': (128, 128, 128),
    'navy blue': (0, 0, 128), 'royal blue': (8, 76, 158),
    'blue': (0, 0, 255), 'azure': (0, 127, 255), 'aqua': (127, 255, 212),
    'teal': (0, 128, 128), 'green': (0, 255, 0),
    'forest green': (34, 139, 34), 'olive': (128, 128, 0),
    'chartreuse': (127, 255, 0), 'lime': (191, 255, 0),
    'golden': (255, 215, 0), 'red': (255, 0, 0), 'coral': (0, 63, 72),
    'hot pink': (252, 15, 192), 'fuchsia': (255, 119, 255),
    'lavender': (181, 126, 220), 'indigo': (75, 0, 130),
    'maroon': (128, 0, 0), 'crimson': (220, 20, 60)}

def color_name_to_rgb(color_name):
    """Convert color name to RGB hex value."""
    hex_value = COLORS.get(color_name.lower())

    if not hex_value:
        _LOGGER.error('unknown color supplied %s default to white', color_name)
        hex_value = COLORS['white']

    return hex_value

# Taken from:
# http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
# License: Code is given as is. Use at your own risk and discretion.
# pylint: disable=invalid-name
def color_RGB_to_xy(R, G, B):
    """Convert from RGB color to XY color."""
    if R + G + B == 0:
        return 0, 0, 0

    R = R / 255
    B = B / 255
    G = G / 255

    # Gamma correction
    R = pow((R + 0.055) / (1.0 + 0.055),
            2.4) if (R > 0.04045) else (R / 12.92)
    G = pow((G + 0.055) / (1.0 + 0.055),
            2.4) if (G > 0.04045) else (G / 12.92)
    B = pow((B + 0.055) / (1.0 + 0.055),
            2.4) if (B > 0.04045) else (B / 12.92)

    # Wide RGB D65 conversion formula
    X = R * 0.664511 + G * 0.154324 + B * 0.162028
    Y = R * 0.313881 + G * 0.668433 + B * 0.047685
    Z = R * 0.000088 + G * 0.072310 + B * 0.986039

    # Convert XYZ to xy
    x = X / (X + Y + Z)
    y = Y / (X + Y + Z)

    # Brightness
    Y = 1 if Y > 1 else Y
    brightness = round(Y * 255)

    return round(x, 3), round(y, 3), brightness

# taken from
# https://github.com/benknight/hue-python-rgb-converter/blob/master/rgb_cie.py
# Copyright (c) 2014 Benjamin Knight / MIT License.
# pylint: disable=bad-builtin
def color_xy_brightness_to_RGB(vX, vY, brightness):
    """Convert from XYZ to RGB."""
    brightness /= 255.
    if brightness == 0:
        return (0, 0, 0)

    Y = brightness

    if vY == 0:
        vY += 0.00000000001

    X = (Y / vY) * vX
    Z = (Y / vY) * (1 - vX - vY)

    # Convert to RGB using Wide RGB D65 conversion.
    r = X * 1.612 - Y * 0.203 - Z * 0.302
    g = -X * 0.509 + Y * 1.412 + Z * 0.066
    b = X * 0.026 - Y * 0.072 + Z * 0.962

    # Apply reverse gamma correction.
    r, g, b = map(
        lambda x: (12.92 * x) if (x <= 0.0031308) else
        ((1.0 + 0.055) * pow(x, (1.0 / 2.4)) - 0.055),
        [r, g, b]
    )

    # Bring all negative components to zero.
    r, g, b = map(lambda x: max(0, x), [r, g, b])

    # If one component is greater than 1, weight components by that value.
    max_component = max(r, g, b)
    if max_component > 1:
        r, g, b = map(lambda x: x / max_component, [r, g, b])

    r, g, b = map(lambda x: int(x * 255), [r, g, b])

    return (r, g, b)

def rgb_hex_to_rgb_list(hex_string):
    """Return an RGB color value list from a hex color string."""
    return [int(hex_string[i:i + len(hex_string) // 3], 16)
            for i in range(0,
                           len(hex_string),
                           len(hex_string) // 3)]

def color_temperature_to_rgb(color_temperature_kelvin):
    """
    Return an RGB color from a color temperature in Kelvin.

    This is a rough approximation based on the formula provided by T. Helland
    http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
    """
    # range check
    if color_temperature_kelvin < 1000:
        color_temperature_kelvin = 1000
    elif color_temperature_kelvin > 40000:
        color_temperature_kelvin = 40000

    tmp_internal = color_temperature_kelvin / 100.0

    red = _get_red(tmp_internal)

    green = _get_green(tmp_internal)

    blue = _get_blue(tmp_internal)

    return (red, green, blue)

def _bound(color_component, minimum=0, maximum=255):
    """
    Bound the given color component value between the given min and max values.

    The minimum and maximum values will be included in the valid output.
    i.e. Given a color_component of 0 and a minimum of 10, the returned value
    will be 10.
    """
    color_component_out = max(color_component, minimum)
    return min(color_component_out, maximum)

def _get_red(temperature):
    """Get the red component of the temperature in RGB space."""
    if temperature <= 66:
        return 255
    tmp_red = 329.698727446 * math.pow(temperature - 60, -0.1332047592)
    return _bound(tmp_red)

def _get_green(temperature):
    """Get the green component of the given color temp in RGB space."""
    if temperature <= 66:
        green = 99.4708025861 * math.log(temperature) - 161.1195681661
    else:
        green = 288.1221695283 * math.pow(temperature - 60, -0.0755148492)
    return _bound(green)

def _get_blue(tmp_internal):
    """Get the blue component of the given color temperature in RGB space."""
    if tmp_internal >= 66:
        return 255
    if tmp_internal <= 19:
        return 0
    blue = 138.5177312231 * math.log(tmp_internal - 10) - 305.0447927307
    return _bound(blue)

def color_temperature_mired_to_kelvin(mired_temperature):
    """Convert absolute mired shift to degrees kelvin."""
    return 1000000 / mired_temperature

def color_temperature_kelvin_to_mired(kelvin_temperature):
    """Convert degrees kelvin to mired shift."""
    return 1000000 / kelvin_temperature


#! /usr/bin/python

# Author: Matthew Hagen

import urllib
from xml.dom import minidom
import os
import sys
import re
from optparse import OptionParser

#parse input arguments
usage = "usage: %prog [option] arg"
parser = OptionParser(usage=usage)
parser.add_option("-f", action="store", type="string", dest="filename", help="should be teh file that outputs interpro_domain_unique.sql")
parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout")

(options, args) = parser.parse_args()

if len(args) != 0:
	sys.exit("Error parsing arguments, "+usage);

phandle = open(options.filename)

interpro_url = "http://www.ebi.ac.uk/cgi-bin/dbfetch?db=interpro&id=%s&format=interproxml"

db_filename 				= "interpro_db2.sql"
db_link_filename 			= "interpro_db_link2.sql"
pubmed_link_filename 			= "interpro_pubmed_link2.sql"
go_link_filename 			= "interpro_go_link2.sql"
go_filename 				= "interpro_go2.sql"
domain_filename 			= "interpro_domain_nen_nen_new.sql"
error_filename                          = "error_new.sql"

db_filename_handle 			= open( db_filename, 'w' )
db_link_filename_handle 		= open( db_link_filename, 'w' )
pubmed_link_filename_handle 		= open( pubmed_link_filename, 'w' )
go_link_filename_handle 		= open( go_link_filename, 'w' )
go_filename_handle 			= open( go_filename, 'w' )
domain_filename_handle 			= open( domain_filename, 'w' )
error_filename_handle                   = open(error_filename, 'w')

#parse input paths to the sequences
for line in phandle:
	ipr_id = line.rstrip()
	sys.stderr.write("Processing id "+ipr_id+"\n")

	url = interpro_url % ipr_id

	try:
		minidom.parse(urllib.urlopen(url))
		xmldoc = minidom.parse(urllib.urlopen(url))
	except:
		error_filename_handle.write(ipr_id+" "+"not found" +"\n")

	# parse each of the IDs received from interproscan to the database [interpro_url]
	# so as to use the xml data about each sequence to retrieve information about that ID.

	interproList = xmldoc.getElementsByTagName('interpro')

	interpro = interproList[0]

	id = interpro.attributes["id"].value.encode('iso-8859-1')

	type = interpro.attributes["type"].value.encode('iso-8859-1')

	name = interpro.getElementsByTagName('name')

	name = name[0].firstChild.data.encode('iso-8859-1')
	abstract = interpro.getElementsByTagName('abstract')[0]

	abstractText = ""
	abstractList = abstract.childNodes
	for abstract in abstractList:
		if (abstract.nodeType == abstract.TEXT_NODE):
			abstractText += abstract.data.encode('iso-8859-1')

	abstractText = re.sub("\s+", " ", abstractText).strip()

	output = id + "|" + name + "|" + type + "|" + abstractText
	domain_filename_handle.write(output + "\n")

	classList = interpro.getElementsByTagName('class_list')

	if (len(classList) > 0):

		classList = classList[0].getElementsByTagName('classification')

		for classification in classList:

			classId = classification.attributes["id"].value
			classType = classification.attributes["class_type"].value

			category = classification.getElementsByTagName('category')[0].firstChild.data
			description = classification.getElementsByTagName('description')[0].firstChild.data

			if (classType == "GO"):
				output = classId + "|" + category + "|" + description
				go_filename_handle.write(output + "\n")
				output = id + "|" + classId
				go_link_filename_handle.write(output + "\n")

	pubList = interpro.getElementsByTagName('pub_list')

	if (len(pubList) > 0):
		pubList = pubList[0].getElementsByTagName('publication')

		for publication in pubList:
			pubmedid = publication.getElementsByTagName('db_xref')
			if (len(pubmedid) == 0):
				continue

			pubmedid = pubmedid[0].attributes['dbkey'].value
			output = id + "|" + pubmedid

			pubmed_link_filename_handle.write(output + "\n")

	memberList = interpro.getElementsByTagName('member_list')

	if (len(memberList) > 0):
		memberList = memberList[0].getElementsByTagName('db_xref')

		for member in memberList:
			db = member.attributes['db'].value
			dbKey = member.attributes['dbkey'].value
			name = member.attributes['name'].value

			output = id + "|" + dbKey
			db_link_filename_handle.write(output + "\n")
			output = dbKey + "|" + name + "|" + db
			db_filename_handle.write(output + "\n")

db_filename_handle.close()
db_link_filename_handle.close()
pubmed_link_filename_handle.close()
go_link_filename_handle.close()
go_filename_handle.close()
domain_filename_handle.close()
error_filename_handle.close()


import requests
url="https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
resp=requests.get(url)
resp.status_code

with open('image.jpg', 'wb') as fp:
    fp.write(resp.content)

def download(url, filename):
    try:
        resp = requests.get(url)
        if resp.status_code==200:
            with open(filename, 'wb') as fp:
                fp.write(resp.content)
                print("Image downloaded Successfully")
        else:
            return "Invalid Url"
    except Exception as error:
        return error
# url1=input("Enter the url= ")
# format=".jpg"
# filename1= input("Enter the file name you want= ")
# download(url1,filename1)

download("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg","tree.jpg")


from odoo import api, fields, models

class ProductTemplate(models.Model):
    _inherit = "product.template"

    website_use_main_extra_image = fields.Boolean(
        string="Use extra media as shop image",
        help="Use the extra media instead of the product image in the website."
        + " Mark the checkbox 'Main image' of the desired extra media attachment.",
        default=False,
    )

    @api.depends("website_use_main_extra_image", "product_template_image_ids")
    def _compute_website_image_ids(self):
        for record in self:
            main_image = False
            mouseover_image = False
            if record.website_use_main_extra_image:
                # there is some inconsistent behavior resulting in access permission
                # errors when vising the same shop page again
                # Due to security restrictions, you are not allowed to access 'Product' (product.template) records
                # although the product is fully published. It does not happen when
                # refreshing the page.
                record_sudo = record.sudo()
                for pti in record_sudo.product_template_image_ids:
                    if not main_image and pti.main_image:
                        main_image = pti
                    if not mouseover_image and pti.mouseover_image:
                        mouseover_image = pti
                    if main_image and mouseover_image:
                        break

            if main_image:
                record.website_product_image_id = main_image[0]
            else:
                record.website_product_image_id = False
            if mouseover_image:
                record.website_mouseover_image_id = mouseover_image[0]
            else:
                record.website_mouseover_image_id = False

    website_product_image_id = fields.One2many(
        "product.image", string="Main Image", compute=_compute_website_image_ids
    )

    website_mouseover_image_id = fields.One2many(
        "product.image", string="Mouseover Image", compute=_compute_website_image_ids
    )

    def _get_images(self, details_view=False):
        self.ensure_one()
        if details_view:
            images = list(
                self.product_template_image_ids.filtered(
                    lambda pti: pti.use_in_details_view
                )
            )
        else:
            images = list(self.product_template_image_ids)

        if self.website_use_main_extra_image:
            return images
        else:
            return [self] + images

    def _get_image_holder(self):
        self.ensure_one()
        if self.website_use_main_extra_image and self.website_product_image_id:
            return self.website_product_image_id
        if not isinstance(self.id, models.NewId):
            return super()._get_image_holder()
        return None


from collections import defaultdict
class Solution:
    def numFactoredBinaryTrees(self, arr: List[int]) -> int:
        # sumi = len(arr)
        mod = 10**9 + 7
        n = len(arr)
        arr.sort()
        d = defaultdict()
        for num in arr:
            d[num] = d.get(num, 0) + 1

        for i in range(1,n):
            for j in range(i+1):
                if arr[i] % arr[j] == 0 and (arr[i] / arr[j]) in d:
                    d[arr[i]] += d[arr[j]] * d[arr[i]/arr[j]]

        return sum(d.values()) % mod


# Regular Expression II
# https://www.interviewbit.com/problems/regular-expression-ii/
#
# Implement regular expression matching with support for '.' and '*'.
#
# '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
#
# The matching should cover the entire input string (not partial).
#
# The function prototype should be:
#
# int isMatch(const char *s, const char *p)
#
# Some examples:
#
# isMatch("aa","a") → 0
# isMatch("aa","aa") → 1
# isMatch("aaa","aa") → 0
# isMatch("aa", "a*") → 1
# isMatch("aa", ".*") → 1
# isMatch("ab", ".*") → 1
# isMatch("aab", "c*a*b") → 1
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

class Solution:
    # @param A : string
    # @param B : string
    # @return an integer
    # dp[i][j] does i chars of b match j chars of a
    def isMatch(self, A, B):

        m, n = len(A), len(B)

        dp = [[False] + [False] * m for _ in range(n + 1)]
        dp[0][0] = True

        for i in range(1, n + 1):
            if B[i - 1] == '.':
                for j in range(1, m + 1):
                    dp[i][j] = dp[i - 1][j - 1]
            elif B[i - 1] == '*':
                last = B[i - 2]
                for j in range(1, m + 1):
                    if dp[i - 2][j] or dp[i - 1][j]:
                        dp[i][j] = True
                    elif A[j - 1] == last or last == '.':
                        dp[i][j] = dp[i][j - 1]
            else:
                for j in range(1, m + 1):
                    dp[i][j] = dp[i - 1][j - 1] if A[j - 1] == B[i - 1] else False

        return int(dp[-1][-1])

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

if __name__ == "__main__":
    s = Solution()
    print(s.isMatch('a', 'a'))
    print(s.isMatch("aa", "a"))
    print(s.isMatch("aa", "aa"))
    print(s.isMatch("aaa", "aa"))
    print(s.isMatch("aaa", "aa."))
    print(s.isMatch("aaa", "aa.."))
    print(s.isMatch("aa", "a*"))
    print(s.isMatch("aa", ".*"))
    print(s.isMatch("ab", ".*"))
    print(s.isMatch("abbbc", "ab*c"))
    print(s.isMatch("aab", "c*a*b"))


import asyncio
from asyncio import CancelledError, Queue

import pytest

from busrouter.router import (
    NokResponse,
    OkResponse,
    PublishRequest,
    PublishResponse,
    RouteSegment,
    SubscribeRequest,
    UnsubscribeAllRequest,
    UnsubscribeRequest,
    add_route,
    match_route,
    remove_route,
    remove_routes,
    route,
)

@pytest.mark.parametrize(
    "sub,pub,matches",
    [
        ["hello", "hello", True],
        ["hello/world", "hello/world", True],
        ["hello", "hello/world", False],
        ["hello/world", "hello", False],
        ["something/else", "#", True],
        ["#", "something/else", True],
        ["#", "#", True],
        ["#", "+", True],
        ["hello/+/world", "hello/nice/world", True],
        ["hello/nice/world", "hello/+/world", True],
        ["hello/+/world", "hello/nice/not", False],
    ],
)
def test_match_route(sub, pub, matches):
    route_map = RouteSegment()
    queue = object()
    add_route(route_map, sub, queue)
    if matches:
        assert match_route(route_map, pub) == [queue]
    else:
        assert match_route(route_map, pub) == []

def test_add_route():
    route_map = RouteSegment()
    queue = object()
    topic = "hello/world"
    add_route(route_map, topic, queue)

    assert "hello" in route_map
    assert "world" in route_map["hello"]
    assert route_map["hello"]["world"].routes == [queue]

def test_remove_route():
    route_map = RouteSegment()
    queue = object()
    queue2 = object()
    topic = "hello/world"
    topic2 = "other/world"
    add_route(route_map, topic, queue)
    add_route(route_map, topic2, queue)
    add_route(route_map, topic, queue2)
    add_route(route_map, topic2, queue2)

    assert route_map["hello"]["world"].routes == [queue, queue2]
    assert route_map["other"]["world"].routes == [queue, queue2]

    remove_route(route_map, topic, queue)
    assert route_map["hello"]["world"].routes == [queue2]
    assert route_map["other"]["world"].routes == [queue, queue2]

    remove_routes(route_map, queue2)
    assert route_map["hello"]["world"].routes == []
    assert route_map["other"]["world"].routes == [queue]

@pytest.mark.asyncio
async def test_subscribe_and_unsubscribe_request():
    request_queue = Queue()
    response_queue = Queue()
    topic = "cool/topic"
    router = asyncio.create_task(route(request_queue))
    await request_queue.put((response_queue, SubscribeRequest(topic)))
    response = await response_queue.get()
    assert isinstance(response, OkResponse)

    await request_queue.put((response_queue, UnsubscribeRequest(topic)))
    response = await response_queue.get()
    assert isinstance(response, OkResponse)

    router.cancel()
    try:
        await router
    except CancelledError:
        pass

@pytest.mark.asyncio
async def test_unsubscribe_request_error():
    request_queue = Queue()
    response_queue = Queue()
    topic = "cool/topic"
    router = asyncio.create_task(route(request_queue))

    await request_queue.put((response_queue, UnsubscribeRequest(topic)))
    response = await response_queue.get()
    assert isinstance(response, NokResponse)

    router.cancel()
    try:
        await router
    except CancelledError:
        pass

@pytest.mark.asyncio
async def test_unsubscribe_all_request():
    request_queue = Queue()
    response_queue = Queue()
    router = asyncio.create_task(route(request_queue))

    await request_queue.put((response_queue, UnsubscribeAllRequest()))
    response = await response_queue.get()
    assert isinstance(response, OkResponse)

    router.cancel()
    try:
        await router
    except CancelledError:
        pass

@pytest.mark.asyncio
async def test_publish():
    request_queue = Queue()
    pub_response_queue = Queue()
    sub_response_queue = Queue()
    router = asyncio.create_task(route(request_queue))
    sub_topic = "pubtest/+/topic"
    pub_topic = "pubtest/something/topic"

    message = b"testmsg"

    await request_queue.put((sub_response_queue, SubscribeRequest(sub_topic)))
    assert isinstance(await sub_response_queue.get(), OkResponse)
    await request_queue.put((pub_response_queue, PublishRequest(pub_topic, message)))
    assert isinstance(await pub_response_queue.get(), OkResponse)

    response = await sub_response_queue.get()
    assert isinstance(response, PublishResponse)
    assert response.topic == pub_topic
    assert response.message == message

    router.cancel()
    try:
        await router
    except CancelledError:
        pass


arr = []
size = int(input("Enter the Size of an Array: "))
print("Enter Negative and Positive Number in an Array: ")
for i in range(size):
    num = int(input())
    arr.append(num)

print("The Array is ", arr)

neg_arr = []
pos_arr = []

for i in arr:
    if i<0:
        neg_arr.append(i)
    else:
        pos_arr.append(i)
print("Sorted Negative and Positive Array is ", neg_arr+pos_arr)


import numpy as np
import cv2
cap=cv2.VideoCapture("./video/10-1.mp4")
kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
bgsubmog=cv2.bgsegm.createBackgroundSubtractorMOG()
cars = []
carno=0
def center(x,y,w,h):
    x1=int(w/2)
    y1=int(h/2)
    cx=x+x1
    cy=y+y1
    return cx,cy

while True:

    ret,frame=cap.read()
    if(ret==True):
        #灰度
        cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        #去噪（高斯）
        blur=cv2.GaussianBlur(frame,(3,3),5)
        #去背影
        mask=bgsubmog.apply(blur)
        #腐蚀,去掉图中的小方块
        erode=cv2.erode(mask,kernel)
        #膨胀
        dilate=cv2.dilate(erode,kernel,iterations=2)
        #闭操作，去掉物体内部的小块
        close=cv2.morphologyEx(dilate,cv2.MORPH_CLOSE,kernel)
        close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)
        #查找轮廓
        cnts,h=cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        cv2.line(frame,(10,600),(1200,600),(255,0,0),3)
        for (i,c) in enumerate(cnts):
            (x,y,w,h)=cv2.boundingRect(c)
            #对车辆的宽和高进行判断，验证是否为有效车辆
            isValid=(w>90)and(h>90)
            if (not isValid):
                continue
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cpoint=center(x,y,w,h)
            cars.append(cpoint)
            cv2.circle(frame,(cpoint),5,(0,0,255),-1)
            for (x,y) in cars:
                print(x,y)
                #要有一条线
                if(y>542) and (y<558):
                    carno+=1
                    cars.remove((x,y))
                    print(carno)

        cv2.putText(frame,"cars count:"+str(carno),(500,60),cv2.FONT_HERSHEY_SIMPLEX,2,(255,0,0),5)
        cv2.imshow("video",frame)
        # cv2.imshow("erode",erode)
        # cv2.imshow("dilate", dilate)

    key=cv2.waitKey(1)
    if (key==27):
        break

cap.release()
cv2.destroyAllWindows()

10.车辆识别项目/1.项目实战.py


# Freelancer (1.3) by Taragoth
# Released 11 July 2011
# Edits by Caba'drin 14 Dec 2011
# Mod-Merger'd by Windyplains, Monnikje and Caba'drin

from header_common import *
from header_operations import *
from module_constants import *
from module_constants import *
from header_parties import *
from header_skills import *
from header_items import *
from header_troops import ca_intelligence
from header_mission_templates import grc_infantry, grc_archers, grc_cavalry

####################################################################################################################
# scripts is a list of script records.
# Each script record contains the following two fields:
# 1) Script id: The prefix "script_" will be inserted when referencing scripts.
# 2) Operation block: This must be a valid operation block. See header_operations.py for reference.
####################################################################################################################

scripts = [
#+freelancer start
  ("freelancer_attach_party",
    [
	    #prepare player to be part of lord's party
        (party_attach_to_party, "p_main_party", "$enlisted_party"),
        (set_camera_follow_party, "$enlisted_party"),
        (party_set_flags, "$enlisted_party", pf_always_visible, 1),
        (disable_party, "p_main_party"),

		#initialize service variable
		(assign, "$freelancer_state", 1),
    ]),

  ("freelancer_detach_party",
    [
	    #removes player from commanders party
		(enable_party, "p_main_party"),
        (party_detach, "p_main_party"),

		(try_begin),
			(party_is_active, "$enlisted_party"),
			(party_relocate_near_party, "p_main_party", "$enlisted_party", 2),
			(party_set_flags, "$enlisted_party", pf_always_visible, 0),
		(try_end),

		(troop_set_slot, "trp_player", slot_troop_leaded_party, "p_main_party"),

	    (set_camera_follow_party, "p_main_party"),
		(assign, "$g_player_icon_state", pis_normal),
	]),

# ADDS THE PLAYER TO THE LORD'S PARTY
  ("freelancer_event_player_enlists",
    [
		(party_clear, "p_freelancer_party_backup"),
       	(call_script, "script_party_copy", "p_freelancer_party_backup", "p_main_party"),
		(remove_member_from_party, "trp_player","p_freelancer_party_backup"),

        #needed to stop bug where parties attack the old player party
        (call_script, "script_set_parties_around_player_ignore_player", 2, 4),
        #set lord as your commander
		(assign, "$enlisted_lord", "$g_talk_troop"),
		(troop_get_slot, "$enlisted_party", "$enlisted_lord", slot_troop_leaded_party),
        #removes troops from player party
        (party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
        (try_for_range_backwards, ":cur_stack", 1, ":num_stacks"), #lower bound is 1 to ignore player character
           (party_stack_get_troop_id, ":cur_troops", "p_main_party", ":cur_stack"),
           (party_stack_get_size, ":cur_size", "p_main_party", ":cur_stack"),
           (party_remove_members, "p_main_party", ":cur_troops", ":cur_size"),
        (try_end),

		#set faction relations to allow player to join battles
        (store_troop_faction, ":commander_faction", "$enlisted_lord"),
		(try_begin),
			(store_relation, ":player_relation", ":commander_faction", "fac_player_supporters_faction"),
			(lt, ":player_relation", 5),
			(call_script, "script_set_player_relation_with_faction", ":commander_faction", 5),
		(try_end),
        (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
           (neq, ":commander_faction", ":cur_faction"),
		   (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
		   (store_relation, ":player_relation", ":cur_faction", "fac_player_supporters_faction"),
		   (ge, ":player_relation", 0),
           (call_script, "script_set_player_relation_with_faction", ":cur_faction", -5),
        (try_end),

        #adds standard issued equipment
		(try_begin),
			(neg|faction_slot_eq, ":commander_faction", slot_faction_freelancer_troop, 0),
			(faction_get_slot, "$player_cur_troop", ":commander_faction", slot_faction_freelancer_troop),
		(else_try),
			(faction_get_slot, "$player_cur_troop", ":commander_faction", slot_faction_tier_1_troop),
		(try_end),
		(call_script, "script_freelancer_equip_troop", "$player_cur_troop"),

		(call_script, "script_freelancer_attach_party"),
		#makes Lords banner the players
		(troop_get_slot, ":banner", "$enlisted_lord", slot_troop_banner_scene_prop),
		(try_begin),
		  (this_or_next|eq, "$g_player_banner_granted", 1),
		  (eq, "$background_type", cb_noble),
		  (troop_get_slot, ":noble_banner", "trp_player", slot_troop_banner_scene_prop),
		  (quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_banner_backup, ":noble_banner"),
		(else_try),
		  (quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_banner_backup, 0),
		(try_end),
		(troop_set_slot, "trp_player", slot_troop_banner_scene_prop, ":banner"),
       # (display_message, "@You have been enlisted!"),

        (str_store_troop_name_link, s13, "$enlisted_lord"),
		(str_store_faction_name_link, s14, ":commander_faction"),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_target_party, "$enlisted_party"),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_importance, 5),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_xp_reward, 1000),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_gold_reward, 100),
		(setup_quest_text, "qst_freelancer_enlisted"),
		(str_clear, s2), #description. necessary?
        (call_script, "script_start_quest", "qst_freelancer_enlisted", "$enlisted_lord"),
		(str_store_troop_name, s5, "$player_cur_troop"),

        (str_store_string, s1, "@Enlisted as a {s5} in the party of {s13} of {s14}."),
		(add_troop_note_from_sreg, "trp_player", 3, s1, 0),

		(str_store_string, s5, "@Current rank: {s5}"),
        (add_quest_note_from_sreg, "qst_freelancer_enlisted", 3, s5, 1),

	    #initialize service variables
		(call_script, "script_freelancer_get_upgrade_xp", "$player_cur_troop"),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_upgrade_xp, reg0),
        (troop_get_xp, reg0, "trp_player"),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_start_xp, reg0),
        (store_current_day, reg0),
        (quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_start_date, reg0),
		(party_get_morale, reg0, "p_main_party"),
		(quest_set_slot, "qst_freelancer_enlisted", slot_quest_freelancer_orig_morale, reg0),

		(assign, "$g_infinite_camping", 1),
        (rest_for_hours_interactive, 24 * 365, 5, 1),
    ]),

#  RUNS IF THE PLAYER LEAVES THE ARMY

  ("freelancer_event_player_discharge",
    [
		#removes faction relation given at enlist
		(store_troop_faction, ":commander_faction", "$enlisted_lord"),
		(call_script, "script_change_player_relation_with_faction_ex", ":commander_faction", 5),
		(try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
            (neq, ":commander_faction", ":cur_faction"),
			(faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
			(store_relation, ":player_relation", ":cur_faction", "fac_player_supporters_faction"),
			(lt, ":player_relation", 0),
            (call_script, "script_set_player_relation_with_faction", ":cur_faction", 0),
        (try_end),
		(call_script, "script_freelancer_unequip_troop", "$player_cur_troop"),
		(troop_equip_items, "trp_player"),

		(try_begin),
			(this_or_next|eq, "$g_player_banner_granted", 1),
			(eq, "$background_type", cb_noble),
			(quest_get_slot, ":noble_banner", "qst_freelancer_enlisted", slot_quest_freelancer_banner_backup),
			(troop_set_slot, "trp_player", slot_troop_banner_scene_prop, ":noble_banner"),
		(else_try),
			(troop_set_slot, "trp_player", slot_troop_banner_scene_prop, 0),
		(try_end),
		(assign, "$freelancer_state", 0),
		(call_script, "script_freelancer_detach_party"),
		(call_script, "script_party_restore"),
		(rest_for_hours, 0,0,0),
		(display_message, "@You have left your commander!"),

		(store_current_day, ":day"),
        (quest_get_slot, reg0, "qst_freelancer_enlisted", slot_quest_freelancer_start_date),
		(val_sub, ":day", reg0),
		(val_mul, ":day", 100),
		(val_div, ":day", 60),

		(call_script, "script_finish_quest", "qst_freelancer_enlisted", ":day"), #percentage of days served, based on 60 days
		(set_show_messages, 0),
		(try_for_range, ":quest", freelancer_quests_begin, freelancer_quests_end),
			(check_quest_active, ":quest"),
			(call_script, "script_cancel_quest", ":quest"),
		(try_end),
		(set_show_messages, 1),

		(str_clear, s1),
		(add_troop_note_from_sreg, "trp_player", 3, s1),
    ]),

#  RUNS IF THE PLAYER GOES ON VACATION

  ("freelancer_event_player_vacation",
   [
		#removes faction relation given at enlist
		(store_troop_faction, ":commander_faction", "$enlisted_lord"),
		(try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
            (neq, ":commander_faction", ":cur_faction"),
			(faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
            (call_script, "script_set_player_relation_with_faction", ":cur_faction", 0),
        (try_end),

		(assign, "$freelancer_state", 2),
		(call_script, "script_freelancer_detach_party"),
		(call_script, "script_party_restore"),
		(rest_for_hours, 0,0,0),
		#(display_message, "@You have been granted leave!"),

		(str_store_troop_name_link, s13, "$enlisted_lord"),
		(str_store_faction_name_link, s14, ":commander_faction"),
		(quest_set_slot, "qst_freelancer_vacation", slot_quest_target_party, "$enlisted_party"),
		#(quest_set_slot, "qst_freelancer_vacation", slot_quest_importance, 0),
		#(quest_set_slot, "qst_freelancer_vacation", slot_quest_xp_reward, 50),
		(quest_set_slot, "qst_freelancer_vacation",	slot_quest_expiration_days, 14),
		(setup_quest_text, "qst_freelancer_vacation"),
		(str_clear, s2), #description. necessary?
        (call_script, "script_start_quest", "qst_freelancer_vacation", "$enlisted_lord"),
		(str_store_string, s5, "@If you do not return to your commander in time, you will be declared a deserter."),
        (add_quest_note_from_sreg, "qst_freelancer_vacation", 3, s5, 0),
    ]),

# RUNS WHEN PLAYER RETURNS FROM VACATION

  ("freelancer_event_player_returns",
    [
	   (store_script_param_1, ":returning_from"),

		#needed to stop bug where parties attack the old player party
        (call_script, "script_set_parties_around_player_ignore_player", 2, 4),

	    (call_script, "script_party_copy", "p_freelancer_party_backup", "p_main_party"),
		(remove_member_from_party, "trp_player","p_freelancer_party_backup"),

        #removes troops from player party #Caba--could use party_clear? and then add the player back?
        (party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
        (try_for_range_backwards, ":cur_stack", 1, ":num_stacks"), #lower bound is 1 to ignore player character
           (party_stack_get_troop_id, ":cur_troops", "p_main_party", ":cur_stack"),
           (party_stack_get_size, ":cur_size", "p_main_party", ":cur_stack"),
           (party_remove_members, "p_main_party", ":cur_troops", ":cur_size"),
        (try_end),

        #To fix any errors of the lord changing parties
		(troop_get_slot, "$enlisted_party", "$enlisted_lord", slot_troop_leaded_party),

		#set faction relations to allow player to join battles
		(store_troop_faction, ":commander_faction", "$enlisted_lord"),
		(try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
           (neq, ":commander_faction", ":cur_faction"),
		   (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
           (call_script, "script_set_player_relation_with_faction", ":cur_faction", -5),
        (try_end),
		(try_begin),
			(store_relation, ":player_relation", ":commander_faction", "fac_player_supporters_faction"),
			(lt, ":player_relation", 5),
			(call_script, "script_set_player_relation_with_faction", ":commander_faction", 5),
		(try_end),

		(call_script, "script_freelancer_attach_party"),
		(display_message, "@You have rejoined your commander!"),
		(try_begin),
			(eq, ":returning_from", plyr_mission_vacation),
			(call_script, "script_finish_quest", "qst_freelancer_vacation", 100),
		(else_try),
			(eq, ":returning_from", plyr_mission_captured),
			(call_script, "script_finish_quest", "qst_freelancer_captured", 100),
		(try_end),
    ]),

  ("freelancer_event_player_revolts",
   [
	#revert parties to former settings
	(call_script, "script_freelancer_detach_party"),
	(call_script, "script_freelancer_event_player_deserts"),

	#to prevent companions from being lost forever
	(call_script, "script_party_restore"),
	(party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
	(try_for_range_backwards, ":cur_stack", 0, ":num_stacks"),
		(party_stack_get_troop_id, ":return_troop", "p_main_party", ":cur_stack"),
		(neg|troop_is_hero, ":return_troop"),
		(party_stack_get_size, ":stack_size", "p_main_party", ":cur_stack"),
		(party_remove_members, "p_main_party", ":return_troop", ":stack_size"),
	(try_end),

	#adds other troops to join player revolt
	(call_script, "script_get_desert_troops"),

	#decreases player relation to his commander and faction
	(call_script, "script_change_player_relation_with_troop", "$enlisted_lord", -10),

	(store_troop_faction, ":commander_faction", "$enlisted_lord"),
	(try_begin),
		(party_get_battle_opponent, ":commander_enemy", "$enlisted_party"),
		(gt, ":commander_enemy", 0),
		(store_faction_of_party, ":other_faction", ":commander_enemy"),
		(store_relation, ":relation", ":other_faction", ":commander_faction"),
		(store_sub, ":mod_relation", 100, ":relation"),
		(val_add, ":mod_relation", 5),
		(call_script, "script_change_player_relation_with_faction_ex", ":commander_faction", ":mod_relation"),
	(try_end),

	(assign, "$freelancer_state", 0),

	(str_store_troop_name_link, s13, "$enlisted_lord"),
	(str_store_faction_name_link, s14, ":commander_faction"),
	(quest_set_slot, "qst_freelancer_revolt", slot_quest_target_party, 0), #changed to revolting prisoner's party if player chooses
	(quest_set_slot, "qst_freelancer_revolt", slot_quest_target_troop, "$enlisted_lord"),
	(setup_quest_text, "qst_freelancer_revolt"),
	(str_clear, s2), #description. necessary?
	(call_script, "script_start_quest", "qst_freelancer_revolt", "trp_player"),
	]),

  # RUNS IF PLAYER DESERTS OR IS AWOL
  ("freelancer_event_player_deserts",
   [
   	(try_begin),
		(neg|party_is_active, "p_main_party"),
		(call_script, "script_freelancer_detach_party"),
	(try_end),

	(store_troop_faction, ":commander_faction", "$enlisted_lord"),
	(call_script, "script_change_player_relation_with_faction_ex", ":commander_faction", -10),
    (call_script, "script_change_player_relation_with_troop", "$enlisted_lord", -10),
    (call_script, "script_change_player_honor", -20),

	(faction_set_slot, ":commander_faction", slot_faction_freelancer_troop, 0),
	(try_begin),
		(this_or_next|eq, "$g_player_banner_granted", 1),
		(eq, "$background_type", cb_noble),
		(quest_get_slot, ":noble_banner", "qst_freelancer_enlisted", slot_quest_freelancer_banner_backup),
		(troop_set_slot, "trp_player", slot_troop_banner_scene_prop, ":noble_banner"),
	(else_try),
		(troop_set_slot, "trp_player", slot_troop_banner_scene_prop, 0),
	(try_end),
	(rest_for_hours, 0,0,0),
	(assign, "$freelancer_state", 0),
	#(display_message, "@You have deserted your commander!"), #Taken care of elsewhere
	(set_show_messages, 0),
	(try_for_range, ":quest", freelancer_quests_begin, freelancer_quests_end),
		(check_quest_active, ":quest"),
		(call_script, "script_fail_quest", ":quest"),
		(call_script, "script_end_quest", ":quest"),
	(try_end),
	(set_show_messages, 1),
	(str_clear, s1),
    (add_troop_note_from_sreg, "trp_player", 3, s1),
   ]),

  ("freelancer_event_player_captured",
    [
        ##bug fix for player getting duplicated when taken prisoner--likely unnecessary & fixed elsewhere
		(try_begin),
			(troop_slot_ge, "trp_player", slot_troop_prisoner_of_party, 1),
			(troop_get_slot, ":party_no", "trp_player", slot_troop_prisoner_of_party),
			(call_script, "script_remove_troop_from_prison", "trp_player"),
			(party_is_active, ":party_no"),
			(party_count_prisoners_of_type, reg0, ":party_no", "trp_player"),
			(gt, reg0, 0),
			(party_remove_prisoners, ":party_no", "trp_player", reg0),
			(gt, reg0, 0), #number removed
		(else_try),
			(try_for_parties, ":party_no"),
				(party_count_prisoners_of_type, reg0, ":party_no", "trp_player"),
				(gt, reg0, 0),
				(party_remove_prisoners, ":party_no", "trp_player", reg0),
			(try_end),
		(try_end),

    	#removes faction relation given at enlist
		(store_troop_faction, ":commander_faction", "$enlisted_lord"),
		(try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
            (neq, ":commander_faction", ":cur_faction"),
			(faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
            (call_script, "script_set_player_relation_with_faction", ":cur_faction", 0),
        (try_end),

		(call_script, "script_freelancer_detach_party"),
		(call_script, "script_party_restore"),
		#remove non-companions. they are lost if you are defeated
		(party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
        (try_for_range_backwards, ":cur_stack", 0, ":num_stacks"),
			(party_stack_get_troop_id, ":return_troop", "p_main_party", ":cur_stack"),
			(neg|troop_is_hero, ":return_troop"),
			(party_stack_get_size, ":stack_size", "p_main_party", ":cur_stack"),
			(party_remove_members, "p_main_party", ":return_troop", ":stack_size"),
		(try_end),
		(assign, "$enlisted_party", 0),
	    (assign, "$freelancer_state", 2),
		(display_message, "@You have been captured! Escape and rejoin your commander!"),

		(str_store_troop_name_link, s13, "$enlisted_lord"),
		(str_store_faction_name_link, s14, ":commander_faction"),
		(quest_set_slot, "qst_freelancer_captured", slot_quest_target_troop, "$enlisted_lord"),
		(quest_set_slot, "qst_freelancer_captured", slot_quest_object_center, "$g_enemy_party"),
		(store_faction_of_party, ":enemy_faction", "$g_enemy_party"),
		(quest_set_slot, "qst_freelancer_captured", slot_quest_object_faction, ":enemy_faction"),
		(quest_set_slot, "qst_freelancer_captured", slot_quest_importance, 0),
		(quest_set_slot, "qst_freelancer_captured", slot_quest_xp_reward, 100),
		(quest_set_slot, "qst_freelancer_captured",	slot_quest_expiration_days, 20),
		(setup_quest_text, "qst_freelancer_captured"),
		(str_clear, s2), #description. necessary?
        (call_script, "script_start_quest", "qst_freelancer_captured", "$enlisted_lord"),
		(str_store_string, s5, "@If you do not return to your commander in time, you will be declared a deserter."),
        (add_quest_note_from_sreg, "qst_freelancer_captured", 3, s5, 0),
    ]),

  # RETURNS PART OF THE ORIGINAL PARTY
  ("party_restore",
    [
        (store_current_day, ":cur_day"),
        #formula for soldier desertion chance
		(quest_get_slot, ":service_day_start", "qst_freelancer_enlisted", slot_quest_freelancer_start_date),
        (store_sub, ":service_length", ":cur_day", ":service_day_start"), #gets number of days served
		(quest_get_slot, ":morale", "qst_freelancer_enlisted", slot_quest_freelancer_orig_morale),
        (store_add, ":return_chance", 800, ":morale"), #up to 100
        (val_sub, ":return_chance", ":service_length"), #up to far over 100

        #loop that looks at each troop stack in a party,
        #then decides if troops of that stack will return,
        #and randomly assigns a number of troops in that stack to return
        (party_get_num_companion_stacks, ":num_stacks", "p_freelancer_party_backup"),
        (try_for_range, ":cur_stack", 0, ":num_stacks"),
			(assign, ":stack_amount", 0),
			(party_stack_get_troop_id, ":return_troop", "p_freelancer_party_backup", ":cur_stack"),
			(neq, ":return_troop", "trp_player"),
			(try_begin),
				(troop_is_hero, ":return_troop"), #bugfix for companions (simple, they always return)
				(assign, ":stack_amount", 1),
			(else_try),
				#limit may need changed for more accurate probability
				(store_random_in_range, ":return_random", 0, 1000),
				(is_between, ":return_random", 0, ":return_chance"),
				(party_stack_get_size, ":stack_size", "p_freelancer_party_backup", ":cur_stack"),
				#checks what chance there is that all troops in stack will return
				(store_random_in_range, ":return_random", 0, 1000),
				(try_begin),
					(is_between, ":return_random", 0, ":return_chance"),
					(assign, ":stack_amount", ":stack_size"),
				(else_try),
					#else random number of troops return
					(store_random_in_range, ":stack_amount", 0, ":stack_size"),
				(try_end),
			(try_end),
			(ge, ":stack_amount", 1),
			(party_add_members, "p_main_party", ":return_troop", ":stack_amount"),
        (try_end),
		(party_clear, "p_freelancer_party_backup"),
		(try_for_range, ":companion", companions_begin, companions_end),
			(troop_slot_eq, ":companion", slot_troop_occupation, slto_player_companion),
			(neg|main_party_has_troop, ":companion"),
			(troop_set_slot, ":companion", slot_troop_days_on_mission, 0),
			(troop_set_slot, ":companion", slot_troop_current_mission, npc_mission_rejoin_when_possible),
			(troop_set_slot, ":companion", slot_troop_mission_object, 0),
		(try_end),
    ]),

#  CALCULATES NUMBER OF DESERTING TROOPS

   ("get_desert_troops", #CABA - check this
    [
        (party_get_morale, ":commander_party_morale", "$enlisted_party"), #does this actually get tracked for non-player parties?
        (store_current_day, ":cur_day"),
        #formula for soldier desertion chance
        #gets number of days served
		(quest_get_slot, ":service_day_start", "qst_freelancer_enlisted", slot_quest_freelancer_start_date),
        (store_sub, ":service_length", ":cur_day", ":service_day_start"),
        #inverts the commander's party morale
        (store_sub, ":commander_neg_morale", 100, ":commander_party_morale"), #still a positive number... 100-80 = 20
        (store_skill_level, ":cur_leadership", "skl_leadership", "trp_player"),
        (store_skill_level, ":cur_persuasion", "skl_persuasion", "trp_player"),
        #had to multiply these skills to give them a decent effect on desertion chance
        (val_mul, ":cur_leadership", 10), #up to 100
        (val_mul, ":cur_persuasion", 10), #up to 100
        (store_add, ":desert_chance", ":cur_leadership", ":cur_persuasion"), #up to 200
		(val_add, ":desert_chance", ":service_length"), #up to 400 maybe
        (val_add, ":desert_chance", ":commander_neg_morale"), #up to 450, maybe? if party morale is down to 50
        #loop that looks at each troop stack in a party,
        #then decides if troops of that stack will desert,
        #and randomly assigns a number of troops in that stack to desert
        (party_get_num_companion_stacks, ":num_stacks", "$enlisted_party"),
        (try_for_range_backwards, ":cur_stack", 1, ":num_stacks"),
            #limit may need changed for more accurate probability
            (store_random_in_range, ":desert_random", 0, 1000),
            (is_between, ":desert_random", 0, ":desert_chance"),
			#switching deserting troops to player party
			(party_stack_get_troop_id, ":desert_troop", "$enlisted_party", ":cur_stack"),
			(party_stack_get_size, ":stack_size", "$enlisted_party", ":cur_stack"),
			(store_random_in_range, ":stack_amount", 0, ":stack_size"),
			(party_remove_members, "$enlisted_party", ":desert_troop", ":stack_amount"),
			(party_add_members, "p_main_party", ":desert_troop", ":stack_amount"),
        (try_end),
    ]),

  ("freelancer_keep_field_loot",
   [
	(get_player_agent_no, ":player"),
	(try_for_range, ":ek_slot", ek_item_0, ek_head),
		(agent_get_item_slot, ":item", ":player", ":ek_slot"),
		(gt, ":item", 0),
		(neg|troop_has_item_equipped, "trp_player", ":item"),
		(troop_add_item, "trp_player", ":item"),
	(try_end),
	(agent_get_horse, ":horse", ":player"),
	(try_begin),
	  (gt, ":horse", 0),
	  (agent_get_item_id, ":horse", ":horse"),
	  (troop_get_inventory_slot, ":old_horse", "trp_player", ek_horse),
	  (neq, ":horse", ":old_horse"),
	  (try_begin),
		(gt, ":old_horse", 0),
		(troop_get_inventory_slot_modifier, ":horse_imod", "trp_player", ek_horse),
		(troop_add_item, "trp_player", ":old_horse", ":horse_imod"),
	  (try_end),
	  (troop_set_inventory_slot, "trp_player", ek_horse, ":horse"),
	(try_end),
   ]),

   #Returns in reg0
  ("freelancer_get_upgrade_xp",
   [
	(store_script_param_1, ":troop_no"),
	(assign, reg0, 0),
    (try_begin),
		(troop_get_upgrade_troop, ":upgrade_troop", ":troop_no", 0),
		(gt, ":upgrade_troop", 1), #make sure troop is valid and not player troop
		(call_script, "script_game_get_upgrade_xp", ":troop_no"),
    (try_end),
        #ranks for pay levels and to upgrade player equipment based on upgrade troop level times 1000
        # (try_begin),
           # (troop_get_upgrade_troop, ":upgrade_troop", "$player_cur_troop", 0),
           # (gt, ":upgrade_troop", 1), #make sure troop is valid and not player troop
           # (store_character_level, ":level", ":upgrade_troop"),
           # (store_pow, ":required_xp", ":level", 2), #square the level and
           # (val_mul, ":required_xp", 100),           #multiply by 100 to get xp
           # (ge, ":service_xp_cur", ":level"),
           # (jump_to_menu, "mnu_upgrade_path"),
        # (try_end),
		   ##THIS  BLOCK IS ALMOST DEFINITELY BE BETTER --said someone ?? on the freelancer team
		   # (store_character_level, ":cur_level", "$player_cur_troop"),
           # (val_sub, ":cur_level", 1),
           # (get_level_boundary, ":cur_level", ":cur_level"),
		   # (store_character_level, ":required_xp", ":upgrade_troop"),
		   # (val_sub, ":required_xp", 1),
		   # (get_level_boundary, ":required_xp", ":required_xp"),
		   # (val_sub, ":required_xp", ":cur_level"),
		   ##
   ]),

   #Returns troop ID in reg0
  ("cf_freelancer_get_reassign_troop",
   [
    (store_script_param_1, ":trp_array"),
	(store_script_param_2, ":division"),

    (troop_get_slot, ":max_slot", ":trp_array", 0),
	(assign, ":end", ":max_slot"),
	(try_for_range, ":i", 1, ":end"),
		(troop_slot_eq, ":trp_array", ":i", "$player_cur_troop"),
		(assign, ":end", ":i"),
	(try_end),
	(lt, ":end", ":max_slot"),

    (assign, ":cur_slot", ":max_slot"),

    (try_for_range, ":i", 1, ":end"), #troops before current troop--thus lower or same tier
        (troop_get_slot, ":troop", ":trp_array", ":i"),
		(gt, ":troop", 0), #double check
		(assign, ":is_valid", 1),
		(try_begin),
			(eq, ":division", grc_cavalry),
			(troop_is_guarantee_horse, ":troop"),
		(else_try),
			(eq, ":division", grc_archers),
			(neg|troop_is_guarantee_horse, ":troop"),
			(troop_is_guarantee_ranged, ":troop"),
		(else_try),
			(eq, ":division", grc_infantry),
			(neg|troop_is_guarantee_horse, ":troop"),
			(neg|troop_is_guarantee_ranged, ":troop"),
		(else_try),
			(assign, ":is_valid", 0),
		(try_end),
		(eq, ":is_valid", 1),
		(call_script, "script_cf_freelancer_player_can_upgrade", ":troop"),
		(troop_set_slot, ":trp_array", ":cur_slot", ":troop"),
		(val_add, ":cur_slot", 1),
    (try_end),
	(gt, ":cur_slot", ":max_slot"),

	(store_sub, ":num_choices", ":cur_slot", ":max_slot"),
	(try_begin),
		(gt, ":num_choices", 1),
		(store_attribute_level, ":int", "trp_player", ca_intelligence),
		(val_div, ":int", 8),
		(val_sub, ":num_choices", 1),
		(val_min, ":int", ":num_choices"),
		(val_add, ":max_slot", ":int"), #bring up the minimum troop based on intelligence/abilty to adapt
	(try_end),
    (store_random_in_range, ":i", ":max_slot", ":cur_slot"),
	(troop_get_slot, reg0, ":trp_array", ":i"),
   ]),

  ("freelancer_list_faction_troops",
   [
    (store_script_param, ":faction", 1),
	(store_script_param, ":destination_array", 2),
	(store_script_param, ":helper_array", 3),
	(try_for_range, reg0, 1, 101),
		(troop_set_slot, ":destination_array", reg0, 0),
		(troop_set_slot, ":helper_array", reg0, 0),
	(try_end),
	(faction_get_slot, reg0, ":faction", slot_faction_tier_1_troop),
	(troop_set_slot, ":destination_array", 1, reg0),
	(troop_set_slot, ":helper_array", 0, reg0),
	(assign, ":list_slot", 2),
	(assign, ":check_slot", 1),
	(assign, ":end", 101),
	(try_for_range, ":unused", 0, ":end"),
		(troop_get_slot, ":troop", ":helper_array", 0),
		(gt, ":troop", 0),
		(try_for_range, ":i", 0, 2),
			(troop_get_upgrade_troop, reg0, ":troop", ":i"),
			(gt, reg0, 0),
			(troop_set_slot, ":destination_array", ":list_slot", reg0),
			(troop_set_slot, ":helper_array", ":check_slot", reg0),
			(val_add, ":list_slot", 1),
			(val_add, ":check_slot", 1),
		(try_end),
		(try_for_range, ":i", 1, ":check_slot"),
		    (troop_get_slot, reg0, ":helper_array", ":i"),
			(store_sub, ":i_minus_one", ":i", 1),
			(troop_set_slot, ":helper_array", ":i_minus_one", reg0),
		(try_end),
		(troop_set_slot, ":helper_array", ":check_slot", 0),
		(val_sub, ":check_slot", 1),
	(else_try),
		(assign, ":end", 0),
	(try_end),
	(troop_set_slot, ":destination_array", 0, ":list_slot"),
   ]),

   #s0 outputs reason for failure
  ("cf_freelancer_player_can_upgrade",
   [
	(store_script_param_1, ":source_troop"),

	(str_clear, s0),
	(troop_get_inventory_capacity, ":troop_cap", ":source_troop"),

	(assign, ":type_available", 0),
	(assign, ":type_count", 0),
	(assign, ":end", itp_type_arrows),
	(try_for_range, ":type", itp_type_one_handed_wpn, ":end"),
		#Count Items from Source Troop
		(assign, ":end2", ":troop_cap"),
		(try_for_range, ":inv_slot", 0, ":end2"),
		    (troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			(gt, ":item", 0),
			(item_get_type, ":item_type", ":item"),
			(eq, ":item_type", ":type"),
			(val_add, ":type_count", 1),
			(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
			(eq, reg0, 1),
			(assign, ":type_available", 1),
			(assign, ":end2", 0), #break
		(try_end),
		(eq, ":type_available", 1),
		(assign, ":end", itp_type_one_handed_wpn), #break
	(try_end), #Melee loop
	(try_begin),
		(eq, ":type_available", 0),
		(gt, ":type_count", 0), #only care if there were items possible to equip
		(str_store_string, s0, "@--too weak for required melee weapons"),
	(try_end),
	(str_is_empty, s0),

	(assign, ":type_available", 0),
	(assign, ":type_count", 0),
	(assign, ":end2", ":troop_cap"),
	(try_for_range, ":inv_slot", 0, ":end2"),
		(troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
		(gt, ":item", 0),
		(item_get_type, ":item_type", ":item"),
		(eq, ":item_type", itp_type_body_armor),
		(val_add, ":type_count", 1),
		(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
		(eq, reg0, 1),
		(assign, ":type_available", 1),
		(assign, ":end2", 0), #break
	(try_end),
	(try_begin),
		(eq, ":type_available", 0),
		(gt, ":type_count", 0), #only care if there were items possible to equip
		(str_store_string, s0, "@--too weak for required armor"),
	(try_end),
	(str_is_empty, s0),

	(try_begin),
		(troop_is_guarantee_ranged, ":source_troop"),
		(assign, ":type_available", 0),
		(assign, ":type_count", 0),
		(assign, ":end", itp_type_goods),
		(try_for_range, ":type", itp_type_bow, ":end"),
			#Count Items from Source Troop
			(assign, ":end2", ":troop_cap"),
			(try_for_range, ":inv_slot", 0, ":end2"),
				(troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
				(gt, ":item", 0),
				(item_get_type, ":item_type", ":item"),
				(eq, ":item_type", ":type"),
				(val_add, ":type_count", 1),
				(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
				(eq, reg0, 1),
				(assign, ":type_available", 1),
				(assign, ":end2", 0), #break
			(try_end),
			(eq, ":type_available", 1),
			(assign, ":end", itp_type_bow), #break
		(try_end), #Ranged loop
		(eq, ":type_available", 0),
		(gt, ":type_count", 0), #only care if there were items possible to equip
		(str_store_string, s0, "@--lacking required ranged skill or strength"),
	(try_end),
	(str_is_empty, s0),

	(try_begin),
		(troop_is_guarantee_horse, ":source_troop"),
		(assign, ":type_available", 0),
		(assign, ":type_count", 0),
		(assign, ":end2", ":troop_cap"),
		(try_for_range, ":inv_slot", 0, ":end2"),
			(troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			(gt, ":item", 0),
			(item_get_type, ":item_type", ":item"),
			(eq, ":item_type", itp_type_horse),
			(val_add, ":type_count", 1),
			(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
			(eq, reg0, 1),
			(assign, ":type_available", 1),
			(assign, ":end2", 0), #break
		(try_end),
		(eq, ":type_available", 0),
		(gt, ":type_count", 0), #only care if there were items possible to equip
		(str_store_string, s0, "@--horsemanship needs improving"),
	(try_end),
	(str_is_empty, s0),

	# (try_begin),
		# (troop_has_flag, ":source_troop", tf_guarantee_shield),##WSE
		# (assign, ":type_available", 0),
		# (assign, ":type_count", 0),
		# (assign, ":end2", ":troop_cap"),
		# (try_for_range, ":inv_slot", 0, ":end2"),
			# (troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			# (gt, ":item", 0),
			# (item_get_type, ":item_type", ":item"),
			# (eq, ":item_type", itp_type_shield),
			# (val_add, ":type_count", 1),
			# (call_script, freelancer_can_use_item, "trp_player", ":item", 0),
			# (eq, reg0, 1),
			# (assign, ":type_available", 1),
			# (assign, ":end2", 0), #break
		# (try_end),
		# (eq, ":type_available", 0),
		# (gt, ":type_count", 0), #only care if there were items possible to equip
		# (str_store_string, s0, "@--lacking required ranged skill or strength"),
	# (try_end),
	# (str_is_empty, s0),
   ]),

  ("freelancer_equip_troop",
   [
    (store_script_param_1, ":source_troop"),

	(str_clear, s2),
	(set_show_messages, 0),

	(assign, ":recording_slot", slot_freelancer_equip_start),
	(troop_get_inventory_capacity, ":troop_cap", ":source_troop"),
	(assign, ":melee_given", 0),
	(assign, ":needs_ammo", 0),
	(assign, ":open_weapon_slot", 0),
	(try_for_range, ":type", itp_type_horse, itp_type_pistol),
	    (neq, ":type", itp_type_goods),
		(neq, ":type", itp_type_arrows),
		(neq, ":type", itp_type_bolts),

		#Assign Prob. of Getting Type
		(assign, ":continue", 0),
		(try_begin),
			(troop_is_guarantee_horse, ":source_troop"),
		    (eq, ":type", itp_type_horse),
			(assign, ":continue", 1),
		(else_try),
		    (troop_is_guarantee_ranged, ":source_troop"),
		    (this_or_next|eq, ":type", itp_type_bow),
			(this_or_next|eq, ":type", itp_type_crossbow),
			(eq, ":type", itp_type_thrown),
			(assign, ":continue", 1),
		(else_try),
		    (this_or_next|eq, ":type", itp_type_shield), #Shields and all armor pieces are guaranteed
		    (ge, ":type", itp_type_head_armor),
			(assign, ":continue", 1),
		(else_try),
		    (neq, ":type", itp_type_horse),
		    (lt, ":open_weapon_slot", 4),
			(store_random_in_range, ":continue", 0, 3), # 1 chance in three of being 1
		(try_end),
		(eq, ":continue", 1),

		#Clear Temp Array
		(try_for_range, ":inv_slot", 0, 20),
			(troop_set_slot, "trp_temp_array_a", ":inv_slot", 0),
		(try_end),

		#Collect Items from Source Troop
		(assign, ":type_count", 0),
		(try_for_range, ":inv_slot", 0, ":troop_cap"),
		    (troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			(gt, ":item", 0),
			(item_get_type, ":item_type", ":item"),
			(eq, ":item_type", ":type"),
			(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
			(eq, reg0, 1),
			(troop_set_slot, "trp_temp_array_a", ":type_count", ":item"),
			(val_add, ":type_count", 1),
		(try_end),
		(gt, ":type_count", 0),

		#Pick Random Item of Type from Troop
		(try_begin),
		    (eq, ":type_count", 1),
			(assign, ":index", 0),
		(else_try),
			(store_random_in_range, ":index", 0, ":type_count"),
		(try_end),
		(troop_get_slot, ":item", "trp_temp_array_a", ":index"),
		(gt, ":item", 0),
		(str_store_item_name, s3, ":item"),
		(str_store_string, s2, "@{s3}, {s2}"),

		#Select correct EK slot to force equip
		(try_begin),
		    (eq, ":type", itp_type_horse),
			(assign, ":ek_slot", ek_horse),
		(else_try),
		    (is_between, ":type", itp_type_head_armor, itp_type_pistol),
			(store_sub, ":shift", ":type", itp_type_head_armor),
			(store_add, ":ek_slot", ek_head, ":shift"),
		(else_try),
			(store_add, ":ek_slot", ek_item_0, ":open_weapon_slot"),
		(try_end),

		#Check for item already there, move it if present
		(try_begin),
		    (troop_get_inventory_slot, ":old_item", "trp_player", ":ek_slot"),
			(gt, ":old_item", 0),
			(troop_get_inventory_slot_modifier, ":old_item_imod", "trp_player", ":ek_slot"),
			(troop_add_item, "trp_player", ":old_item", ":old_item_imod"),
		(try_end),

		#Add Item
		(troop_set_inventory_slot, "trp_player", ":ek_slot", ":item"),
		(party_set_slot, "p_freelancer_party_backup", ":recording_slot", ":item"),
		(val_add, ":recording_slot", 1),
		(try_begin),
		    (is_between, ":type", itp_type_one_handed_wpn, itp_type_head_armor), #Uses one of the 4 weapon slots
		    (val_add, ":open_weapon_slot", 1),
			(try_begin),
				(is_between, ":type", itp_type_one_handed_wpn, itp_type_arrows),
				(assign, ":melee_given", 1),
            (else_try),
				(eq, ":type", itp_type_bow),
				(assign, ":needs_ammo", itp_type_arrows),
			(else_try),
				(eq, ":type", itp_type_crossbow),
				(assign, ":needs_ammo", itp_type_bolts),
			(try_end),
		(try_end),
	(try_end), #Item Types Loop

    #add ammo for any equipped bow
    (try_begin),
	    (neq, ":needs_ammo", 0),
		#Check for item already in the last slot, move it if present
		(try_begin),
		    (troop_get_inventory_slot, ":old_item", "trp_player", ek_item_3),
			(gt, ":old_item", 0),
			(troop_get_inventory_slot_modifier, ":old_item_imod", "trp_player", ek_item_3),
			(troop_add_item, "trp_player", ":old_item", ":old_item_imod"),
		(try_end),

		(assign, ":end", ":troop_cap"),
		(try_for_range, ":inv_slot", 0, ":end"),
		    (troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			(gt, ":item", 0),
			(item_get_type, ":type", ":item"),
			(eq, ":type", ":needs_ammo"),
			(troop_set_inventory_slot, "trp_player", ek_item_3, ":item"),
			(party_set_slot, "p_freelancer_party_backup", ":recording_slot", ":item"),
		    (val_add, ":recording_slot", 1),
			(assign, ":open_weapon_slot", 4),
			(str_store_item_name, s3, ":item"),
		    (str_store_string, s2, "@{s3}, {s2}"),
			(assign, ":end", 0),
		(try_end),
	(try_end),

	#double check melee was given
	(try_begin),
	    (eq, ":melee_given", 0),
		(assign, ":end", ":troop_cap"),
		(try_for_range, ":inv_slot", 0, ":end"),
		    (troop_get_inventory_slot, ":item", ":source_troop", ":inv_slot"),
			(gt, ":item", 0),
			(item_get_type, ":type", ":item"),
			(is_between, ":type", itp_type_one_handed_wpn, itp_type_arrows),
			(call_script, freelancer_can_use_item, "trp_player", ":item", 0),
			(eq, reg0, 1),
			(try_begin),
			    (gt, ":open_weapon_slot", 3),
			    (assign, ":open_weapon_slot", 2),
			(try_end),

			#Check for item already there
			(try_begin),
				(troop_get_inventory_slot, ":old_item", "trp_player", ":open_weapon_slot"),
				(gt, ":old_item", 0),
				(troop_get_inventory_slot_modifier, ":old_item_imod", "trp_player", ":open_weapon_slot"),
				(troop_add_item, "trp_player", ":old_item", ":old_item_imod"),
			(try_end),

			(troop_set_inventory_slot, "trp_player", ":open_weapon_slot", ":item"),
			(party_set_slot, "p_freelancer_party_backup", ":recording_slot", ":item"),
		    (val_add, ":recording_slot", 1),
			(str_store_item_name, s3, ":item"),
		    (str_store_string, s2, "@{s3}, {s2}"),
		    (assign, ":end", 0),
		(try_end),
	(try_end),

    (set_show_messages, 1),
	(try_begin),
		(neg|str_is_empty, s2),
		(val_sub, ":recording_slot", slot_freelancer_equip_start),
		(party_set_slot, "p_freelancer_party_backup", slot_freelancer_equip_start - 1, ":recording_slot"),	#Record Number of Items Added

		(str_store_troop_name, s1, ":source_troop"),
		(display_message, "@The equipment of a {s1}: {s2}is assigned to you."),
	(try_end),
   ]),

  ("freelancer_unequip_troop",
   [
    (store_script_param_1, ":source_troop"),

	(str_clear, s2),
	(set_show_messages, 0),

	(party_get_slot, ":num_items", "p_freelancer_party_backup", slot_freelancer_equip_start - 1), #Num of items previously given

    (troop_get_inventory_capacity, ":cap", "trp_player"),
	(try_for_range, ":i", 0, ":num_items"),
	    (store_add, ":slot", slot_freelancer_equip_start, ":i"),
	    (party_get_slot, ":given_item", "p_freelancer_party_backup", ":slot"),
		(gt, ":given_item", 0),

		(assign, ":end", ":cap"),
		(try_for_range, ":inv_slot", 0, ":end"),
			(troop_get_inventory_slot, ":item", "trp_player", ":inv_slot"),
			(eq, ":item", ":given_item"),
			(troop_get_inventory_slot_modifier, ":imod", "trp_player", ":inv_slot"),
			(eq, ":imod", 0), #Native troop items never have modifiers

			(troop_set_inventory_slot, "trp_player", ":inv_slot", -1),
			(str_store_item_name, s3, ":item"),
			(str_store_string, s2, "@{s3}, {s2}"),

			(assign, ":end", 0), #Break
		(try_end), #Player Inventory Loop
	(try_end), #Item Given Slot Loop

	(set_show_messages, 1),
	(try_begin),
		(neg|str_is_empty, s2),
		(party_set_slot, "p_freelancer_party_backup", slot_freelancer_equip_start - 1, 0),	#Reset Number of Items Added
		(str_store_troop_name, s1, ":source_troop"),
		(display_message, "@The equipment of a {s1}: {s2}is taken from you."),
	(try_end),
	(troop_equip_items, "trp_player"),
   ]),
#+freelancer end

]

from util_wrappers import *
from util_scripts import *

scripts_directives = [
	#[SD_OP_BLOCK_INSERT, "agent_reassign_team", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_BEFORE,(party_stack_get_troop_id, ":leader_troop_id", ":party_no", 0),0,not_in_party], Just going to hope we don't really need this
    [SD_OP_BLOCK_INSERT, "game_start", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_AFTER,(assign, "$g_player_luck", 200),0,
	[
		(assign, "$freelancer_state", 0),
    ]],
	[SD_OP_BLOCK_INSERT, "encounter_init_variables", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_BEFORE, (gt, "$g_starting_strength_friends", 0),0,
	[
		#(try_begin), #in the script
      	    (eq, "$freelancer_state", 1),
			(store_character_level, "$g_strength_contribution_of_player", "$player_cur_troop"),
			(val_div, "$g_strength_contribution_of_player", 3),
			(val_max, "$g_strength_contribution_of_player", 3), #contribution(scale 0-100) = level/3, min 3 (so about 3-15)
			#(store_character_level, ":freelancer_player_contribution", "$player_cur_troop"),
			#(val_mul, ":freelancer_player_contribution", 6),
			#(val_div, ":freelancer_player_contribution", 5), #level * 1.2 (for a bit of a scaling bump)
			#(val_max, ":freelancer_player_contribution", 10), #and to give a base line
			#(assign, "$g_strength_contribution_of_player", ":freelancer_player_contribution"),
        (else_try),
	]],
    [SD_OP_BLOCK_INSERT, "enter_court", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_AFTER,(party_stack_get_troop_id, ":stack_troop","p_temp_party",":i_stack"),0,
	[
		(gt, ":stack_troop", 0), #fixes duplicate players in towns
    ]],
	[SD_OP_BLOCK_INSERT, "game_event_simulate_battle", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_AFTER,(troop_is_hero, ":cur_troop_id"),0,
	[
		(gt, ":cur_troop_id", 0), #fixes problems with player getting added as prisoner
    ]],
	[SD_OP_BLOCK_INSERT, "abort_quest", D_SEARCH_FROM_BOTTOM | D_SEARCH_LINENUMBER | D_INSERT_AFTER,0,0, ##ADD TO END
	[
		(try_begin),
		    (is_between, ":quest_no", freelancer_quests_begin, freelancer_quests_end),
			(str_store_troop_name, s13, "$enlisted_lord"),
			(dialog_box, "@You have deserted from the party of {s13}!", "@Notice!"),
			(call_script, "script_freelancer_event_player_deserts"),
		(try_end),
    ]],
	[SD_OP_BLOCK_REPLACE, "change_troop_faction", D_SEARCH_FROM_BOTTOM | D_SEARCH_SCRIPTLINE,(call_script, "script_abort_quest", ":quest", 0),0,
	[
		(try_begin), #prevents cancelling freelancer quests on defection/indictment
			(eq, ":quest", "qst_freelancer_enlisted"), #only do necessary Freelancer stuff once
			(str_store_troop_name, s5, "$player_cur_troop"),
			(str_store_troop_name_link, s13, "$enlisted_lord"),
			(str_store_faction_name_link, s14, ":faction_no"),
			(str_store_string, s1, "@Enlisted as a {s5} in the party of {s13} of {s14}."),
			(add_troop_note_from_sreg, "trp_player", 3, s1, 0),
			#set faction relations to allow player to join battles
			(try_begin),
				(store_relation, ":player_relation", ":faction_no", "fac_player_supporters_faction"),
				(lt, ":player_relation", 5),
				(call_script, "script_set_player_relation_with_faction", ":faction_no", 5),
			(try_end),
			(try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
			   (neq, ":faction_no", ":cur_faction"),
			   (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
			   (store_relation, ":player_relation", ":cur_faction", "fac_player_supporters_faction"),
			   (ge, ":player_relation", 0),
			   (call_script, "script_set_player_relation_with_faction", ":cur_faction", -5),
			(try_end),
		(else_try),
			(neg|is_between, ":quest", freelancer_quests_begin, freelancer_quests_end),
			(call_script, "script_abort_quest", ":quest", 0), ##Natively in the script
		(try_end),
    ]],
	##FLORIS ONLY - Trade with Merchant Caravans
	#[SD_OP_BLOCK_INSERT, "party_give_xp_and_gold", D_SEARCH_FROM_TOP | D_SEARCH_SCRIPTLINE | D_INSERT_BEFORE, (party_slot_eq, ":enemy_party", slot_party_type, spt_kingdom_caravan),0,not_in_party],
	##FLORIS ONLY END
]

def modmerge_scripts(orig_scripts):
	# process script directives first
	process_script_directives(orig_scripts, scripts_directives)
	# add remaining scripts
	add_scripts(orig_scripts, scripts, True)

# Used by modmerger framework version >= 200 to merge stuff
# This function will be looked for and called by modmerger if this mod is active
# Do not rename the function, though you can insert your own merging calls where indicated
def modmerge(var_set):
    try:
        var_name_1 = "scripts"
        orig_scripts = var_set[var_name_1]

		# START do your own stuff to do merging

        modmerge_scripts(orig_scripts)

		# END do your own stuff

    except KeyError:
        errstring = "Variable set does not contain expected variable: \"%s\"." % var_name_1
        raise ValueError(errstring)


from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from keymgmt.models import SSHAccount

class SSHAccountForm(forms.ModelForm):
    def clean_obj_id(self):
        return self.cleaned_data['obj_id']

    class Meta:
        model = SSHAccount
        fields = ['name', 'obj_id', 'obj_name']
        error_messages = {
            NON_FIELD_ERRORS: {
                'unique_together': 'Account already exists.'
            }
        }