"""
@file
@brief Helpers to convert docstring to various format.
"""
import re
import textwrap
import os
from io import StringIO
from docutils import core, languages
from docutils.io import StringInput, StringOutput
from .utils_sphinx_doc import migrating_doxygen_doc
from .helpgen_exceptions import HelpGenConvertError
from ..texthelper.texts_language import TITLES
from ..loghelper.flog import noLOG

def default_sphinx_options(fLOG=noLOG, **options):
    """
    Defines or overrides default options for :epkg:`Sphinx`, listed below.

    .. runpython::

        from pyquickhelper.helpgen.rst_converters import default_sphinx_options
        options = default_sphinx_options()
        for k, v in sorted(options.items()):
            print("{0} = {1}".format(k, v))

    :epkg:`latex` is not available on :epkg:`Windows`.
    """
    # delayed import to speed up time
    from .conf_path_tools import find_graphviz_dot, find_dvipng_path

    res = {  # 'output_encoding': options.get('output_encoding', 'unicode'),
        # 'doctitle_xform': options.get('doctitle_xform', True),
        # 'initial_header_level': options.get('initial_header_level', 2),
        # 'input_encoding': options.get('input_encoding', 'utf-8-sig'),
        'blog_background': options.get('blog_background', False),
        'sharepost': options.get('sharepost', None),
        'todoext_link_only': options.get('todoext_link_only', False),
        'mathdef_link_only': options.get('mathdef_link_only', True),
        'blocref_link_only': options.get('blocref_link_only', False),
        'faqref_link_only': options.get('faqref_link_only', False),
        'nbref_link_only': options.get('nbref_link_only', False),
        'todo_link_only': options.get('todo_link_only', False),
        'language': options.get('language', 'en'),
        # 'outdir': options.get('outdir', '.'),
        # 'imagedir': options.get('imagedir', '.'),
        # 'confdir': options.get('confdir', '.'),
        # 'doctreedir': options.get('doctreedir', '.'),
        'math_number_all': options.get('math_number_all', False),
        # graphviz
        'graphviz_output_format': options.get('graphviz_output_format', 'png'),
        'graphviz_dot': options.get('graphviz_dot', find_graphviz_dot(exc=False)),
        # latex
        'imgmath_image_format': options.get('imgmath_image_format', 'png'),
        # containers
        'out_blogpostlist': [],
        'out_runpythonlist': [],
        # 'warning_stream': StringIO(),
    }

    if res['imgmath_image_format'] == 'png':
        try:
            imgmath_latex, imgmath_dvipng, imgmath_dvisvgm = find_dvipng_path(
                exc=False)
            has_latex = True
        except FileNotFoundError:
            # miktex is not available,
            has_latex = False

        if has_latex:
            res['imgmath_latex'] = imgmath_latex
            res['imgmath_dvipng'] = imgmath_dvipng
            res['imgmath_dvisvgm'] = imgmath_dvisvgm

    for k, v in options.items():
        if k not in res:
            res[k] = v

    return res

def rst2html(s, fLOG=noLOG, writer="html", keep_warnings=False,
             directives=None, language="en",
             layout='docutils', document_name="<<string>>",
             external_docnames=None, filter_nodes=None,
             new_extensions=None, update_builder=None,
             ret_doctree=False, destination=None, destination_path=None,
             **options):
    """
    Converts a string from :epkg:`RST`
    into :epkg:`HTML` format or transformed :epkg:`RST`.

    @param      s                   string to convert
    @param      fLOG                logging function (warnings will be logged)
    @param      writer              ``'html'`` for :epkg:`HTML` format,
                                    ``'rst'`` for :epkg:`RST` format,
                                    ``'md'`` for :epkg:`MD` format,
                                    ``'elatex'`` for :epkg:`latex` format,
                                    ``'doctree'`` to get the doctree, *writer* can also be a tuple
                                    for custom formats and must be like ``('buider_name', builder_class)``.
    @param      keep_warnings       keep_warnings in the final HTML
    @param      directives          new directives to add (see below)
    @param      language            language
    @param      layout              ``'docutils'``, ``'sphinx'``, ``'sphinx_body'``, see below.
    @param      document_name       document name, not really important since the input is a string
    @param      external_docnames   if the string to parse makes references to other documents,
                                    if one is missing, an exception is raised.
    @param      filter_nodes        transforms the doctree before writing the results (layout must be 'sphinx'),
                                    the function takes a doctree as a single parameter
    @param      new_extensions      additional extension to setup
    @param      update_builder      update the builder after it is instantiated
    @param      ret_doctree         returns the doctree
    @param      destination         set a destination (requires for some extension)
    @param      destination_path    set a destination path (requires for some extension)
    @param      options             :epkg:`Sphinx` options see
                                    `Render math as images <https://www.sphinx-doc.org/en/master/ext/math.html#module-sphinx.ext.imgmath>`_,
                                    a subset of options is used, see @see fn default_sphinx_options.
                                    By default, the theme (option *html_theme*) will ``'basic'``.
    @return                         HTML format

    *directives* is None or a list of 2 or 5-uple:

    * a directive name (mandatory)
    * a directive class: see `Sphinx Directive
      <https://www.sphinx-doc.org/en/master/development/tutorials/helloworld.html>`_,
      see also @see cl RunPythonDirective as an example (mandatory)
    * a docutils node: see @see cl runpython_node as an example
    * two functions: see @see fn visit_runpython_node, @see fn depart_runpython_node as an example

    The parameter *layout* specify the kind of HTML you need.

    * ``'docutils'``: very simple :epkg:`HTML`, style is not included, recursive
      directives are not processed (recursive means they modify the doctree).
      The produced :epkg:`HTML` only includes the body (no :epkg:`HTML` header).
    * ``'sphinx'``: in memory :epkg:`sphinx`, the produced :epkg:`HTML` includes the header, it is also recursive
      as directives can modify the doctree.
    * ``'sphinx_body'``: same as ``'sphinx'`` but only the body is returned.

    If the writer is a tuple, it must be a 2-uple ``(builder_name, builder_class)``.
    However, the builder class must contain an attribute ``_writer_class`` with
    the associated writer. The builcer class must also implement a method
    ``iter_pages`` which enumerates all written pages:
    ``def iter_pages(self) -> Dict[str,str]`` where the key is the document name
    and the value is its content.

    .. exref::
        :title: How to test a Sphinx directive?

        The following code defines a simple directive
        definedbased on an existing one.
        It also defined what to do if a new node
        is inserted in the documentation.

        ::

            from docutils import nodes
            from pyquickhelper.helpgen import rst2html

            class runpythonthis_node(nodes.Structural, nodes.Element):
                pass

            class RunPythonThisDirective (RunPythonDirective):
                runpython_class = runpythonthis_node

            def visit_node(self, node):
                self.body.append("
visit_node
")
            def depart_node(self, node):
                self.body.append("
depart_node
")

            content = '''
                        test a directive
                        ================

                        .. runpythonthis::

                            print("this code shoud appear" + "___")
                        '''.replace("                    ", "")
                        # to remove spaces at the beginning of the line

            tives = [ ("runpythonthis", RunPythonThisDirective,
                       runpythonthis_node, visit_node, depart_node) ]

            html = rst2html(content, writer="html", keep_warnings=True,
                            directives=tives)

        Unfortunately, this functionality is only tested on :epkg:`Python` 3.
        It might not work on :epkg:`Python` 2.7.
        The function produces files if the document contains latex
        converted into image.

    .. faqref::
       :title: How to get more about latex errors?
       :index: latex

        :epkg:`Sphinx` is not easy to use when it comes to debug latex expressions.
        I did not find an easy way to read the error returned by latex about
        a missing bracket or an unknown command. I finally added a short piece
        of code in ``sphinx.ext.imgmath.py`` just after the call to
        the executable indicated by *imgmath_latex*

        ::

            if b'...' in stdout or b'LaTeX Error' in stdout:
                print(self.builder.config.imgmath_latex_preamble)
                print(p.returncode)
                print("################")
                print(latex)
                print("..........")
                print(stdout.decode("ascii").replace("\\r", ""))
                print("-----")
                print(stderr)

        It displays the output if an error happened.

    .. faqref::
        :title: How to hide command line window while compiling latex?
        :lid: command line window

        :epkg:`Sphinx` calls :epkg:`latex` through command line.
        On :epkg:`Windows`, a command line window
        can annoyingly show up anytime a formula is compiled.
        The following can be added to hide it:

        ::

            startupinfo = STARTUPINFO()
            startupinfo.dwFlags |= STARTF_USESHOWWINDOW

        And ``, startupinfo=startupinfo`` must be added to lines ``p = Popen(...``.

    By default, the function now interprets :epkg:`Sphinx`
    directives and not only *docutils* ones.
    Parameter *directives* adds a directive
    before parsing the :epkg:`RST`.
    The function is more consistent.
    Format ``rst`` is available as well as
    custom builders.
    New nodes are optional in *directives*.
    Markdown format was added.
    """
    # delayed import to speed up time
    def _get_MockSphinxApp():
        from .sphinxm_mock_app import MockSphinxApp
        return MockSphinxApp
    MockSphinxApp = _get_MockSphinxApp()

    if 'html_theme' not in options:
        options['html_theme'] = 'basic'
    defopt = default_sphinx_options(**options)
    if "master_doc" not in defopt:
        defopt["master_doc"] = document_name
    if writer in ('latex', 'elatex') and 'latex_documents' not in defopt:
        latex_documents = [(document_name, ) * 5]
        defopt['latex_documents'] = latex_documents

    if writer in ["custom", "sphinx", "HTMLWriterWithCustomDirectives", "html"]:
        mockapp, writer, title_names = MockSphinxApp.create(
            "sphinx", directives, confoverrides=defopt,
            new_extensions=new_extensions,
            fLOG=fLOG, destination_path=destination_path)
        writer_name = "HTMLWriterWithCustomDirectives"
    elif writer in ("rst", "md", "latex", "elatex", 'text', 'doctree'):
        writer_name = writer
        mockapp, writer, title_names = MockSphinxApp.create(
            writer, directives, confoverrides=defopt,
            new_extensions=new_extensions,
            fLOG=fLOG, destination_path=destination_path)
    elif isinstance(writer, tuple):
        # We extect something like ("builder_name", builder_class)
        writer_name = writer
        mockapp, writer, title_names = MockSphinxApp.create(
            writer, directives, confoverrides=defopt,
            new_extensions=new_extensions,
            fLOG=fLOG, destination_path=destination_path)
    else:
        raise ValueError(
            f"Unexpected writer '{writer}', should be 'rst' or 'html' or 'md' or 'elatex' or 'text'.")

    if writer is None and directives is not None and len(directives) > 0:
        raise NotImplementedError(
            "The writer must not be null if custom directives will be added, check the documentation of the fucntion.")

    # delayed import to speed up time
    from sphinx.environment import default_settings
    settings_overrides = default_settings.copy()
    settings_overrides["warning_stream"] = StringIO()
    settings_overrides["master_doc"] = document_name
    settings_overrides["source"] = document_name
    settings_overrides["contentsname"] = document_name
    settings_overrides.update({k: v[0]
                               for k, v in mockapp.new_options.items()})

    # next
    settings_overrides.update(defopt)
    config = mockapp.config
    config.blog_background = True
    config.blog_background_page = False
    config.sharepost = None

    if hasattr(writer, "add_configuration_options"):
        writer.add_configuration_options(mockapp.new_options)
    for k in {'outdir', 'imagedir', 'confdir', 'doctreedir'}:
        setattr(writer.builder, k, settings_overrides.get(k, ''))
    if destination_path is not None:
        writer.builder.outdir = destination_path
    if update_builder:
        update_builder(writer.builder)

    env = mockapp.env
    if env is None:
        raise ValueError("No environment was built.")

    env.temp_data["docname"] = document_name
    env.temp_data["source"] = document_name
    if mockapp.builder.env is None:
        mockapp.builder.env = env
    else:
        mockapp.builder.env.temp_data["docname"] = document_name
        mockapp.builder.env.temp_data["source"] = document_name
    settings_overrides["env"] = env

    lang = languages.get_language(language)
    for name in title_names:
        if name not in lang.labels:
            lang.labels[name] = TITLES[language][name]

    for k, v in sorted(settings_overrides.items()):
        fLOG(f"[rst2html] {k}={v}{' --- added' if hasattr(config, k) else ''}")
    for k, v in sorted(settings_overrides.items()):
        if hasattr(writer.builder.config, k) and writer.builder.config[k] != v:
            writer.builder.config[k] = v

    _, pub = core.publish_programmatically(
        source=s, source_path=None, destination_path=destination_path, writer=writer,
        writer_name=writer_name, settings_overrides=settings_overrides,
        source_class=StringInput, destination_class=StringOutput,
        destination=destination, reader=None, reader_name='standalone',
        parser=None, parser_name='restructuredtext', settings=None,
        settings_spec=None, config_section=None, enable_exit_status=False)

    doctree = pub.document

    if filter_nodes is not None:
        if layout == "docutils" and writer != "doctree":
            raise ValueError(
                "filter_nodes is not None, layout must not be 'docutils'")
        filter_nodes(doctree)

    mockapp.finalize(doctree, external_docnames=external_docnames)
    parts = pub.writer.parts

    if not keep_warnings:
        if isinstance(parts["whole"], list):
            # Not html.
            exp = "".join(parts["whole"])
        else:
            exp = re.sub(
                '(
(.|\\n)*?
)', "", parts["whole"])
    else:
        if isinstance(parts["whole"], list):
            exp = "".join(parts["whole"])
        else:
            exp = parts["whole"]

    if ret_doctree:
        return doctree

    if layout == "docutils":
        return exp
    else:
        page = None
        pages = []
        main = (f"/{document_name}.m.html",
                f"/{document_name}.m.{writer_name}",
                document_name)
        if not hasattr(writer.builder, "iter_pages"):
            raise AttributeError(
                f"Class '{writer.builder}' must have a method 'iter_pages' which returns a dictionary.")
        contents = []
        for k, v in writer.builder.iter_pages():
            pages.append(k)
            contents.append(v)
            if k in main:
                page = v
                break
        if page is None and len(contents) == 1:
            page = contents[0]
        if page is None:
            raise ValueError(
                f"No page contents was produced, only '{pages}'.")
        if layout == "sphinx":
            if isinstance(page, str):
                return page
            else:
                return "\n".join(page)
        elif layout == "sphinx_body":
            lines = page.replace('', '\n').split("\n")
            keep = []
            begin = False
            for line in lines:
                s = line.strip(" \n\r")
                if s == "":
                    begin = False
                if begin:
                    keep.append(line)
                if s == "":
                    begin = True
            res = "\n".join(keep)
            return res
        else:
            raise ValueError(
                f"Unexpected value for layout '{layout}'")

def correct_indentation(text):
    """
    Tries to improve the indentation before running :epkg:`docutils`.

    @param      text        text to correct
    @return                 corrected text
    """
    title = {}
    rows = text.split("\n")
    for row in rows:
        row = row.replace("\t", "    ")
        cr = row.lstrip()
        ind = len(row) - len(cr)

        tit = cr.strip("\r\n\t ")
        if len(tit) > 0 and tit[0] in "-+=*^" and tit == tit[0] * len(tit):
            title[ind] = title.get(ind, 0) + 1

    if len(title) > 0:
        mint = min(title.keys())
    else:
        mint = 0
    if mint > 0:
        newrows = []
        for row in rows:
            i = 0
            while i < len(row) and row[i] == ' ':
                i += 1

            rem = min(i, mint)
            if rem > 0:
                newrows.append(row[rem:])
            else:
                newrows.append(row)

        return "\n".join(newrows)
    else:
        return text

def docstring2html(function_or_string, format="html", fLOG=noLOG, writer="html",
                   keep_warnings=False, directives=None, language="en",
                   layout='docutils', document_name="<<string>>",
                   filter_nodes=None, **options):
    """
    Converts a docstring into a :epkg:`HTML` format.

    @param      function_or_string      function, class, method or doctring
    @param      format                  output format (``'html'`` or '``rawhtml``')
    @param      fLOG                    logging function
    @param      writer                  ``'html'`` for :epkg:`HTML` format,
                                        ``'rst'`` for :epkg:`RST` format,
                                        ``'md'`` for :epkg:`MD` format
    @param      keep_warnings           keep_warnings in the final :epkg:`HTML`
    @param      directives              new directives to add (see below)
    @param      language                language
    @param      layout                  ``'docutils'``, ``'sphinx'``, ``'sphinx_body'``, see below.
    @param      document_name           document_name for this string
    @param      filter_nodes            transform the doctree before writing the results
                                        (layout must be 'sphinx')
    @param      options                 Sphinx options see `Render math as images
                                        <https://www.sphinx-doc.org/en/master/ext/math.html#module-sphinx.ext.imgmath>`_,
                                        a subset of options is used, see @see fn default_sphinx_options.
                                        By default, the theme (option *html_theme*) will ``'basic'``.
    @return                             (str) :epkg:`HTML` format or (IPython.core.display.HTML)

    .. exref::
        :title: Produce HTML documentation for a function or class

        The following code can display the dosstring in :epkg:`HTML` format
        to display it in a :epkg:`notebook`.

        ::

            from pyquickhelper.helpgen import docstring2html
            import sklearn.linear_model
            docstring2html(sklearn.linear_model.LogisticRegression)

    The output format is defined by:

    * ``'html'``: IPython :epkg:`HTML` object
    * ``'rawhtml'``: :epkg:`HTML` as text + style
    * ``'rst'``: :epkg:`rst`
    * ``'text'``: raw text
    """
    if not isinstance(function_or_string, str):
        doc = function_or_string.__doc__
    else:
        doc = function_or_string

    if format == "text":
        return doc

    if doc is None:
        return ""

    javadoc = migrating_doxygen_doc(doc, "None", log=False)[1]
    rows = javadoc.split("\n")
    from .utils_sphinx_doc import _private_migrating_doxygen_doc
    rst = _private_migrating_doxygen_doc(
        rows, index_first_line=0, filename="None")
    rst = "\n".join(rst)
    ded = textwrap.dedent(rst)

    try:
        html = rst2html(ded, fLOG=fLOG, writer=writer,
                        keep_warnings=keep_warnings, directives=directives,
                        language=language, filter_nodes=filter_nodes,
                        document_name=document_name,
                        layout=layout, **options)
    except Exception:
        # we check the indentation
        ded = correct_indentation(ded)
        try:
            html = rst2html(ded, fLOG=fLOG, writer=writer,
                            keep_warnings=keep_warnings, directives=directives,
                            language=language, filter_nodes=filter_nodes,
                            document_name=document_name,
                            layout=layout, **options)
        except Exception as e:
            lines = ded.split("\n")
            lines = ["%04d  %s" % (i + 1, _.strip("\n\r"))
                     for i, _ in enumerate(lines)]
            raise HelpGenConvertError(
                "Unable to process:\n{0}".format("\n".join(lines))) from e

    ret_doctree = writer == "doctree"
    if ret_doctree:
        writer = "doctree"

    if writer in ('doctree', 'rst', 'md'):
        return html

    if format == "html":
        from IPython.core.display import HTML
        return HTML(html)
    if format in ("rawhtml", 'rst', 'md', 'doctree'):
        return html
    raise ValueError(
        "Unexpected format: '{}', should be html, rawhtml, text, rst, "
        "md, doctree.".format(format))

def rst2rst_folder(rststring, folder, document_name="index", **options):
    """
    Converts a :epkg:`RST` string into simplified :epkg:`RST`.

    @param      rststring       :epkg:`rst` string
    @param      folder          the builder needs to write the resuts in a
                                folder defined by this parameter
    @param      document_name   main document
    @param      options         additional options (same as *conf.py*)
    @return                     converted string
    """
    if not os.path.exists(folder):
        raise FileNotFoundError(folder)

    new_options = {}
    new_options.update(options)

    def update_builder(builder):
        builder.outdir = folder

    rst = rst2html(rststring, writer="rst", document_name="example",
                   update_builder=update_builder, layout="sphinx",
                   **new_options)
    return rst


# -*- coding: utf-8 -*-
from Action import Action
import util
import re
from datetime import datetime
import threading

class PrintSinaL2Action(Action):
    def __init__(self, **kwargs):
        Action.__init__(self, **kwargs )
        self._producer_list = [
            {
                 "name"             :    "SinaLevel2WS",
                 "producer_name"    :    "PrintSinaL2.SinaLevel2-quotation"
            }]
        self._init()
        self.logger.info(self._name +u"初始化")
        self.count = 0

    # 需要重写的方法
    def handler(self, event):
        dt = datetime.now()
        if isinstance(event.data, list):
            for data in event.data:
                self.count += 1
                print("PrintSinaL2:{}, \nCount:{},  Length: {}\n{}".format( dt,self.count, len(data),data ) )
        else:
            self.count += 1
            print("PrintSinaL2:{}, \nCount:{},  Length: {}\n{}".format( dt,self.count, len(event.data),event.data ) )

        # self.logger.info("线程退出")


# N,M = 3, 4
# price_per_weight = [0] + [2, 3, 5]
# cars = [0] + [200, 100, 300, 800]
# order = [0] +  [3, 2, -3, 1, 4, -4, -2, -1]

# 주차공간 N, M대의 차량
import sys
input = sys.stdin.readline
N, M = map(int,input().split())
price_per_weight = [0] + [int(input().rstrip()) for _ in range(N)]
cars = [0] + [int(input().rstrip()) for _ in range(M)]
order = [0] + [int(input().rstrip()) for _ in range(M*2)]

def find_vacant_space():
    for i in range(1,N+1):
            if not space[i]:
                return i
    return False

def find_car(car_num):
    for i in range(1, N+1):
        if space[i] == car_num:
            return i

ans = 0
space = [0] * (N+1)

waiting = []
for o in order:
    if o > 0: # 들어오는 케이스
        available = find_vacant_space()
        if available:
            space[available] = o

        else:
            waiting.append(o)

    else: # 나가는 case
        parking = find_car(-o)
        ans += price_per_weight[parking] * cars[-o]
        space[parking] = 0

        if waiting:
            parkable = find_vacant_space()
            space[parkable] = waiting.pop(0)

print(ans)


from math import sqrt
def count_div(num):
 count=0
 for x in range(1,int(sqrt(num)+1)):
  if num%x==0:
   count+=2
 return count

n=2000
num=(n*(n+1))/2
while True:
 some=count_div(num)
 if some<500:
  print (n,some)
  n+=1
  num=(n*(n+1))/2
 else:
  print(num,n,some)
  break


import scrapy
import logging
import re
from scrapy.selector import Selector
from urllib.parse import urljoin
from landchina.landchina_com.items import LandChinaItem, Payment
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import exists
from landchina.landchina_com.models.models import Record, create_engine
from scrapy.utils.project import get_project_settings

class LandSpider(scrapy.Spider):
    name = "landchina_com"
    root_url = "http://www.landchina.com/default.aspx?tabid=263"
    encoding = "gbk"
    start_date = "2018-6-20"
    end_date = "2018-6-25"
    begin_page = "1"
    postData = {'TAB_QueryConditionItem': '9f2c3acd-0256-4da2-a659-6949c4671a2a',
                'TAB_QuerySubmitConditionData': '9f2c3acd-0256-4da2-a659-6949c4671a2a:{}~{}'.format(
                    start_date, end_date),
                'TAB_QuerySortItemList': '282:False',
                'TAB_QuerySubmitPagerData': begin_page,
                'hidComName': 'default',
                '__VIEWSTATE': "",
                '__EVENTVALIDATION': ""}
    engine = create_engine(get_project_settings().get("CONNECTION_STRING"))
    session = sessionmaker(bind=engine)()

    def start_requests(self):
        self.log("begin login for {} - {}".format(self.start_date, self.end_date), logging.INFO)
        return [scrapy.Request(url=self.root_url, callback=self.parse_login, encoding=self.encoding)]
        # return [scrapy.Request(url='http://www.landchina.com/default.aspx?tabid=386&comname=default&wmguid=75c72564-ffd9-426a-954b-8ac2df0903b7&recorderguid=3a4498fe-ba10-4080-9cfd-e78f16b03db1', callback=self.parse_detail, encoding=self.encoding)]

    def parse_login(self, response):
        self.log("process login ...", logging.INFO)
        resp = Selector(response)
        self.retrieve_state(resp)

        self.log("begin page {} for {} - {}".format(self.postData["TAB_QuerySubmitPagerData"], self.start_date,
                                                    self.end_date), logging.INFO)
        return scrapy.FormRequest(url=self.root_url, callback=self.parse_list, formdata=self.postData,
                                  meta=self.postData, encoding=self.encoding)

    def parse_list(self, response):
        self.log("process list page {}".format(response.url), logging.INFO)
        resp = Selector(response)
        table = resp.xpath('//table[@id="TAB_contentTable"]')[0]

        # push detail page links to scrapy
        detail_links = table.xpath('//a[contains(@href, "tabid=386")]/@href').extract()
        for link in detail_links:
            matchObj = re.match(r'.*recorderguid=(.*)', link, re.M | re.I)
            if matchObj and self.record_exist(matchObj[1]):
                continue
            yield scrapy.Request(url=urljoin(self.root_url, link), callback=self.parse_detail, meta=response.meta,
                                 encoding=self.encoding)

        # push page links to scrapy
        if response.meta["TAB_QuerySubmitPagerData"] == self.begin_page:
            self.retrieve_state(resp)
            totalPage=int(self.begin_page) + 1
            try:
                totalPage = table.xpath("//a[contains(., '尾页')]").re_first(r"QueryAction.GoPage\('TAB',(\d*)").strip()
            except:
                pass
            for pageNo in range(int(self.begin_page), int(totalPage) + 1):
                self.log("begin page {} for {} - {}".format(pageNo, self.start_date, self.end_date), logging.INFO)
                self.postData["TAB_QuerySubmitPagerData"] = str(pageNo)
                yield scrapy.FormRequest(url=self.root_url, callback=self.parse_list, formdata=self.postData,
                                         meta=self.postData, encoding=self.encoding)

    def parse_detail(self, response):
        self.log("process detail page {}, {}".format(response.meta["TAB_QuerySubmitPagerData"], response.url),
                 logging.INFO)
        resp = Selector(response)
        childTrs = resp.xpath('//table[@class="theme"]/tbody/tr')
        data = LandChinaItem()
        data["url"] = response.url
        data["guid"] = resp.xpath('//form/@action').re_first(r'recorderguid=(.*)')
        data["district"] = childTrs[2].xpath('td[2]/span/text()').extract_first()
        data["regulationNo"] = childTrs[2].xpath('td[4]/span/text()').extract_first()
        data["name"] = childTrs[3].xpath('td[2]/span/text()').extract_first()
        data["location"] = childTrs[4].xpath('td[2]/span/text()').extract_first()
        data["area"] = childTrs[5].xpath('td[2]/span/text()').extract_first()
        are2 = childTrs[5].xpath('td[4]/span/text()').extract()
        try:
            if are2 == "" or not are2:
                data["landSource"] = "新增建设用地(来自存量库)"
            elif float(data["area"]) == float(are2):
                data["landSource"] = "现有建设用地"
            elif float(are2) == 0:
                data["landSource"] = "新增建设用地"
            else:
                data["landSource"] = "新增建设用地(来自存量库)"
        except:
            data["landSource"] = "新增建设用地(来自存量库)"
        data["usage"] = childTrs[6].xpath('td[2]/span/text()').extract_first()
        data["wayOfSupply"] = childTrs[6].xpath('td[4]/span/text()').extract_first()
        data["tenureOfUse"] = childTrs[7].xpath('td[2]/span/text()').extract_first()
        data["industry"] = childTrs[7].xpath('td[4]/span/text()').extract_first()
        data["landLevel"] = childTrs[8].xpath('td[2]/span/text()').extract_first()
        data["price"] = childTrs[8].xpath('td[4]/span/text()').extract_first()
        data["owner"] = childTrs[10].xpath('td[2]/span/text()').extract_first()
        plotRatio = childTrs[12].xpath('td/table//tr[2]/td')
        data["plotRatioDownLimit"] = plotRatio[1].xpath('span/text()').extract_first()
        data["plotRatioUpperLimit"] = plotRatio[3].xpath('span/text()').extract_first()
        data["dateOfDeliveryAgreed"] = childTrs[12].xpath('td[4]/span/text()').extract_first()
        data["dateOfConstructionAgreed"] = childTrs[13].xpath('td[2]/span/text()').extract_first()
        data["dateOfCompletionAgreed"] = childTrs[13].xpath('td[4]/span/text()').extract_first()
        data["dateOfConstructionActual"] = childTrs[14].xpath('td[2]/span/text()').extract_first()
        data["dateOfCompletionActual"] = childTrs[14].xpath('td[4]/span/text()').extract_first()
        data["approvedBy"] = childTrs[15].xpath('td[2]/span/text()').extract_first()
        if data["approvedBy"] is not None:
            if "人民政府" not in data["approvedBy"]:
                data["approvedBy"] += "人民政府"
        data["dateOfSigning"] = childTrs[15].xpath('td[4]/span/text()').extract_first()
        paymentsTrs = childTrs[9].xpath('td[2]//tr[contains(@kvalue, "-")]')
        payments = []
        for paymentsTr in paymentsTrs:
            payment = Payment()
            payment["guid"] = paymentsTr.xpath('@kvalue').extract_first()
            payment["date"] = paymentsTr.xpath('td[2]/span/text()').extract_first()
            payment["amount"] = paymentsTr.xpath('td[3]/span/text()').extract_first()
            payment["comment"] = paymentsTr.xpath('td[4]/span/text()').extract_first()
            payments.append(dict(payment))
        data["payments"] = payments
        return data

    def parse(self, response):
        self.log("process parse func {}".format(response.url), logging.INFO)
        pass

    def retrieve_state(self, resp):
        vs = resp.xpath('//input[@id="__VIEWSTATE"]/@value').extract_first().strip()
        ev = resp.xpath('//input[@id="__EVENTVALIDATION"]/@value').extract_first().strip()
        self.postData['__VIEWSTATE'] = vs
        self.postData['__EVENTVALIDATION'] = ev

    def record_exist(self, guid):
        return self.session.query(exists().where(Record.guid == guid)).scalar()


from flask import Flask, request, render_template, redirect, url_for, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from socket import gethostname

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///job_website.sqlite3.db'
CORS(app)
db = SQLAlchemy(app)

#CLASS Post_Job THAT CREATES TABLE post_job IN DATABASE
class Post_Job(db.Model):
    job_id = db.Column(db.Integer(), primary_key=True)
    job_title = db.Column(db.String())
    job_location = db.Column(db.String())
    job_requirements = db.Column(db.String())
    job_other_skills = db.Column(db.String())
    job_about = db.Column(db.String())
    job_apply = db.Column(db.String())

    def to_dict(self):
        result = {}

        for key in self.__mapper__.c.keys():
            if getattr(self, key) is not None:
                result[key] = str(getattr(self, key))
            else:
                result[key] = getattr(self, key)
        return result

#HOMEPAGE
@app.route('/')
def home():
    job_list = Post_Job.query.all()
    return render_template('index.html',job_list=job_list)

#ROUTE ADD JOBS THAT USES FUNCTION ADD NEW JOBS
@app.route('/add')
def add():
    jobs = Post_Job.query.all()
    return render_template('add_jobs.html',jobs=jobs)

#FUNCTION ADD NEW JOBS
@app.route('/job/add', methods=['POST'])
def add_job():
    try:
        form = request.form
        post = Post_Job(
            job_title=form['job_title'],
            job_location=form['job_location'],
            job_requirements=form['job_requirements'],
            job_other_skills=form['job_other_skills'],
            job_about=form['job_about'],
            job_apply = form['job_apply']
            )
        db.session.add(post)
        db.session.commit()
    except Exception as error:
        print('Error',error)
    return redirect(url_for('home'))

#LISTS ALL JOBS
@app.route('/list')
def list_jobs():
    job_list = Post_Job.query.all()
    return render_template('list_jobs.html',job_list=job_list)

#EDIT JOBS USING ID
@app.route('/job/<id>/edit', methods=['POST','GET'])
def edit_jobs(id):
    if request.method == 'POST':
        try:
            edit = Post_Job.query.get(id)
            form = request.form
            edit.job_title = form['job_title']
            edit.job_location = form['job_location']
            edit.job_requirements = form['job_requirements']
            edit.job_other_skills = form['job_other_skills']
            edit.job_about = form['job_about']
            edit.job_apply = form['job_apply']
            db.session.commit()
        except Exception as error:
            print('Error',error)
        return redirect(url_for('list_jobs'))
    else:
        try:
            edit = Post_Job.query.get(id)
            return render_template('edit_jobs.html',edit=edit)
        except Exception as error:
            print('Error',error)
    return redirect(url_for('list_jobs'))

#DELETE JOBS USING ID
@app.route('/job/<id>/del')
def delete_job(id):
    try:
        job = Post_Job.query.get(id)
        db.session.delete(job)
        db.session.commit()
    except Exception as error:
        print('Error',error)
    return redirect(url_for('list_jobs'))

#API JOBS LIST
@app.route('/api/jobs')
def api_list_jobs():
    try:
        api_jobs = Post_Job.query.all()
        return jsonify([jobs.to_dict() for jobs in api_jobs])
    except Exception as error:
        print('Error',error)
    return jsonify([])

#API ADD JOBS
@app.route('/api/add_jobs', methods=['PUT'])
def api_add_jobs():
    try:
        form = request.get_json()
        jobs = Post_Job(
            job_title=form['job_title'],
            job_location=form['job_location'],
            job_requirements=form['job_requirements'],
            job_other_skills=form['job_other_skills'],
            job_about=form['job_about'],
            job_apply = form['job_apply']
            )
        db.session.add(jobs)
        db.session.commit()
        return jsonify({'success':True})
    except Exception as error:
        print('Error',error)
    return jsonify({'success':False})

# #API EDIT
# @app.route('/api/post/<id>', methods=['PUT'])
# def api_edit_post(id):
#     try:
#         post = Post.query.get(id)
#         data = request.get_json()
#         post.title = data['title']
#         post.content = data['content']
#         post.author = data['author']
#         db.session.commit()
#         return jsonify({'success':True})
#     except Exception as error:
#         print('Error',error)

#     return jsonify({'success':False})

# #API DELETE
# @app.route('/api/post/<id>/', methods=['DELETE'])
# def api_delete_post(id):
#     try:
#         post = Post.query.get(id)
#         db.session.delete(post)
#         db.session.commit()
#         return jsonify({'success':True})
#     except Exception as error:
#         print('Error',error)
#     return jsonify({'success':False})

app.run(debug=True)

with app.app_context():
    db.create_all()
    db.session.commit()


from music21 import *
import ashes
import sys

xmlName = sys.argv[1]
s = converter.parse(xmlName)

while True:
	raw_intput = input("transpose index, interval: ")
	if raw_intput:
		p_index, interval_str = raw_intput.split()
		s.parts[int(p_index)].transpose(interval.Interval(interval_str), inPlace=True)
	else:
		break

measureNumber = len(s.parts[0].getElementsByClass('Measure'))

for i in range(1, measureNumber+1):
	# print(i)
	m = s.measure(i)
	ashesAnalysis = ashes.Ashes(m)
	if ashesAnalysis.isValidMeasure():
		step1 = ashesAnalysis.verticalMatch()
		step2 = ashesAnalysis.verticalMerge()
		step3 = ashesAnalysis.horizontalMerge()
		chordDict = ashesAnalysis.getChordinBeat()
		for part in m.parts[::-1]:
			for n in part.recurse().getElementsByClass('GeneralNote'):
				if (n.isNote or n.isChord) and n.beat in chordDict:
					n.addLyric(chordDict[n.beat].getPrintNotation() if chordDict[n.beat] else "N/A")
					del chordDict[n.beat]
s.show()


"""
Author: Abdullah Najjar
Version: 0.1
Description: This game is called Adventure
# TODO: Fix player speed and problem in movement, also screen size issues + add map tiling
"""
import arcade
import os
import random

# Global variables
SPRITE_SCALING = 0.5 #Character size
SPRITE_SCALING_COIN = .50 #Size of coins
COIN_COUNT = 50 #Number of coins

SCREEN_WIDTH = 800 #Width of window
SCREEN_HEIGHT = 600 #Height of window
SCREEN_TITLE = "Adventure" #Window title

MAX_SPEED = 2.7 # Speed limit
ACCELERATION_RATE = 0.1 # How fast we accelerate
FRICTION = 0.02 # How fast to slow down after we letr off the key

SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = (SPRITE_PIXEL_SIZE * SPRITE_SCALING)

# How many pixels to keep as a minimum margin between the character
# and the edge of the screen.
VIEWPORT_MARGIN = SPRITE_PIXEL_SIZE * SPRITE_SCALING
RIGHT_MARGIN = 4 * SPRITE_PIXEL_SIZE * SPRITE_SCALING

# Physics
MOVEMENT_SPEED = 4 * SPRITE_SCALING
JUMP_SPEED = 50 * SPRITE_SCALING
GRAVITY = .5 * SPRITE_SCALING

class Player(arcade.Sprite):
    """
    Player class
    """
    def update(self):
        """
        Update for the movement of the player
        # TODO: Make the screen edge move as the player moves
        """
        self.center_x += self.change_x
        self.center_y += self.change_y

        # Check to see if we hit the screen edge
        if self.left < 0:
            self.left = 0
            self.change_x = 0 # Zero x speed
        elif self.right > SCREEN_WIDTH - 1:
            self.right = SCREEN_WIDTH - 1
            self.change_x = 0

        if self.bottom < 0:
            self.bottom = 0
            self.change_y = 0
        elif self.top > SCREEN_HEIGHT - 1:
            self.top = SCREEN_HEIGHT - 1
            self.change_y = 0

class MyGame(arcade.Window):
    """
    Main application class.
    """

    def __init__(self, width, height, title):
        """
        Initializer
        """

        # Call the parent class initializer
        super().__init__(width, height, title)

        # Set the working directory (where we expect to find files) to the same
        # directory this .py file is in. You can leave this out of your own
        # code, but it is needed to easily run the examples using "python -m"
        # as mentioned at the top of this program.
        file_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(file_path)

        # Variables that will hold sprite lists
        self.all_sprites_list = None
        self.all_wall_list = None
        self.static_wall_list = None
        self.moving_wall_list = None
        self.player_list = None
        self.coin_list = None

        # Set up the player info
        self.player_sprite = None
        self.physics_engine = None
        self.view_left = 0
        self.view_bottom = 0
        self.end_of_map = 0
        self.game_over = False

        self.score = 0

        # Track the current state of what key is pressed
        self.left_pressed = False
        self.right_pressed = False
        self.up_pressed = False
        self.down_pressed = False

        width, height = self.get_size()
        self.set_viewport(0, width, 0, height)

        # Set the background color
        arcade.set_background_color(arcade.color.BABY_BLUE)

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists -> Player & coins
        self.player_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()
        self.all_wall_list = arcade.SpriteList()
        self.static_wall_list = arcade.SpriteList()
        self.moving_wall_list = arcade.SpriteList()

        self.score = 0    # Score

        # Set up the player character image, size and position
        self.player_sprite = Player(":resources:images/animated_characters/male_adventurer/maleAdventurer_walk7.png", SPRITE_SCALING)
        self.player_sprite.center_x = 2 * GRID_PIXEL_SIZE
        self.player_sprite.center_y = 3 * GRID_PIXEL_SIZE
        self.player_list.append(self.player_sprite)

        # Create floor
        for i in range(30):
            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", SPRITE_SCALING)
            wall.bottom = 0
            wall.center_x = i * GRID_PIXEL_SIZE
            self.static_wall_list.append(wall)
            self.all_wall_list.append(wall)

        # Create platform side to side
        wall = arcade.Sprite(":resources:images/tiles/grassMid.png", SPRITE_SCALING)
        wall.center_y = 3 * GRID_PIXEL_SIZE
        wall.center_x = 3 * GRID_PIXEL_SIZE
        wall.boundary_left = 2 * GRID_PIXEL_SIZE
        wall.boundary_right = 5 * GRID_PIXEL_SIZE
        wall.change_x = 2 * SPRITE_SCALING

        self.all_wall_list.append(wall)
        self.moving_wall_list.append(wall)

        # Create platform side to side
        wall = arcade.Sprite(":resources:images/tiles/grassMid.png", SPRITE_SCALING)
        wall.center_y = 3 * GRID_PIXEL_SIZE
        wall.center_x = 7 * GRID_PIXEL_SIZE
        wall.boundary_left = 5 * GRID_PIXEL_SIZE
        wall.boundary_right = 9 * GRID_PIXEL_SIZE
        wall.change_x = -2 * SPRITE_SCALING

        self.all_wall_list.append(wall)
        self.moving_wall_list.append(wall)

        # Create platform moving up and down
        wall = arcade.Sprite(":resources:images/tiles/grassMid.png", SPRITE_SCALING)
        wall.center_y = 5 * GRID_PIXEL_SIZE
        wall.center_x = 5 * GRID_PIXEL_SIZE
        wall.boundary_top = 8 * GRID_PIXEL_SIZE
        wall.boundary_bottom = 4 * GRID_PIXEL_SIZE
        wall.change_y = 2 * SPRITE_SCALING

        self.all_wall_list.append(wall)
        self.moving_wall_list.append(wall)

        # Create platform moving diagonally
        wall = arcade.Sprite(":resources:images/tiles/grassMid.png", SPRITE_SCALING)
        wall.center_y = 5 * GRID_PIXEL_SIZE
        wall.center_x = 8 * GRID_PIXEL_SIZE
        wall.boundary_left = 7 * GRID_PIXEL_SIZE
        wall.boundary_right = 9 * GRID_PIXEL_SIZE

        wall.boundary_top = 8 * GRID_PIXEL_SIZE
        wall.boundary_bottom = 4 * GRID_PIXEL_SIZE
        wall.change_x = 2 * SPRITE_SCALING
        wall.change_y = 2 * SPRITE_SCALING

        self.all_wall_list.append(wall)
        self.moving_wall_list.append(wall)

        self.physics_engine = \
            arcade.PhysicsEnginePlatformer(self.player_sprite,
                                           self.all_wall_list,
                                           gravity_constant=GRAVITY)

        # Create the coins
        for i in range(COIN_COUNT):

            # Create the coin instance -> The Coin image from kenney.nl
            coin = arcade.Sprite(":resources:images/items/coinGold.png",
                                 SPRITE_SCALING_COIN)

            # Position the coin
            coin.center_x = random.randrange(SCREEN_WIDTH)
            coin.center_y = random.randrange(SCREEN_HEIGHT)

            # Add the coin to the lists
            self.coin_list.append(coin)

        # Set the viewport boundaries
        # These numbers set where we have 'scrolled' to.
        self.view_left = 0
        self.view_bottom = 0

        self.game_over = False

    def on_draw(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        arcade.start_render()

        # Get viewport dimensions
        left, screen_width, bottom, screen_height = self.get_viewport()

        self.coin_list.draw()
        self.static_wall_list.draw()
        self.moving_wall_list.draw()

        # Put the text on the screen.
        # Adjust the text position based on the viewport so that we don't
        # scroll the text too.
        # distance = self.player_sprite.right
        # output = f"Distance: {distance}"
        # arcade.draw_text(output, self.view_left + 10, self.view_bottom + 20,
        #                  arcade.color.WHITE, 14)

        # Put the text on the screen.
        output = f"Score: {self.score}"
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

        self.player_list.draw()         # Draw all the sprites.

        # Display speed
        arcade.draw_text(f"X Speed: {self.player_sprite.change_x:6.3f}", 10, 50, arcade.color.WHITE)
        arcade.draw_text(f"Y Speed: {self.player_sprite.change_y:6.3f}", 10, 70, arcade.color.WHITE)

    def on_update(self, delta_time):
        """ Movement and game logic """

        # Call update on all sprites (The sprites don't do much in this
        # example though.)
        self.coin_list.update()
        self.physics_engine.update()

        # Track if we need to change the viewport

        changed = False
        # Generate a list of all sprites that collided with the player.
        coins_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)

        # Loop through each colliding sprite, remove it, and add to the score.
        for coin in coins_hit_list:
            coin.remove_from_sprite_lists()
            self.score += 1

        # Add some friction
        if self.player_sprite.change_x > FRICTION:
            self.player_sprite.change_x -= FRICTION
        elif self.player_sprite.change_x < -FRICTION:
            self.player_sprite.change_x += FRICTION
        else:
            self.player_sprite.change_x = 0

        if self.player_sprite.change_y > FRICTION:
            self.player_sprite.change_y -= FRICTION
        elif self.player_sprite.change_y < -FRICTION:
            self.player_sprite.change_y += FRICTION
        else:
            self.player_sprite.change_y = 0

        # Apply acceleration based on the keys pressed
        if self.up_pressed and not self.down_pressed:
            self.player_sprite.change_y += ACCELERATION_RATE
        elif self.down_pressed and not self.up_pressed:
            self.player_sprite.change_y += -ACCELERATION_RATE
        if self.left_pressed and not self.right_pressed:
            self.player_sprite.change_x += -ACCELERATION_RATE
        elif self.right_pressed and not self.left_pressed:
            self.player_sprite.change_x += ACCELERATION_RATE

        if self.player_sprite.change_x > MAX_SPEED:
            self.player_sprite.change_x = MAX_SPEED
        elif self.player_sprite.change_x < -MAX_SPEED:
            self.player_sprite.change_x = -MAX_SPEED
        if self.player_sprite.change_y > MAX_SPEED:
            self.player_sprite.change_y = MAX_SPEED
        elif self.player_sprite.change_y < -MAX_SPEED:
            self.player_sprite.change_y = -MAX_SPEED

        # Call update to move the sprite
        # If using a physics engine, call update on it instead of the sprite
        # list.
        self.player_list.update()

    def on_key_press(self, key, modifiers):
        """Called whenever a key is pressed. """

        if key == arcade.key.UP:
            self.up_pressed = True
        elif key == arcade.key.DOWN:
            self.down_pressed = True
        elif key == arcade.key.LEFT:
            self.left_pressed = True
        elif key == arcade.key.RIGHT:
            self.right_pressed = True

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key. """

        if key == arcade.key.UP:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = JUMP_SPEED
        elif key == arcade.key.LEFT:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif key == arcade.key.RIGHT:
            self.player_sprite.change_x = MOVEMENT_SPEED

def main():
    """ Main method """
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
    window.setup()
    arcade.run()

if __name__ == "__main__":
    main()


#!/usr/bin/python

import time
import virtGPIO as GPIO

led = 9

# Demonstrate classic digital read/write, & analog read, and pwm

# Setup: a LED on pin 9,
#        plus a jumper from pin 9 to pin A2

GPIO.setup(led,GPIO.OUT)
c = 0

while True:

    c = (c+21)
    GPIO.output(led,c & 1)   # LED blink
    print ("Written LED as %d" % (c&1))

    # read it back
    print ("pin%d=%x" % (led, GPIO.input(led)))

    # Analog 2 is tied to LED, so should go from 0000 to 03FF  (0 to 1023)
    print ("anl2 = %04x" % GPIO.analogRead(GPIO.A2))

    time.sleep(5)

    # pin 9 is also a native PWM pin on arduino:
    print ("Changing pwm brightness to %d" % (c%255))
    GPIO.pwmWrite(led, c % 256)

    time.sleep(6)


import cv2 as cv
import numpy as np
import google_streetview.api as gsv
import matplotlib.pyplot as plt
import math

# enter venv : > src/Scripts/activate

# feature match params

sift = cv.SIFT_create()

FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)

flann = cv.FlannBasedMatcher(index_params, search_params)

# get key

f = open('MapRH/key.txt', 'r')
API_KEY = f.read()

# find near addresses

def iter_string(string, p):
	fstword = string.split()[0]

	remaining = ""

	for i in range (1, len(string.split())):
		remaining = remaining + " " + string.split()[i]

	fstword = str(int(fstword) + p)

	reconst = fstword + remaining

	return reconst

# get the coordinates of the images

def get_c(r1, r2):
	k = ['date', 'location', 'pano_id', 'status']

	for i, kv in enumerate(r1.metadata[:10]):
		for ki in k:
			if ki in kv:
				if ki == 'location':
					cl1 = [kv[ki]['lng'], kv[ki]['lat']]

	for i, kv in enumerate(r2.metadata[:10]):
		for ki in k:
			if ki in kv:
				if ki == 'location':
					cl2 = [kv[ki]['lng'], kv[ki]['lat']]

	return cl1, cl2

# calculate distance between coordinates

def c_dist(c1, c2):
	long1, lat1 = c1[0], c1[1]
	long2, lat2 = c2[0], c2[1]

	R = 6317

	phi1 = lat1 * math.pi / 180
	phi2 = lat2 * math.pi / 180
	d_phi = (lat2 - lat1) * math.pi / 180
	d_lam = (long2 - long1) * math.pi / 180

	a = math.sin(d_phi/2) * math.sin(d_phi/2) + math.cos(phi1) * math.cos(phi2) * math.sin(d_lam/2) * math.sin(d_lam/2)
	c = 2*math.atan2(math.sqrt(a), math.sqrt(1 - a))
	d = R * c * 1000

	return d

# get single image

def get_image(loc, heading, pitch, name):

	params = [{
		'size': '480x480', # max 640x640 pixels
		'location': loc,
		'heading': heading,
		'pitch': pitch,
		'key': API_KEY
	}]

	results = gsv.results(params)

	for i, url in enumerate(results.links):
		if results.metadata[i]['status'] == 'OK':
			file_path = 'MapRH/Images/' + name + '.jpg'
			gsv.helpers.download(url, file_path)

	return results

# get all images

def get_scene(loc):
	res = []

	locs = [iter_string(loc, 2), iter_string(loc, 4)]
	count = 0

	for l in locs:
		res.append(get_image(l, 157, 0, str(count)))
		count = count + 1

	c1, c2 = get_c(res[0], res[1])
	return c_dist(c1, c2)

def draw_pts(img, pts):
	img_out = img
	for pt in pts:
		x = pt[0]
		y = pt[1]

		img_out = cv.circle(img_out, (int(x), int(y)), radius=5, color=(0, 255, 0), thickness=3)

	return img_out

# pixel disparity

def disp(x1, x2):
    return abs(x1 - x2)

# 3D coordinate calculation

def pt(pL, pR):
    u_l, v_l = pL[0], pL[1]
    u_r, v_r = pR[0], pR[1]

    d = disp(u_l, u_r)

    x = (b/d) * (u_l - im1.shape[0]/2)
    y = (b/d)  * (v_l - im1.shape[1]/2)
    z = (b/d) * 100

    return [x, y, z]

b = get_scene('ENTER ADDRESS HERE') #c_dist([43.6684822,-79.3950423], [43.6685049,-79.394918])

# load images and detect matching points

im1 = cv.imread('MapRH/Images/0.jpg')
im2 = cv.imread('MapRH/Images/1.jpg')

pts_1, desc_1 = sift.detectAndCompute(im1, None)
pts_2, desc_2 = sift.detectAndCompute(im2, None)

matches = flann.knnMatch(desc_1, desc_2, k=2)

masked_1_pts = []
masked_2_pts = []

lowe_coeff = 0.8

for i0, (m0,n0) in enumerate(matches):
    if m0.distance < lowe_coeff * n0.distance:
        masked_2_pts.append(pts_2[m0.trainIdx].pt)
        masked_1_pts.append(pts_1[m0.queryIdx].pt)

masked_1_pts = np.int32(masked_1_pts)
masked_2_pts = np.int32(masked_2_pts)

F, mask = cv.findFundamentalMat(masked_1_pts, masked_2_pts, cv.FM_LMEDS)

masked_1_pts = masked_1_pts[mask.ravel()==1]
masked_2_pts = masked_2_pts[mask.ravel()==1]

# calculate x, y, z values

pts_3D = []

for p in range (len(masked_1_pts[:, 0])):
    pt_3D = pt(masked_1_pts[p, :], masked_2_pts[p, :])
    pts_3D.append(pt_3D)

pts_3D = np.double(pts_3D)

# plot on x, y, z axes

fig = plt.figure()
ax = plt.axes(projection='3d')

ax.scatter3D(pts_3D[:, 0], pts_3D[:, 1], pts_3D[:, 2], 'gray')
# ax.set_zlim(0, max(pts_3D[:, 2]) + 0.2)
# ax.set_ylim(min(pts_3D[:, 1]) - 0.1, max(pts_3D[:, 1]) + 0.1)
# ax.set_xlim(min(pts_3D[:, 0]) - 0.1, max(pts_3D[:, 0]) + 0.1)

plt.show()

# pt_im1 = draw_pts(im1, masked_1_pts)
# pt_im2 = draw_pts(im2, masked_2_pts)

# plt.imshow(pt_im2)
# plt.show()


import GUI
from GUI.MovieWindow import MovieWindow
from pyforms import BaseWidget
from pyforms.Controls import ControlList, ControlText, ControlButton

# TO DO: write specifications

class MovieListWindow(BaseWidget):
    """
    This applications is a GUI implementation of the People class
    """

    def __init__(self, movieController, rentalController):
        # MovieController.__init__(self, R)
        BaseWidget.__init__(self, 'Movie')
        # Definition of the forms fields2
        self._searchInput = ControlText("Search")
        self._searchButton = ControlButton("Go")
        self._formset = [
            ('_searchInput',
             ('_searchButton')),
            ("_movieList")
        ]

        self._movieList = ControlList('Movies',
                                      plusFunction=self.__addPersonBtnAction,
                                      minusFunction=self.__removeMovieBtnAction)
        self.__controller = movieController
        self.__rentalController = rentalController
        data = [[x.id, x.title, x.description, x.genre] for x in self.__controller.getAllMovies()]
        self._movieList.value += data
        self._movieList.selectEntireRow = True
        self._movieList.readOnly = True
        self._movieList.horizontalHeaders = ['Id', 'Title', 'Description', 'Genre']
        self._movieList.cellDoubleClicked = self.updateMovieAction
        self._searchButton.value = self.searchData

    def updateMovieAction(self, row, item):
        win = MovieWindow(False)
        win.getData(*self._movieList.value[row])
        win.parent = self
        win.show()

    def __addPersonBtnAction(self):
        """
        Add person button event.
        """
        # A new instance of the PersonWindow is opened and shown to the user.
        win = MovieWindow(True)
        win.parent = self
        win.show()

    def addMovie(self, id, title, description, genre):
        self.__controller.addMovie(id, title, description, genre)
        self.renderData()

    def updateMovie(self, id, title, description, genre):
        self.__controller.updateMovie(id, title, description, genre)
        self.renderData()

    def __removeMovieBtnAction(self):
        """
        Remove movie button event
        """
        # self.removePerson(self._peopleList.selected_row_index)
        if len(self._movieList.mouseSelectedRowsIndexes) == 1:
            self.__controller.removeMovie(int(self._movieList.value[self._movieList.mouseSelectedRowIndex][0]))
            self.__rentalController.removeAllAppOfMovie(self._movieList.value[self._movieList.mouseSelectedRowIndex][0])
        else:
            for i in self._movieList.mouseSelectedRowsIndexes:
                self.__controller.removeMovie(int(self._movieList.value[i][0]))
                self.__rentalController.removeAllAppOfMovie(self._movieList.value[i][0])
        self.renderData()
        # Execute the application

    def renderData(self):
        data = [[x.id, x.title, x.description, x.genre] for x in GUI.MainApp.MainApp.movieController.getAllMovies()]
        self._movieList.value = data

    def searchData(self):
        self.renderData()
        data = self._movieList.value
        search = self._searchInput.value
        values = []
        if len(search.strip()) == 0:
            self.renderData()
            return
        for d in data:
            for l in d:
                if search.strip().lower() in l.lower():
                    values.append(d)
                    break
        self._movieList.value = values


from datetime import datetime
from bson.tz_util import FixedOffset
from bson.regex import Regex
import unidecode

class Produtos:
    connection = None
    def __init__(self, connection):
        self.connection = connection
        self.database = self.connection['DigisatServer']
        self.collection_movimentacoes = self.database["Movimentacoes"]
        self.collection_produtos_servicos = self.database["ProdutosServicos"]
        self.collection_pessoas = self.database["Pessoas"]

    def get_prods(self):
        query = {"Ativo": True, "CamposPersonalizado": {u"$exists": True}}
        cursor = self.collection_produtos_servicos.find(query)
        produtos = []
        try:
            for doc in cursor:
                produto = {
                    'codigo': doc['CodigoInterno'],
                    'descricao': doc['Descricao'],
                    'marca': '',
                    'produto': False,
                    'tipo': False,
                    'classe': False,
                    'especie': False,
                    'percentual': False,
                    'safra': False,
                    'unidade': doc['UnidadeMedida']['Sigla']
                }
                if 'Marca' in doc:
                        produto['Marca'] = doc['Marca']['Descricao']

                if 'CamposPersonalizado' in doc:
                    for campo in doc['CamposPersonalizado']:
                        if campo['TipoPersonalizado']['Ativo'] is True:
                            campo_desc = unidecode.unidecode(campo['TipoPersonalizado']['Descricao']).lower()
                            if  campo_desc == 'codigo_sisdevin' and campo['Valor'] != '':
                                produto['codigo'] = campo['Valor']

                            if  campo_desc == 'produto' and campo['Valor'] != '':
                                produto['produto'] = campo['Valor']

                            if campo_desc == 'tipo' and campo['Valor'] != '':
                                produto['tipo'] = campo['Valor']

                            if campo_desc == 'classe' and campo['Valor'] != '':
                                produto['classe'] = campo['Valor']

                            if campo_desc == 'especie' and campo['Valor'] != '':
                                produto['especie'] = campo['Valor']

                            if campo_desc == 'percentual' and campo['Valor'] != '':
                                produto['percentual'] = campo['Valor']

                            if campo_desc == 'safra' and campo['Valor'] != '':
                                produto['safra'] = campo['Valor']

                if produto not in produtos and False not in produto.values():
                    produtos.append(produto)
        finally:
            return produtos

    def get_notas(self):
        produtos = []
        gte, lte = self.get_period()
        query = {
            "DataHoraEmissao": {
                u"$gte": gte,
                u"$lte": lte
            },
            "$or": [
                {
                    u"_t": Regex(u".*NotaFiscalEletronicaSaida.*", "i")
                },
                {
                    u"_t": Regex(u".*NotaFiscalConsumidorEletronica.*", "i")
                }
            ],
            "Situacao.Codigo": {
                u"$not": {
                    u"$in": [
                        1,
                        4,
                        12
                    ]
                }
            }
        }

        cursor = self.collection_movimentacoes.find(query)
        notas = []

        for doc in cursor:
            if 'NotaFiscalConsumidorEletronica' in doc['_t']:
                tipo = 2
            elif 'NotaFiscalEletronicaSaida' in doc['_t']:
                tipo = 1
            else:
                tipo = 3

            if 'EnderecoPrincipal' not in doc['Pessoa']:
                pessoa = self.collection_pessoas.find_one({'_id': doc['Pessoa']['PessoaReferencia']})
                pessoa = pessoa['Carteira']
            else:
                pessoa = doc['Pessoa']

            nota = {
                'mes':doc['DataHoraEmissao'].month,
                'ano': doc['DataHoraEmissao'].year,
                'operacao': '01',
                'numero': doc['Numero'],
                'uf': pessoa['EnderecoPrincipal']['Municipio']['Uf']['Sigla'],
                'tipo': tipo,
                'serie': doc['Serie'],
                'itens': []
            }

            for item in doc['ItensBase']:
                prod = self.collection_produtos_servicos.find_one({'_id': item['ProdutoServico']['ProdutoServicoReferencia']})
                valid = self.is_prod_valid(prod)
                if valid:
                    prod_valid = {
                        'produto': '',
                        'embalagem': '',
                        'litros': ''
                    }
                    for campo in prod['CamposPersonalizado']:
                        if campo['TipoPersonalizado']['Ativo'] is True:
                            campo_desc = unidecode.unidecode(campo['TipoPersonalizado']['Descricao']).lower()
                            if  campo_desc == 'codigo_sisdevin' and campo['Valor'] != '':
                                prod_valid['produto'] = campo['Valor']

                            if  campo_desc == 'embalagem' and campo['Valor'] != '':
                                prod_valid['embalagem'] = campo['Valor']

                            if  campo_desc == 'quantidade_baixar' and campo['Valor'] != '':
                                prod_valid['litros'] = item['Quantidade'] * campo['Valor']
                    nota['itens'].append(prod_valid)
            if nota['itens']:
                notas.append(nota)
        return notas

    def is_prod_valid(self, doc):
        cont = 0
        campos = ['codigo_sisdevin', 'embalagem', 'quantidade_baixar']
        if 'CamposPersonalizado' in doc:
            for campo in doc['CamposPersonalizado']:
                if campo['TipoPersonalizado']['Ativo'] is True:
                    campo_desc = unidecode.unidecode(campo['TipoPersonalizado']['Descricao']).lower()
                    for x in campos:
                        if campo_desc == x and campo['Valor'] != '':
                            cont += 1
            if cont == len(campos):
                return True
            else:
                return False
        else:
            return False

    def get_period(self):
        date = datetime.now()
        try:
            date_initial = input('Digite a data inicial no seguinte formato DIA-MES-ANO, exemplo {0}-{1}-{2}: '.format(date.day, date.month, date.year))
            gte = datetime.strptime("{0} 00:00:00.000000".format(date_initial), "%d-%m-%Y %H:%M:%S.%f").replace(tzinfo = FixedOffset(-180, "-0300"))
        except:
            print('Data inicial ou formato, incorreto, vamos tentar de novo')
            gte, lte = self.get_period()

        try:
            date_ended = input('Digite a data final no seguinte formato DIA-MES-ANO, exemplo {0}-{1}-{2}: '.format(date.day, date.month, date.year))
            lte = datetime.strptime("{0} 23:59:59.000000".format(date_ended), "%d-%m-%Y %H:%M:%S.%f").replace(tzinfo = FixedOffset(-180, "-0300"))
        except:
            print('Data final invalida ou formato, incorreto, vamos tentar de novo')
            gte, lte = self.get_period()
        return gte, lte


#coding: utf-8
import re

class Field:

    name = None
    type = None
    length = None
    unsigned = None
    character_set = None
    collate = None
    not_null = None
    auto_increment = None
    default = None
    comment = None

    def __str__(self):
        sql = "`%s` %s" % (self.name, self.type)

        if self.length != None:
            sql += "(" + self.length + ")"

        if self.unsigned == True:
            sql += " UNSIGNED"

        if self.auto_increment == True:
            sql += " AUTO_INCREMENT"

        if self.character_set != None:
            sql += " CHARACTER SET " + self.character_set

        if self.collate != None:
            sql += " COLLATE " + self.collate

        if self.not_null == True:
            sql += " NOT NULL"

        if self.default != None:
            sql += " DEFAULT " + self.default

        if self.comment != None:
            sql += " COMMENT " + self.comment

        return sql

class Key:

    name = None
    field = None
    using = None
    type = None

    def __str__(self):
        if self.type == 'PRIMARY':
            return "PRIMARY KEY (%s)" % (self.field)

        sql = "";
        if self.type != None:
            sql += self.type + " "

        sql += "INDEX `" + self.name + "` (" +self.field+ ")"

        if self.using != None:
            sql += " USING " + self.using

        return sql

def parse_sql(lines):
    data = {}

    table = ''; fields = {}; field_sort = []; keys = {}; sql = ''; state = 0

    for line in lines:
        line = line.strip()

        if line == "":
            continue

        if state == 0:
            r = re.match('^CREATE\s+TABLE\s+`(\w+)`\s+\($', line, re.IGNORECASE)
            if r:
                table = r.group(1)
                sql += line + "\n"
                state = 1

                continue

            if line[0:2] == '/*':             # 注释
                continue

            if line[0:3] == '-- ':            # 注释
                continue

            if line[0:4].upper() == 'SET ':   # SET
                continue

            if line[0:5].upper() == 'DROP ':  # DROP TABLE
                continue

            if line == '--':                  # 空注释
                continue

        elif state == 1:
            sql += line + "\n"

            r = re.match("^`(\w+)`\s+(\w+)(?:\((.*?)\))*(\s+UNSIGNED)*(?:\s+CHARACTER\s+SET\s+(\w+))*(?:\s+COLLATE\s+(\w+))*(\s+NOT\s+NULL)*(\s+AUTO_INCREMENT)*(?:\s+DEFAULT\s+(.*?))*(?:\s+COMMENT\s+('.*?'))*,*$", line, re.IGNORECASE)
            if r:
                comment = r.group(10)
                origin = None

                if comment != None:
                    r_opt = re.match('^\'<origin:(\w+)>(.*?)\'$', comment)
                    if r_opt:
                        origin = r_opt.group(1)
                        comment = r_opt.group(2)

                field = Field()
                field.name = r.group(1)
                field.type = r.group(2)
                field.length = r.group(3)
                field.unsigned = r.group(4) != None
                field.character_set = r.group(5)
                field.collate = r.group(6)
                field.not_null = r.group(7) != None
                field.auto_increment = r.group(8) != None
                field.default = r.group(9)
                field.comment = comment

                if origin != None:
                    field_key = origin
                else:
                    field_key = field.name

                if fields.has_key(field_key):
                    raise Exception('"' + table + '.' + field_key + '" already exists')

                field_sort.append(field_key)
                fields[field_key] = field

                continue

            r = re.match('^(?:(FULLTEXT|UNIQUE)\s+)*KEY\s+`(\w+)`\s+\((.*?)\)(?:\s+USING\s+(\w+))*,*$', line, re.IGNORECASE)
            if r:
                key = Key()
                key.name = r.group(2)
                key.field = r.group(3)
                key.using = r.group(4)
                key.type = r.group(1)

                keys[key.name] = key

                continue

            r = re.match('^PRIMARY\s+KEY\s+\((.*?)\),*$', line, re.IGNORECASE)
            if r:
                key = Key()
                key.field = r.group(1)
                key.type = 'PRIMARY'

                keys['PRIMARY' + key.field] = key

                continue

            r = re.match('^\).*?;$', line, re.IGNORECASE)
            if r:
                table_key = table.lower()

                data[table_key] = {
                    'name': table,
                    'field_sort': field_sort,
                    'fields': fields,
                    'keys': keys,
                    'sql': sql,
                }

                table = ''; fields = {}; field_sort = []; keys = {}; sql = ''; state = 0

                continue

            raise Exception('Unknown SQL syntax: "' + line + '"')

    return data


"""
    Modifique o programa 9.8 para gerar uma lista html, usando os elementos ul e il
"""

# dicionários para organizar os itens
compras = {"Limpesa": ["Sabão em pó",  "Detergente", "Amaciante"],
           "Carnes": ["Frango", "Bisteca", "Fígado"],
           "Bebidas": ["Suco", "Cerveja", "Vinho"]
           }

# Cria a estrutura básica da página web
with open("compras.html", "w", encoding="utf-8") as listacompras:
    listacompras.write
    ("""
    <DOCTYPE html>

            <meta charset = "utf-8">
            <title>Lista de Compras</title>

lista de Compras

    """)

    # for para dicionar os itens percorrendo o dicionário
    for c, v in compras.items():
        listacompras.write(f"
{c}
\n")
        for e in v:
            listacompras.write(f"
 {e}
\n")
    listacompras.write("")


#! /usr/bin/env python
# -*- coding:UTF-8 -*-
# 并发测试客户端

import socket
import threading
import sys

def work(host, port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((host, port))

    sys.stdout.write("%s is running: \n"%threading.currentThread())
    s.send("Hello world!")
    while True:
        data = s.recv(1024)
        if not data:
            break
        sys.stdout.write(data)
    s.close()

if __name__ == '__main__':
    host = '192.168.1.100'
    port = 10000
    threads =  []

    for num in range(100):
        t = threading.Thread(target=work, name="Thead: %d"%num, args=(host, port))
        t.daemon = True
        t.start()
        threads.append(t)

    for thread in threads:
        t.join()


import subprocess
import unittest

IMAGE_NAME = 'python3-docker-unittest:latest'

class PythonDockerImageTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # find Python and Pip version in Dockerfile
        cls._python_version = None
        cls._pip_version = None
        with open('Dockerfile') as docker_file:
            for line in docker_file:
                if line.startswith('ENV PYTHON_VERSION='):
                    cls._python_version = line.split('=')[1].strip()
                elif line.startswith('ENV PYTHON_PIP_VERSION='):
                    cls._pip_version = line.split('=')[1].strip()

    def _run_command_in_image(self, *command, code=None):
        input_ = code.encode('utf-8') if code is not None else None
        docker_command = ('docker', 'run', '--rm', '--interactive', IMAGE_NAME) + command
        process = subprocess.run(
            docker_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=input_)
        return process.stdout.decode('utf-8').strip()

    def _run_python_in_image(self, code):
        input_ = code.encode('utf-8')
        docker_command = ['docker', 'run', '--rm', '--interactive', IMAGE_NAME]
        process = subprocess.run(
            docker_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=input_)
        return process.stdout.decode('utf-8').strip()

    def test_python_version_command_line(self):
        result = self._run_command_in_image('python', '--version')
        self.assertEqual(result, f'Python {self._python_version}')

    def test_python_version_in_python(self):
        result = self._run_python_in_image(
            '''
import sys
print(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')
''')
        self.assertEqual(result, f'{self._python_version}')

    def test_pip_version_command_line(self):
        result = self._run_command_in_image('pip', '--version')
        self.assertTrue(result.startswith(f'pip {self._pip_version}'))

    def test_sqlite(self):
        result = self._run_python_in_image(
            '''
import sqlite3
sqlite3.connect(':memory:')
''')
        self.assertEqual(result, '')

    def test_ssl(self):
        result = self._run_python_in_image(
            '''
import ssl
ciphers = ssl.create_default_context().get_ciphers()
if len(ciphers) > 0:
    print('found ciphers')
else:
    print('no ciphers found')
''')
        self.assertEqual(result, 'found ciphers')

    def test_install_numpy(self):
        result = self._run_command_in_image('pip', 'install', 'numpy')
        self.assertIn('Successfully installed numpy', result)


from django.test import TestCase
from .models import Contact

class ContactTestCase(TestCase):
    fixtures = ["test_committee_accounts", "test_contacts"]

    def setUp(self):
        self.valid_contact = Contact(
            type=Contact.ContactType.INDIVIDUAL,
            last_name="Last",
            first_name="First",
            street_1="Street",
            city="City",
            state="St",
            zip="123456789",
            country="Country",
            committee_account_id="735db943-9446-462a-9be0-c820baadb622",
        )

    def test_get_contact(self):
        contact = Contact.objects.get(last_name="Lastname")
        self.assertEquals(contact.type, Contact.ContactType.INDIVIDUAL)

    def test_save_and_delete(self):
        self.valid_contact.save()
        contact_from_db = Contact.objects.get(last_name="Last")
        self.assertIsInstance(contact_from_db, Contact)
        self.assertEquals(contact_from_db.first_name, "First")
        contact_from_db.delete()
        self.assertRaises(Contact.DoesNotExist, Contact.objects.get, first_name="First")

        soft_deleted_contact = Contact.all_objects.get(last_name="Last")
        self.assertEquals(soft_deleted_contact.first_name, "First")
        self.assertIsNotNone(soft_deleted_contact.deleted)
        soft_deleted_contact.hard_delete()
        self.assertRaises(
            Contact.DoesNotExist, Contact.all_objects.get, last_name="Last"
        )


from osv import fields, osv
from tools.translate import _
import wizard
import pooler
import Image
import time

class wizard_create_locations (osv.osv_memory):

    """create locations"""
    _name = 'wizard.create.locations'
    _description = 'Vehicle location'

    _columns = {
                'company': fields.many2one ('res.company','Company', required=True),
                'tire_stock': fields.many2one ('stock.location','Tire Stock'),
                'retread': fields.many2one ('stock.location','Retread'),
                'scratch': fields.many2one ('stock.location','Scratch'),
                'waste': fields.many2one ('stock.location','Waste'),
                'flatire': fields.many2one ('stock.location','Flat Tire'),
                'schema4' : fields.binary('4 Tire Schema'),
                'schema6' : fields.binary('6 Tire Schema'),
                'schema8' : fields.binary('8 Tire Schema'),
                }

    def onchange_company (self, cr, uid, ids, company_id, context=None):

        pool = pooler.get_pool(cr.dbname)
        company_obj = pool.get('res.company')
        company = company_obj.browse (cr,uid,company_id)
        context = {'company' : company.id}
        values ={}
        if company.tire_stock:
            values['tire_stock'] = company.tire_stock.id
        if company.retread:
            values['retread'] = company.retread.id
        if company.scratch:
            values['scratch'] = company.scratch.id
        if company.waste:
            values['waste'] = company.waste.id
        if company.flatire:
            values['flatire'] = company.flatire.id
        if company.schema4:
            values['schema4'] = company.schema4
        if company.schema6:
            values['schema6'] = company.schema6
        if company.schema8:
            values['schema8'] = company.schema8
        values ['context'] = context
        return {'value' : values}

    def save_config (self,cr,uid,ids,data,context=None):

        values ={}
        pool = pooler.get_pool(cr.dbname)
        company_obj = pool.get('res.company')
        company= self.browse(cr,uid,ids[0]).company
        values ['tire_stock'] = self.browse(cr,uid,ids[0]).tire_stock.id
        values ['retread'] = self.browse(cr,uid,ids[0]).retread.id
        values ['scratch'] = self.browse(cr,uid,ids[0]).scratch.id
        values ['waste'] = self.browse(cr,uid,ids[0]).waste.id
        values ['flatire'] = self.browse(cr,uid,ids[0]).flatire.id

        if self.browse(cr,uid,ids[0]).schema4:
            values ['schema4'] = self.browse(cr,uid,ids[0]).schema4.id
        else:
            values ['schema4'] = ''
        if self.browse(cr,uid,ids[0]).schema6:
            values ['schema6'] = self.browse(cr,uid,ids[0]).schema6.id
        else:
            values ['schema6'] = ''
        if self.browse(cr,uid,ids[0]).schema8:
            values ['schema8'] = self.browse(cr,uid,ids[0]).schema8
        else:
            values ['schema8'] = ''
        company = company_obj.browse(cr,uid,company.id)
        company_obj.write(cr,uid,company.id,values)

        value = {
                 'type': 'ir.actions.close_window',
                }

        return value

    def create_locations(self, cr, uid, data, context):

        res = {}
        pool = pooler.get_pool(cr.dbname)
        company_obj = pool.get('res.company')
        company_list = company_obj.search(cr,uid,[])
        company= company_obj.browse(cr,uid,company_list[0])
        vehicle_obj = pool.get('fleet.vehicles')
        stloc_obj = pool.get('stock.location')
        vehicle_list = vehicle_obj.search(cr, uid, [('buslocat','=', None)])
        for vehicle in vehicle_list:
            vehi = vehicle_obj.browse(cr, uid, vehicle)
            buslo_val={'name': vehi.name,'active':True ,'usage':'internal', 'chained_location_type':'none','chained_auto_packing' :'manual', 'chained_delay':'0'}
            bus_location = stloc_obj.create(cr,uid,buslo_val)
            if vehi.tires:
                if vehi.tires > 6:
                    vehi_vals = {'axles' : '3axle', 'buslocat':bus_location, 'schema':''}
                    if company.schema8 :
                        vehi_vals ['schema'] = company.schema8
                elif vehi.tires ==4:
                    vehi_vals = {'axles' : '2axle', 'buslocat':bus_location, 'schema':''}
                    if company.schema4 :
                        vehi_vals ['schema'] = company.schema4
                else:
                    vehi_vals = {'axles' : '2axle', 'buslocat':bus_location, 'schema':''}
                    if company.schema6 :
                        vehi_vals ['schema'] = company.schema6
                for i in range (1,vehi.tires+1): # middle axle creation and its tires
                    tire_name= vehi.name.strip('bus ') + '-' + str(i)
                    tire = {'name': tire_name,'active':True,'usage':'internal','location_id': bus_location, 'chained_location_type':'none','chained_auto_packing' :'manual', 'chained_delay':'0'}
                    tires = stloc_obj.create(cr,uid,tire)
                vehicle_obj.write(cr,uid,vehi.id,vehi_vals)
        return res

wizard_create_locations()


import socket
s=socket.socket()
s.bind(("localhost",5005))
s.listen(1)
con,adr=s.accept()
print("Connected ... ",str(adr))
print("Sending File ... ")
with open("File1.txt","rb") as f1:
    while True:
        data=f1.read(1024)
        con.send(data)
        if not data:
            break
print("File Send Success")
s.close()


"""
rl.py: Reinforcement learning implementation
       of Hare brain
"""
from __future__ import division
from random import random, randint
from math import hypot, exp, log as logn
from os.path import join as osjoin

from foxgame.controller import Brain
from foxgame.structures import Vector, Direction
from foxgame.options import FoxgameOption, task

from libs.neuralnet.nn import NeuralNetwork, load_network

import logging
log = logging.getLogger(__name__)

try:
    import psyco
    psyco.full()
except ImportError:
    log.debug('Running without psyco.')

def norm_action(a):
    #return (a[0]+1)/2, (a[1]+1)/2
    return a

class HareBrain(Brain):
    net_file = osjoin('foxgame', 'controllers', 'libs', 'rl_Q.db')

    size = (600, 400)

    hiddens = 15

    # discount rate
    gamma = 0.5
    # eligibilty trace decay (lambda)
    trace_decay = 0.8

    # greediness factor (one minus eps)
    greediness = 0.70

    speed_normalizer = 500

    # Rewards
    time_reward = 0.1 # per second
    carrot_reward = 1
    fox_reward = -100

    update_rate = 10

    def get_state(self):
        diagonal = hypot(HareBrain.size[0], HareBrain.size[1])
        return ((self.game.hare.pos.x-self.nearest_fox.pos.x)/diagonal,
                (self.game.hare.pos.y-self.nearest_fox.pos.y)/diagonal,
                (self.game.hare.pos.x-self.game.carrot.pos.x)/diagonal,
                (self.game.hare.pos.y-self.game.carrot.pos.y)/diagonal,
                self.game.hare.pos.x/HareBrain.size[0],
                self.game.hare.pos.y/HareBrain.size[1],
                self.game.hare.speed.x/HareBrain.speed_normalizer,
                self.game.hare.speed.y/HareBrain.speed_normalizer,
                self.nearest_fox.speed.x/HareBrain.speed_normalizer,
                self.nearest_fox.speed.y/HareBrain.speed_normalizer)

    def set_up(self):
        """
        Load neural network data from a file
        """

        self.state = self.get_state()
        self.action = 0, 0

        try:
            # Try loading an existing policy
            self.network = load_network(self.net_file, TDLambda)
        except IOError:
            # Should create a new network
            self.network = self.init_network()

        self.update_actions(self.state)

        self.tick_count = 0
        self.time = 0
        self.carrots = 0
        self.reward = 0

    def update_actions(self, state):
        self.Q = dict(((h, v),
                       self.network.put(state + norm_action((h, v)))[0])
                      for h in (0, -1, 1)
                      for v in (0, -1, 1))
        #print ' '.join('%s %.3f' % x for x in self.Q.items())

    def best_action(self):
        # return action which gives maximum value
        # for current state
        return max(self.Q, key=lambda k:self.Q[k])

    def choose_action(self):
        # eps-greedy policy
        if random() < self.greediness:
            # go greedy
            return self.best_action()
        else:
            return randint(-1, 1), randint(-1, 1)

    def update(self, time):
        self.tick_count += 1

        if self.game.collision:
            # large negative reward if hare got taken
            r = HareBrain.fox_reward
            log.debug('fox caught me')
        elif self.pawn.carrots > self.carrots:
            # large positive reward if got carrot
            num_carrots = (self.pawn.carrots - self.carrots)
            r = num_carrots * HareBrain.carrot_reward
            self.carrots = self.pawn.carrots
            log.debug('I got a carrot')
        else:
            # positive reward if it is still alive
            r = HareBrain.time_reward * time

        self.reward += r

        if self.tick_count % self.update_rate == 0:
        #if True:
            dtime = self.game.time_elapsed - self.time
            self.update_network(dtime)

        return Direction(self.action)

    def update_network(self, time):
        # SARSA-lambda update

        # get previouse state-action
        s = self.state
        a = self.action

        # observe new state
        s1 = self.get_state()
        self.state = s1

        # refresh policy values (Q)
        self.update_actions(s1)

        # choose new action
        a1 = self.choose_action()
        self.action = a1

        alpha = exp(-2*self.game.time_elapsed)
        #print 'alpha:', alpha

        self.network.update(s + norm_action(a),     # Q(s, a)
                            s1 + norm_action(a1),   # Q(s', a')
                            self.reward,            # r
                            time,
                            alpha=alpha)

        self.reward = 0

    def tear_down(self):
        # hackish: update with last frame
        # needed to get negative reward on game end
        self.update(1/60)

        self.network.save(self.net_file)

    @task
    def task_reset():
        HareBrain.init_network()

    @staticmethod
    def init_network():
        log.info('Initializing new neural network')
        network = TDLambda(12, HareBrain.hiddens, funct='sigmoid')
        network.save(HareBrain.net_file)
        return network

class TDLambda(NeuralNetwork):
    """
    NN based  scalar function approximator for
    TD-lambda methods. Refer to Sutton-Barto 8.4.
    """
    def __init__(self, ni, nh, no=1, bias=False, funct='sigmoid',
                   wi=None, wo=None):
        super(TDLambda, self).__init__(ni, nh, 1, False, funct, wi, wo)

        # Eligibility trace (e vector)
        self.trace_wi = [[0]*self.nh for i in range(self.ni)]
        self.trace_wo = [0]*self.nh

    def update(self, inputs0, inputs1, reward, time,
                 gamma=0.1, trace_decay=0.99, alpha=0.01):
        Q_new = self.put(inputs1)[0]
        Q_old = self.put(inputs0)[0]

        self.trace_bp(reward + gamma*Q_new, trace_decay=trace_decay,
                      gamma=gamma, eps=0.1)

        # update weights between input and hidden layer
        for i in range(self.ni):
            for j in range(self.nh):
                self.wi[i][j] += alpha*self.trace_wi[i][j]

        # update weights between input and hidden layer
        for j in range(self.nh):
            self.wo[j][0] += alpha*self.trace_wo[j]

    def trace_bp(self, target, trace_decay=0.1, gamma=0.1, eps=0.5):

        output_deltas = [(target-ao) * self.dfunct(ao)
                         for k, ao in enumerate(self.ao)]

        # Hidden delta
        hidden_deltas = []
        for j in xrange(self.nh):
            hidden_deltas.append(
                            self.dfunct(self.ah[j]) * sum(
                            od*w for od, w in zip(output_deltas, self.wo[j])))

        step = gamma*trace_decay
        # Weights between hidden and output
        for j in range(self.nh):
            self.trace_wo[j] = step*self.trace_wo[j] + \
                                    eps * output_deltas[0] * self.ah[j]

        # Weights between input and hidden
        for i in xrange(self.ni):
            for j in xrange(self.nh):
                self.trace_wi[i][j] = step*self.trace_wi[i][j]  + \
                                         eps * hidden_deltas[j] * self.ai[i]

__extraopts__ = (
                 FoxgameOption('hiddens', type='int'),
                 FoxgameOption('gamma', type='float'),
                 FoxgameOption('trace_decay', type='float'),
                 FoxgameOption('greediness', type='float'),
                 FoxgameOption('time_reward', type='float'),
                 FoxgameOption('fox_reward', type='float'),
                 FoxgameOption('carrot_reward', type='float'),
                 FoxgameOption('update_rate', type='int'),
                 FoxgameOption('net_file', type='string')
                )


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

import random
from django.shortcuts import render
from my_game.models import System, AsteroidField

# функция генерации астероидных полей
def asteroid_generation(request):
    if request.method == "POST" and request.POST.get('add_button') is not None:

        asteroid = int(request.POST.get('asteroid', None))
        for i in range(asteroid):
            #генерация кооржинат поля
            system = System.objects.filter().order_by('x').first()
            x_min = system.x - 10
            system = System.objects.filter().order_by('x').last()
            x_max = system.x + 10
            system = System.objects.filter().order_by('y').first()
            y_min = system.y - 10
            system = System.objects.filter().order_by('y').last()
            y_max = system.y + 10
            x = round(random.uniform(x_min, x_max), 3)
            y = round(random.uniform(y_min, y_max), 3)
            z = round(random.uniform(-30, 30), 3)

            # размер поля
            k = random.random()
            if 0.07 > k:
                size = random.randint(3000000, 5000000)
            else:
                if 0.07 <= k <= 0.2:
                    size = random.randint(1000000, 3000000)
                else:
                    if 0.2 < k < 0.8:
                        size = random.randint(500000, 1000000)
                    else:
                        size = random.randint(100000, 500000)

            #количество артефактов в поле
            k = random.random()
            if 0.02 > k:
                artifact = 5
            elif 0.02 <= k <= 0.1:
                artifact = 4
            elif 0.1 < k <= 0.2:
                artifact = 3
            elif 0.2 < k <= 0.4:
                artifact = 2
            elif 0.4 < k <= 0.7:
                artifact = 1
            else:
                artifact = 0

            # уровень обогащения поля
            k = random.random()
            if 0.05 > k:
                ore = round(random.uniform(0.8, 0.95), 3)
            elif 0.05 <= k <= 0.35:
                ore = round(random.uniform(0.799, 0.8), 3)
            else:
                ore = round(random.uniform(0.6, 0.799), 3)

            mineral_koef = round(random.uniform(0.07, 0.2), 3) * ore
            resource_koef = ore - mineral_koef

            koef_res_1 = round(round(random.uniform(0.2, 0.3), 3) * resource_koef, 3)
            koef_res_2 = round(round(random.uniform(0.2, 0.3), 3) * resource_koef, 3)
            koef_res_3 = round(round(random.uniform(0.2, 0.3), 3) * resource_koef, 3)
            koef_res_4 = round(resource_koef - (koef_res_1 + koef_res_2 + koef_res_3), 3)
            koef_min_1 = round(round(random.uniform(0.2, 0.3), 3) * mineral_koef, 3)
            koef_min_2 = round(round(random.uniform(0.2, 0.3), 3) * mineral_koef, 3)
            koef_min_3 = round(round(random.uniform(0.2, 0.3), 3) * mineral_koef, 3)
            koef_min_4 = round(mineral_koef - (koef_min_1 + koef_min_2 + koef_min_3), 3)

            asteroid_test = AsteroidField.objects.filter(x=x, y=y, z=z).first()

            if asteroid_test:
                size = asteroid_test.size
                koef_res_1 = asteroid_test.koef_res_1
                koef_res_2 = asteroid_test.koef_res_2
                koef_res_3 = asteroid_test.koef_res_3
                koef_res_4 = asteroid_test.koef_res_4
                koef_min_1 = asteroid_test.koef_min_1
                koef_min_2 = asteroid_test.koef_min_2
                koef_min_3 = asteroid_test.koef_min_3
                koef_min_4 = asteroid_test.koef_min_4

                asteroid = AsteroidField(
                    x=x,
                    y=y,
                    z=z,
                    size=size,
                    koef_res_1=koef_res_1,
                    koef_res_2=koef_res_2,
                    koef_res_3=koef_res_3,
                    koef_res_4=koef_res_4,
                    koef_min_1=koef_min_1,
                    koef_min_2=koef_min_2,
                    koef_min_3=koef_min_3,
                    koef_min_4=koef_min_4,
                    artifact=artifact
                )
                asteroid.save()
            else:
                asteroid = AsteroidField(
                    x=x,
                    y=y,
                    z=z,
                    size=size,
                    koef_res_1=koef_res_1,
                    koef_res_2=koef_res_2,
                    koef_res_3=koef_res_3,
                    koef_res_4=koef_res_4,
                    koef_min_1=koef_min_1,
                    koef_min_2=koef_min_2,
                    koef_min_3=koef_min_3,
                    koef_min_4=koef_min_4,
                    artifact=artifact
                )
                asteroid.save()

        message = 'Поля сгенерированы'
        output = {'message': message}

        return render(request, "admin/generation.html", output)


import faultInjectionUtils

#------------------------------------------------------------------------------
# Here is the list of files to be modified by this script, along with
# blocks of new code (first two lines of block are start and end text to
# search for and replace between) for each of the modified files.
fileModificationsDictionary = { \
    'ApexDiagnostic.cpp': [ \
    # # # # # # # # # # # # # # # # # # # # # # # # #
    '''
    // Start Fault Injection Point 7
    // End Fault Injection Point 7
    // Fault Injection Code Start
    DgnList[DGN_TIMER].triggerValueTimeslice = MsToDgnSlices(DGN_FI_ONE_MIN_MS);
    DgnList[DGN_TIMER].stepValueTimeslice = MsToDgnSlices(DGN_FI_ONE_MIN_MS);
    // Fault Injection Code End
    '''
    ]
}

# Call the procedure to modify and build the test firmware code with the
# above modifications.
faultInjectionUtils.FaultInjectionUtils().ModifyAndBuildFaultInjectionFile(fileModificationsDictionary, __file__)