#!/usr/lib/env python
#-*- encoding:utf-8 -*-

# Author: lixingtie
# Email: lixingtie@barfoo.com.cn
# Create Date: 2012-8-15

import sys
import tornado.web
import tornado.ioloop
import framework.mvc.web

from settings import settings
from handlers.account.account import Login

from core.platform.daemon import Daemon

def run():
    _settings = {
            "debug" : settings.DEBUG,
            "static_host": settings.STATIC_HOST,
            "static_port": settings.STATIC_PORT,
            "static_path" : settings.STATIC_PATH,
            "handler_path" : settings.HANDLER_PATH,
            "template_path" : settings.TEMPLATE_PATH,
            "control_path" : settings.CONTROL_PATH,
            "login_url" : settings.LOGIN_URL,
            "cookie_secret" : settings.COOKIE_SECRET,
            "session_lifetime" : settings.SESSION_LIFETIME,
            "compiled_template_cache": False,
            }
    app = framework.mvc.web.Application([
        (r"/(platform/system/[^/]+/static/.*)", tornado.web.StaticFileHandler, dict(path=".")),
	(r"/account/login.html", Login),
    ], **_settings)
    app.listen(settings.PERMISSION_PORT)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":

    if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] == 'run'):
        run();
    else:

        pid_file = sys.argv.pop(1)

        log_file = settings.PERMISSION_LOG or '/tmp/yrdev_permission.log'

        daemon = Daemon(run, pid_file, log_file)
        daemon.action()


from datetime import date, datetime, timedelta
from schedule import send_email
from parse_filings import parse_filings_on_cloud
from parse_settings import parse_settings_on_cloud
from colorama import Fore, Style
import logging
import click
import sys
logger = logging.getLogger()
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.INFO)

# dates should be strings in format (m)m-(d)d-yyyy
def split_into_weeks(start, end):
    start_date = datetime.strptime(start, "%m-%d-%Y").date()
    end_date = datetime.strptime(end, "%m-%d-%Y").date()

    days_in_range = ((end_date - start_date).days) + 1

    if days_in_range > 7:
        first_end_date = start_date + timedelta(days=6)
        first_end_date_str = first_end_date.strftime("%-m-%-d-%Y")
        next_start_date_str = (first_end_date + timedelta(days=1)).strftime("%-m-%-d-%Y")

        return [(start, first_end_date_str)] + split_into_weeks(next_start_date_str, end)

    else:
        return [(start, end)]

# start, end are dates as strings
def try_to_parse(start, end, tries):
    for attempt in range(1, tries + 1):
        try:
            parse_filings_on_cloud(start, end, get_old_active=False)
            parse_settings_on_cloud(start, end)
            logger.info(Fore.GREEN + f"Successfully parsed filings between {start} and {end} on attempt {attempt}.\n" + Style.RESET_ALL)

            return "success"
        except Exception as error:
            if attempt == tries:
                logger.error(f"Error message: {error}")

    message = f"{start}, {end}"
    logger.error(Fore.RED + f"Failed to parse filings and settings between {start} and {end} on all {tries} attempts.\n" + Style.RESET_ALL)
    return message

# gets all filings since a given date but splits it up by week, tells you which weeks failed
# date should be string in format (m)m-(d)d-yyyy
def get_all_filings_settings_since_date(start_date):
    yesterdays_date = (date.today() - timedelta(days=1)).strftime("%-m-%-d-%Y")
    weeks = split_into_weeks(start_date, yesterdays_date)
    logger.info(f"Will get all filings and settings between {start_date} and {yesterdays_date}\n")

    failures = []
    for week_start, week_end in weeks:
        msg = try_to_parse(week_start, week_end, 5)
        if msg != "success":
            failures.append(msg)

    if failures:
        failures_str = "\n".join(failures)
        logger.info("All failures:")
        logger.info(Fore.RED + failures_str + Style.RESET_ALL)
        send_email(failures_str, "Date ranges for which parsing filings and settings failed")
    else:
        logger.info(Fore.GREEN + f"There were no failures when getting all filings between {start_date} and {yesterdays_date} - yay!!" + Style.RESET_ALL)

@click.command()
@click.argument("date", nargs=1)

# date should be in format (m)m-(d)d-yyyy
def get_all_since_date(date):
    get_all_filings_settings_since_date(date)

if __name__ == "__main__":
    get_all_since_date()


import os
import json
import traceback
import paramtools
import pandas as pd
from .helpers import convert_defaults, convert_adj
import inspect
from taxcrunch.cruncher import Cruncher, CruncherParams
from taxcalc import Policy
from IPython.display import HTML

TCPATH = inspect.getfile(Policy)
TCDIR = os.path.dirname(TCPATH)

with open(os.path.join(TCDIR, "policy_current_law.json"), "r") as f:
    pcl = json.loads(f.read())

RES = convert_defaults(pcl)

class TCParams(paramtools.Parameters):
    defaults = RES

def get_inputs(meta_params_dict):
    """
	Return default parameters from Tax-Cruncher
	"""
    params = CruncherParams()
    policy_params = TCParams()

    keep = [
        "mstat",
        "page",
        "sage",
        "depx",
        "dep13",
        "dep17",
        "dep18",
        "pwages",
        "swages",
        "dividends",
        "intrec",
        "stcg",
        "ltcg",
        "otherprop",
        "nonprop",
        "pensions",
        "gssi",
        "ui",
        "proptax",
        "otheritem",
        "childcare",
        "mortgage",
        "mtr_options"
    ]
    full_dict = params.specification(
        meta_data=True, include_empty=True, serializable=True
    )

    params_dict = {var: full_dict[var] for var in keep}

    cruncher_params = params_dict

    pol_params = policy_params.specification(
        meta_data=True, include_empty=True, serializable=True, year=2019
    )

    return {}, {"Tax Information": cruncher_params, "Policy": pol_params}

def validate_inputs(meta_params_dict, adjustment, errors_warnings):
    params = CruncherParams()
    params.adjust(adjustment["Tax Information"], raise_errors=False)
    errors_warnings["Tax Information"]["errors"].update(params.errors)

    pol_params = {}
    # drop checkbox parameters.
    for param, data in list(adjustment["Policy"].items()):
        if not param.endswith("checkbox"):
            pol_params[param] = data

    policy_params = TCParams()
    policy_params.adjust(pol_params, raise_errors=False)
    errors_warnings["Policy"]["errors"].update(policy_params.errors)

    return errors_warnings

def run_model(meta_params_dict, adjustment):
    params = CruncherParams()
    params.adjust(adjustment["Tax Information"], raise_errors=False)
    newvals = params.specification()

    crunch = Cruncher(inputs=newvals, custom_reform=convert_adj(adjustment["Policy"], 2019))

    return comp_output(crunch)

def comp_output(crunch):
    basic = crunch.basic_table()
    detail = crunch.calc_table()

    table_basic = basic.to_html(
        classes="table table-striped table-hover"
    )
    table_detail = detail.to_html(
        classes="table table-striped table-hover"
    )

    comp_dict = {
        "model_version": "0.0.1",
        "renderable": [
            {"media_type": "table", "title": "Basic Liabilities", "data": table_basic},
            {
                "media_type": "table",
                "title": "Calculation of Liabilities",
                "data": table_detail,
            },
        ],
        "downloadable": [],
    }
    return comp_dict


#!/usr/bin/env python

# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Executable for cross-compiling ROS2 packages."""

import argparse
import logging
from string import Template

from cross_compile.sysroot_compiler import DockerConfig
from cross_compile.sysroot_compiler import Platform
from cross_compile.sysroot_compiler import SysrootCompiler

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

_SYSROOT_PATH = """\
The full path to the directory containing 'sysroot'. The 'ros2_ws/src' \
and 'qemu-user-static' directories and the 'Dockerfile_workspace' \
file used to cross-compile the ROS packages should all be in this \
directory. Defaults to the current working directory."""

_USAGE = """
Example usage:

python3 ros2_cross_compile.py /tmp --arch armhf --os debian
python3 ros2_cross_compile.py --sysroot-path /home/user/ \
--arch aarch64 --os ubuntu
python3 ros2_cross_compile.py --sysroot-path /home/user/ \
--sysroot-base-image arm64v8/ubuntu:bionic
"""

CC_COMPLETE_STRING = Template(
    """To setup the cross compilation build environment:
1. Run the command below to setup using sysroot's GLIBC for cross-compilation.
`bash $system_setup_script_path`
2. Run the command below to export the environment variables used by the \
cross-compiled ROS packages.
`source $build_setup_file_path`'
""")

def create_arg_parser():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description='Sysroot creator for cross compilation workflows.',
        epilog=_USAGE,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '-a', '--arch',
        required=True,
        type=str,
        choices=['armhf', 'aarch64'],
        help='Target architecture')
    parser.add_argument(
        '-o', '--os',
        required=True,
        type=str,
        choices=['ubuntu', 'debian'],
        help='Target OS')
    parser.add_argument(
        '-d', '--distro',
        required=False,
        type=str,
        default='dashing',
        choices=['ardent', 'bouncy', 'crystal', 'dashing'],
        help='Target ROS distribution')
    parser.add_argument(
        '-r', '--rmw',
        required=False,
        type=str,
        default='fastrtps',
        choices=['fastrtps', 'opensplice', 'connext'],
        help='Target RMW implementation')
    parser.add_argument(
        '--sysroot-base-image',
        required=False,
        type=str,
        help='Base Docker image to use for building the sysroot. Ex. arm64v8/ubuntu:bionic')
    parser.add_argument(
        '--docker-network-mode',
        required=False,
        type=str,
        default='host',
        help="Docker's network_mode parameter to use for all Docker interactions")
    parser.add_argument(
        '--sysroot-nocache',
        action='store_true',
        required=False,
        help="When set to true, this disables Docker's cache when building "
             'the image for the workspace sysroot')
    parser.add_argument(
        '--ros2-workspace',
        required=False,
        type=str,
        default='ros2_ws',
        help="The location of the ROS2 workspace you'll be cross compiling "
             'against. Usually ros2_ws if you moved it correctly.')
    parser.add_argument(
        '--sysroot-path',
        required=False,
        default=None,
        type=str,
        nargs='?',
        help=_SYSROOT_PATH)
    return parser

def main():
    """Start the cross-compilation workflow."""
    # Configuration
    parser = create_arg_parser()
    args = parser.parse_args()
    platform = Platform(args)
    docker_args = DockerConfig(args)

    # Main pipeline
    sysroot_create = SysrootCompiler(cc_root_dir=args.sysroot_path,
                                     ros_workspace_dir=args.ros2_workspace,
                                     platform=platform,
                                     docker_config=docker_args)
    sysroot_create.execute_cc_pipeline()

    logger.info(CC_COMPLETE_STRING.substitute(
        system_setup_script_path=sysroot_create.get_system_setup_script_path(),
        build_setup_file_path=sysroot_create.get_build_setup_script_path()))

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logger.exception(e)
        exit(1)


# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any
from unittest.mock import patch

import flash
import pandas as pd
import pytest
import torch
from flash.core.data.io.input import DataKeys
from flash.core.utilities.imports import _TOPIC_SERVE_AVAILABLE, _TOPIC_TABULAR_AVAILABLE
from flash.tabular import TabularRegressionData, TabularRegressor
from torch import Tensor

from tests.helpers.task_tester import StaticDataset, TaskTester

class TestTabularRegressor(TaskTester):
    task = TabularRegressor
    task_kwargs = {
        "parameters": {"categorical_fields": list(range(4))},
        "embedding_sizes": [(10, 32) for _ in range(4)],
        "cat_dims": [10 for _ in range(4)],
        "num_features": 8,
        "backbone": "tabnet",
    }
    cli_command = "tabular_regression"
    is_testing = _TOPIC_TABULAR_AVAILABLE
    is_available = _TOPIC_TABULAR_AVAILABLE

    # TODO: Resolve JIT issues
    scriptable = False
    traceable = False

    marks = {
        "test_fit": [
            pytest.mark.parametrize(
                "task_kwargs",
                [
                    {"backbone": "tabnet"},
                    {"backbone": "tabtransformer"},
                    {"backbone": "fttransformer"},
                    {"backbone": "autoint"},
                    {"backbone": "node"},
                    {"backbone": "category_embedding"},
                ],
            )
        ],
        "test_val": [
            pytest.mark.parametrize(
                "task_kwargs",
                [
                    {"backbone": "tabnet"},
                    {"backbone": "tabtransformer"},
                    {"backbone": "fttransformer"},
                    {"backbone": "autoint"},
                    {"backbone": "node"},
                    {"backbone": "category_embedding"},
                ],
            )
        ],
        "test_test": [
            pytest.mark.parametrize(
                "task_kwargs",
                [
                    {"backbone": "tabnet"},
                    {"backbone": "tabtransformer"},
                    {"backbone": "fttransformer"},
                    {"backbone": "autoint"},
                    {"backbone": "node"},
                    {"backbone": "category_embedding"},
                ],
            )
        ],
        "test_cli": [pytest.mark.parametrize("extra_args", ([],))],
    }

    @property
    def example_forward_input(self):
        return {
            "continuous": torch.rand(1, 4),
            "categorical": torch.randint(0, 10, size=(1, 4)),
        }

    def check_forward_output(self, output: Any):
        assert isinstance(output, Tensor)
        assert output.shape == torch.Size([1, 1])

    @property
    def example_train_sample(self):
        return {DataKeys.INPUT: (torch.randint(0, 10, size=(4,)), torch.rand(4)), DataKeys.TARGET: 0.1}

    @property
    def example_val_sample(self):
        return self.example_train_sample

    @property
    def example_test_sample(self):
        return self.example_train_sample

    @pytest.mark.parametrize(
        "backbone", ["tabnet", "tabtransformer", "fttransformer", "autoint", "node", "category_embedding"]
    )
    def test_init_train_no_num(self, backbone, tmpdir):
        no_num_sample = {DataKeys.INPUT: (torch.randint(0, 10, size=(4,)), torch.empty(0)), DataKeys.TARGET: 0.1}
        dataset = StaticDataset(no_num_sample, 4)

        args = self.task_args
        kwargs = dict(**self.task_kwargs)
        kwargs.update(num_features=4)
        model = self.task(*args, **kwargs)

        trainer = flash.Trainer(default_root_dir=tmpdir, fast_dev_run=True)
        trainer.fit(model, model.process_train_dataset(dataset, batch_size=4))

    @pytest.mark.parametrize("backbone", ["tabnet", "tabtransformer", "autoint", "node", "category_embedding"])
    def test_init_train_no_cat(self, backbone, tmpdir):
        no_cat_sample = {DataKeys.INPUT: (torch.empty(0), torch.rand(4)), DataKeys.TARGET: 0.1}
        dataset = StaticDataset(no_cat_sample, 4)

        args = self.task_args
        kwargs = dict(**self.task_kwargs)
        kwargs.update(parameters={"categorical_fields": []}, embedding_sizes=[], cat_dims=[], num_features=4)
        model = self.task(*args, **kwargs)

        trainer = flash.Trainer(default_root_dir=tmpdir, fast_dev_run=True)
        trainer.fit(model, model.process_train_dataset(dataset, batch_size=4))

@pytest.mark.skipif(not _TOPIC_SERVE_AVAILABLE, reason="serve libraries aren't installed.")
@pytest.mark.parametrize(
    "backbone", ["tabnet", "tabtransformer", "fttransformer", "autoint", "node", "category_embedding"]
)
@patch("flash._IS_TESTING", True)
def test_serve(backbone):
    train_data = {"num_col": [1.4, 2.5], "cat_col": ["positive", "negative"], "target": [1, 2]}
    datamodule = TabularRegressionData.from_data_frame(
        "cat_col",
        "num_col",
        "target",
        train_data_frame=pd.DataFrame.from_dict(train_data),
        batch_size=1,
    )
    model = TabularRegressor.from_data(datamodule=datamodule, backbone=backbone)
    model.eval()
    model.serve(parameters=datamodule.parameters)


# uncompyle6 version 3.7.4
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /tmp/pip-install-x0nyl_ya/jinja2/jinja2/defaults.py
# Compiled at: 2019-07-30 18:47:05
# Size of source mod 2**32: 1400 bytes
"""
    jinja2.defaults
    ~~~~~~~~~~~~~~~

    Jinja default filters and tags.

    :copyright: (c) 2017 by the Jinja Team.
    :license: BSD, see LICENSE for more details.
"""
from jinja2._compat import range_type
from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner, Namespace
BLOCK_START_STRING = '{%'
BLOCK_END_STRING = '%}'
VARIABLE_START_STRING = '{{'
VARIABLE_END_STRING = '}}'
COMMENT_START_STRING = '{#'
COMMENT_END_STRING = '#}'
LINE_STATEMENT_PREFIX = None
LINE_COMMENT_PREFIX = None
TRIM_BLOCKS = False
LSTRIP_BLOCKS = False
NEWLINE_SEQUENCE = '\n'
KEEP_TRAILING_NEWLINE = False
from jinja2.filters import FILTERS as DEFAULT_FILTERS
from jinja2.tests import TESTS as DEFAULT_TESTS
DEFAULT_NAMESPACE = {'range':range_type,
 'dict':dict,
 'lipsum':generate_lorem_ipsum,
 'cycler':Cycler,
 'joiner':Joiner,
 'namespace':Namespace}
DEFAULT_POLICIES = {'compiler.ascii_str':True,
 'urlize.rel':'noopener',
 'urlize.target':None,
 'truncate.leeway':5,
 'json.dumps_function':None,
 'json.dumps_kwargs':{'sort_keys': True},
 'ext.i18n.trimmed':False}
__all__ = tuple(x for x in locals().keys() if x.isupper())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 12:03:40 2020

@author: louise
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm

fd = open('writetest.dat', 'rb')
datain=np.fromfile(file=fd, dtype=np.double)
fd.close()

n=int(len(datain)/2)

data=datain.reshape(2,n)

value=[]
wavelength=[]

#for i in range(len(data)):
 #   v=float(data[i][1])
  #  value.append(v)

#for i in range(len(data)):
 #   v=float(data[i][0])
  #  wavelength.append(v)

print(data)


from pathlib import Path
import logging
from build_jamf_core.create_methods_for_get_class import MethodLogic

class CreateClass:
    """
    Create python text files
    """
    lb = "\n"
    class_text = None
    file_name = None

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

    def text_base(self, url_extension):
        self.file_name = url_extension.replace('/', '')
        text = f"from core.get_jamf.get_jamf import GetJamf\n\n\n" \
            f"class {url_extension.replace('/', '').capitalize()}(GetJamf):\n\n" \
            f"    url = '{url_extension}'\n\n"

        return text

    def text_base_with_search_only_url(self, url_extension):
        url = url_extension.split("/")[1]
        self.file_name = url
        text = f"from core.get_jamf.get_jamf import GetJamf\n\n\n" \
            f"class {url.capitalize()}(GetJamf):\n\n" \
            f"    url = '/{url}'\n\n"

        return text

    def create_text_for_attrs(self, func_title, func_params, ext_url, url):
        f_string_handler = 'f"{self.url}'
        text = f'    def by{func_title}(self{func_params}):\n' \
            f'        self.url = {f_string_handler}{ext_url}"\n' \
            f'        return self.get_jamf()\n\n'

        self.class_text += text

    def has_bracket(self, text):
        if "{" in text:
            bracket = True
        else:
            bracket = False

        return bracket

    def bracket_remover(self, text_with_brackets):
        return text_with_brackets.replace("{", "").replace("}", "")

    def write_python_page(self, class_text):
        with open(Path(f"base_core/core/get_jamf/{self.file_name}.py"), "w") as writefile:
            writefile.write(class_text)

    def main(self):
        urls = self.url_index  # set of url exenstions per rest api FEATURE
        url_extension_base = urls[0][0]
        if "{" in url_extension_base:  # if { is in the url_extension_base its a search only url
            self.class_text = self.text_base_with_search_only_url(url_extension=url_extension_base)
        else:
            self.class_text = self.text_base(url_extension=url_extension_base)

        for url_data in urls:
            url = url_data[0]
            rest_type = url_data[1]

            if rest_type == 'get':
                method_logic = MethodLogic(url, rest_type).main()
                if method_logic:
                    self.class_text += method_logic

        self.write_python_page(self.class_text)


import numpy as np
import jakobi, gauss_seidel, relaxation

f = open('data1.txt')
N = int(f.readline())
A_str = f.readline().split(' ')
b_str = f.readline().split(' ')
A_num = [float(x) for x in A_str]
b_num = [float(x) for x in b_str]
A = np.asarray(A_num).reshape(N,N)
b = np.asarray(b_num)

J = jakobi.Jakobi(N, A, b, 'result_j.xlsx')
print(J.solve(err=0.0000001),'\n')

G = gauss_seidel.Gauss_Seidel(N, A, b, 'result_gs.xlsx')
print(G.solve(err=0.0000001),'\n')

R = relaxation.Relaxation(N, A, b, 1, 'result_r_1.xlsx')
print(R.solve(err=0.0000001),'\n')


import  os
from common.read_config import ReadConfig

project_conf_path=os.path.split(os.path.realpath(__file__))[0]+'\\file_path.conf'
project_path=ReadConfig(filepath=project_conf_path).read_config(section='PROJECT_PATH',option='project')

#测试数据文件路径
test_data_path=os.path.join(project_path,'data','data.xlsx')
#token 数据存储文件
token=os.path.join(project_path,'data','user_token.xlsx')

if __name__ == '__main__':

    print(token)


##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Wiki implementation

$Id$
"""
__docformat__ = 'restructuredtext'

from email.MIMEText import MIMEText
from email.Header import Header

from persistent import Persistent

from zope.interface import implements
from zope.event import notify
from zope.schema.vocabulary import getVocabularyRegistry
from zope.annotation.interfaces import IAnnotations
from zope.component.interfaces import ObjectEvent
from zope.filerepresentation.interfaces import IReadFile
from zope.filerepresentation.interfaces import IWriteFile
from zope.filerepresentation.interfaces import IReadDirectory
from zope.filerepresentation.interfaces import IWriteDirectory
from zope.sendmail.interfaces import IMailDelivery

from zope.app import zapi
from zope.app.container.btree import BTreeContainer
from zope.app.container.contained import Contained
from zope.app.container.interfaces import \
     IObjectAddedEvent, IObjectRemovedEvent

from zwiki.interfaces import IWiki, IWikiPage
from zwiki.interfaces import IWikiContained, IWikiPageContained
from zwiki.interfaces import IWikiPageHierarchy, IMailSubscriptions
from zwiki.interfaces import IWikiPageEditEvent
from zwiki.diff import textdiff

HierarchyKey = 'http://www.zope.org/zwiki#1.0/PageHierarchy/parents'
SubscriberKey = 'http://www.zope.org/zwiki#1.0/MailSubscriptions/emails'

class WikiPage(BTreeContainer):
    """A persistent Wiki Page implementation."""

    implements(IWikiPage, IWikiContained)

    def __init__(self, source=u''):
        super(WikiPage, self).__init__()
        self._source = source

    def _getSource(self):
        return self._source

    def _setSource(self, source):
        old_source = self._source
        self._source = source
        notify(WikiPageEditEvent(self, old_source))

    # See zwiki.interfaces.IWikiPage
    source = property(_getSource, _setSource)

    # See zwiki.interfaces.IWikiPage
    type = u'zope.source.rest'

class WikiPageHierarchyAdapter(object):
    __doc__ = IWikiPageHierarchy.__doc__

    implements(IWikiPageHierarchy)
    __used_for__ = IWikiPage

    def __init__(self, context):
        self.context = context
        self._annotations = IAnnotations(context)
        if not self._annotations.get(HierarchyKey):
            self._annotations[HierarchyKey] = ()

    def reparent(self, parents):
        "See zwiki.interfaces.IWikiPageHierarchy"
        self.setParents(parents)

    def setParents(self, parents):
        res = []
        for p in parents:
            if p != zapi.name(self.context):
                #don't store myself as a parent
                res.append(p)
        self._annotations[HierarchyKey] = tuple(res)

    def getParents(self):
        return self._annotations[HierarchyKey]

    parents = property(getParents, setParents)

    def path(self):
        "See zwiki.interfaces.IWikiPageHierarchy"
        if not self.getParents():
            return [self.context]
        wiki = zapi.getParent(self.context)
        name = self.getParents()[0]
        hier = IWikiPageHierarchy(wiki[name])
        return hier.path() + [self.context]

    def findChildren(self, recursive=True):
        "See zwiki.interfaces.IWikiPageHierarchy"
        wiki = zapi.getParent(self.context)
        contextName = zapi.name(self.context)
        children = []
        for pageName in wiki:
            hier = IWikiPageHierarchy(wiki[pageName])
            if contextName in hier.getParents():
                if recursive:
                    subs = hier.findChildren()
                else:
                    subs = ()
                children.append((wiki[pageName], subs))
        return tuple(children)

# Adapters for file-system style access

class Directory(object):
    r"""Adapter to provide a file-system rendition of wiki pages

    Usage:

      >>> page = WikiPage()
      >>> page.source = 'This is the FrontPage.'

      >>> from comment import Comment
      >>> comment = Comment()
      >>> comment.title = u'C1'
      >>> comment.source = u'Comment 1'
      >>> page[u'comment1'] = comment

      >>> dir = Directory(page)
      >>> IReadDirectory.providedBy(dir)
      True
      >>> IWriteDirectory.providedBy(dir)
      True

      >>> dir.keys()
      [u'comment1', u'content.txt']
      >>> len(dir)
      2

      >>> content = dir.get('content.txt')
      >>> content.__class__ == ContentFile
      True
      >>> comment = dir.get('comment1')
      >>> comment.__class__ == Comment
      True

      >>> del dir[u'content.txt']
      >>> dir.keys()
      [u'comment1', u'content.txt']
      >>> del dir[u'comment1']
      >>> dir.keys()
      [u'content.txt']
    """

    content_file = u'content.txt'
    implements(IReadDirectory, IWriteDirectory)
    __used_for__ = IWikiPage

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

    def keys(self):
        return list(self.context.keys()) + [self.content_file]

    def get(self, key, default=None):
        if key == self.content_file:
            return ContentFile(self.context)
        return self.context.get(key, default)

    def __iter__(self):
        return iter(self.keys())

    def __getitem__(self, key):
        v = self.get(key, self)
        if v is self:
            raise KeyError(key)
        return v

    def values(self):
        return map(self.get, self.keys())

    def __len__(self):
        return len(self.context)+1

    def items(self):
        get = self.get
        return [(key, get(key)) for key in self.keys()]

    def __contains__(self, key):
        return self.get(key) is not None

    def __setitem__(self, name, object):
        if name == self.content_file:
            pass
        else:
            self.context.__setitem__(name, object)

    def __delitem__(self, name):
        if name == self.content_file:
            pass
        else:
            self.context.__delitem__(name)

class ContentFile:
    r"""Adapter for letting a Wiki Page look like a regular file.

    Usage:

      >>> page = WikiPage()
      >>> page.source = 'This is the FrontPage.'

      >>> file = ContentFile(page)
      >>> IReadFile.providedBy(file)
      True
      >>> IWriteFile.providedBy(file)
      True

      >>> file.read()
      u'Source Type: zope.source.rest\n\nThis is the FrontPage.'
      >>> file.size()
      53

      >>> file.write('Type: zope.source.stx\n\nThis is the FrontPage 2.')
      >>> file.context.type
      u'zope.source.stx'
      >>> file.context.source
      u'This is the FrontPage 2.'

    Sometimes the user might not have entered a valid type; let's ignore the
    assignment then.

      >>> file.write('Type: zope.source.foo\n\nThis is the FrontPage 3.')
      >>> file.context.type
      u'zope.source.stx'
      >>> file.context.source
      u'This is the FrontPage 3.'

    Or the type was ommitted altogether.

      >>> file.write('This is the FrontPage 4.')
      >>> file.context.type
      u'zope.source.stx'
      >>> file.context.source
      u'This is the FrontPage 4.'
    """

    implements(IReadFile, IWriteFile)
    __used_for__ = IWikiPage

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

    def read(self):
        """See zope.filerepresentation.interfaces.IReadFile"""
        text = u'Source Type: %s\n\n' %self.context.type
        text += self.context.source
        return text

    def size(self):
        """See zope.filerepresentation.interfaces.IReadFile"""
        return len(self.read())

    def write(self, data):
        """See zope.filerepresentation.interfaces.IWriteFile"""
        if data.startswith('Type: '):
            type, data = data.split('\n\n', 1)
            type = type[6:]
            vocab = getVocabularyRegistry().get(self.context, 'SourceTypes')
            if type in [term.value for term in vocab]:
                self.context.type = unicode(type)

        self.context.source = unicode(data)

# An edit event containing the source before the update

class WikiPageEditEvent(ObjectEvent):
    implements(IWikiPageEditEvent)

    oldSource = u''

    def __init__(self, object, old_source):
        super(WikiPageEditEvent, self).__init__(object)
        self.oldSource = old_source

# Component to fullfill mail subscriptions

class MailSubscriptions:
    """An adapter for WikiPages to provide an interface for collecting E-mails
    for sending out change notices."""

    implements(IMailSubscriptions)
    __used_for__ = IWikiPage, IWiki

    def __init__(self, context):
        self.context = context
        self._annotations = IAnnotations(context)
        if not self._annotations.get(SubscriberKey):
            self._annotations[SubscriberKey] = ()

    def getSubscriptions(self):
        "See zwiki.interfaces.IMailSubscriptions"
        return self._annotations[SubscriberKey]

    def addSubscriptions(self, emails):
        "See zwiki.interfaces.IMailSubscriptions"
        subscribers = list(self._annotations[SubscriberKey])
        for email in emails:
            if email not in subscribers:
                subscribers.append(email.strip())
        self._annotations[SubscriberKey] = tuple(subscribers)

    def removeSubscriptions(self, emails):
        "See zwiki.interfaces.IMailSubscriptions"
        subscribers = list(self._annotations[SubscriberKey])
        for email in emails:
            if email in subscribers:
                subscribers.remove(email)
        self._annotations[SubscriberKey] = tuple(subscribers)

class WikiMailer(object):
    """Class to handle all outgoing mail."""

    fromaddr = "wiki@zope3.org"
    encoding = "utf-8"

    def __call__(self, event):
        if IWikiPage.providedBy(event.object):
            if IObjectAddedEvent.providedBy(event):
                self.handleAdded(event.object)

            elif IWikiPageEditEvent.providedBy(event):
                self.handleModified(event)

            elif IObjectRemovedEvent.providedBy(event):
                self.handleRemoved(event.object)

    def handleAdded(self, object):
        subject = 'Added: ' + zapi.name(object)
        emails = self.getAllSubscribers(object)
        body = object.source
        self.mail(emails, subject, body)

    def handleModified(self, event):
        object = event.object
        if zapi.name(object) is not None:
            subject = 'Modified: ' + zapi.name(object)
            emails = self.getAllSubscribers(object)
            body = textdiff(event.oldSource, object.source)
            self.mail(emails, subject, body)

    def handleRemoved(self, object):
        subject = 'Removed: ' + zapi.name(object)
        emails = self.getAllSubscribers(object)
        body = subject
        self.mail(emails, subject, body)

    def getAllSubscribers(self, object):
        """Retrieves all email subscribers by looking into the local Wiki Page
           and into the Wiki for the global subscriptions."""
        emails = tuple(IMailSubscriptions(object).getSubscriptions())
        emails += tuple(IMailSubscriptions(zapi.getParent(object)
                                           ).getSubscriptions())
        return emails

    def mail(self, emails, subject, body):
        """Mail out the Wiki change message."""
        if emails:
            msg = self._getMessage(subject, body)
            mail_delivery = zapi.getUtility(IMailDelivery, 'wiki-delivery')
            mail_delivery.send(self.fromaddr, emails, msg)

    def _getMessage(self, subject, body):
        message = MIMEText(body.encode(self.encoding), "plain", self.encoding)
        message["Subject"] = Header(
            subject.encode(self.encoding), self.encoding)
        message["From"] = self.fromaddr
        message["To"] = self.fromaddr
        return message.as_string()

# Create a global mailer object.
mailer = WikiMailer()


import gym
import pytest

# noinspection PyUnresolvedReferences
import gym_maze
from lcs.agents.acs2 import ACS2, Configuration
from examples.acs2.maze.utils import calculate_performance
from .utils import count_microclassifiers, \
    count_macroclassifiers, \
    count_reliable

class TestMaze:

    @pytest.fixture
    def env(self):
        return gym.make('Woods1-v0')

    def test_should_traverse(self, env):
        # given
        cfg = Configuration(8, 8,
                            epsilon=1.0,
                            do_ga=False,
                            performance_fcn=calculate_performance)
        agent = ACS2(cfg)

        # when
        population, metrics = agent.explore(env, 300)

        # then
        assert 90 < count_macroclassifiers(population) < 200

        assert 100 == self._get_knowledge(metrics)

        assert count_macroclassifiers(population) == count_reliable(population)

        assert count_macroclassifiers(population) \
            == count_microclassifiers(population)

        assert self._get_total_steps(metrics) > 5000

    def test_should_traverse_with_ga(self, env):
        # given
        cfg = Configuration(8, 8,
                            epsilon=1.0,
                            do_ga=True,
                            performance_fcn=calculate_performance)
        agent = ACS2(cfg)

        # when
        population, metrics = agent.explore(env, 300)

        # then
        assert abs(250 - count_macroclassifiers(population)) < 55

        assert 100 == self._get_knowledge(metrics)

        assert count_macroclassifiers(population) \
            > count_reliable(population)

        assert count_macroclassifiers(population) \
            <= count_microclassifiers(population)

        assert self._get_total_steps(metrics) > 5000

    @pytest.mark.skip(reason="implement it")
    def test_should_exploit_maze(self):
        pass

    @staticmethod
    def _get_knowledge(metrics):
        return metrics[-1]['performance']['knowledge']

    @staticmethod
    def _get_total_steps(metrics):
        return metrics[-1]['agent']['total_steps']


from login.models import User
from django.db import models

class Question(models.Model):
	question_text = models.TextField(null = False,max_length= 200)
	code = models.TextField(blank=True)
	image = models.ImageField(blank=True,upload_to='question/image')
		# 难度设定
	hardchoice=(
		("relax",0.5),
		("easy",0.65),
		("difficult",0.80),
		("chanllenge",0.95),
		)
	hardRate=models.CharField(max_length=100,choices=hardchoice,default="relax")

	# 根据难度设定分数
	def calMark(self):
		return ((((self.get_hardRate_display())-0.5)*100//15)+1)*5
	mark = property(calMark)

	Question_Type = (
		('scq','单选题'),
		('mcq','多选题'),
		('fill','填空题'),
		('TorF','判断题'),
		('code','编程题')
		)
	type = models.CharField(max_length=3,choices=Question_Type,default='scq')

	class Meta:
		verbose_name='Questions'
		verbose_name_plural=verbose_name

	def __str__(self):
		return self.question_text[:100]

#multi choice manger
class singleChoiceManager(models.Manager):
	def get_queryset(self):
		return super(singleChoiceManager,self).get_queryset().filter(type='scq')

#proxy single choice Question
class singleQuestion(Question):
	objects = singleChoiceManager()
	class Meta:
		verbose_name = 'SingleQuestions'
		verbose_name_plural = verbose_name
		proxy = True

#choice for single,这里question为选项
# 所有的选项新建了一个类，每个选项从1开始编号，
class singleChoice(models.Model):
	question = models.ForeignKey(singleQuestion, on_delete= models.CASCADE)
	choice_text = models.CharField(max_length=200,null = True,default='')
	ans = (
		('Yes', 'Yes'),
		('No', 'No')
		)
	answer = models.CharField(max_length=3,choices=ans,default='No')
	def __str__(self):
		return self.choice_text

# 用户输入选择模型
class singleStatus(models.Model):
	User = models.ForeignKey(User,on_delete=models.CASCADE)
	question = models.ForeignKey(singleQuestion,on_delete=models.CASCADE)
	#red not answered,yellow ans but flag,ans green
	status = (
			('Red','red'),
			('Yellow','yellow'),
			('Green','green'),
		)
	#Question not answer first so red
	Qstatus = models.CharField(max_length=6,choices=status,default='red')
	selected = models.IntegerField(default=-1)
	#not answered -1,pre 1 or 0 not used in single
	preResult  = models.IntegerField(default=-1)

# 模型管理器，相当于重写或者增加方法
#fill up manager
class FillManager(models.Manager):
	def get_queryset(self):
		return super(FillManager,self).get_queryset().filter(type='fill')

#proxy for fill ups
class FillQuestion(Question):
	objects = FillManager()
	class Meta:
		verbose_name = "Fill Up"
		verbose_name_plural = "Fill Ups"
		proxy = True

#substrings for fill ups
class FillChoice(models.Model):
	question = models.ForeignKey(FillQuestion,on_delete= models.CASCADE)
	choice_text = models.CharField(max_length=200,null = False)

class FillStatus(models.Model):
	User = models.ForeignKey(User,on_delete=models.CASCADE)
	question = models.ForeignKey(FillQuestion,on_delete=models.CASCADE)
	#red not answered,yellow ans but flag,ans green
	status = (
		('Red','red'),
		('Yellow','yellow'),
		('Green','green'),
		)
	#Question not answer first so red
	Qstatus = models.CharField(max_length=6,choices=status,default='red')
	answer = models.CharField(max_length=200,blank=True)
	#not answered -1,pre 1 or 0
	preResult  = models.IntegerField(default=-1)

'''
用户答题记录表

记录用户历史答题情况

answeredHistory
'''
class answeredHistory(models.Model):
	userid = models.CharField(max_length=100)
	questionid = models.CharField(max_length=100)
	answeredMode=models.CharField(max_length=20,null=True)
	answeredRW=models.BooleanField(default=False)
	answerMade=models.CharField(max_length=100)
	answeredDatetime=models.CharField(null=False,max_length=20)

	def __str__(self):
		return (self.userid+self.answeredDatetime)
	class Meta:
		unique_together=(("userid","questionid","answeredDatetime"),)
		verbose_name = "answeredHistory"
		verbose_name_plural = verbose_name

'''
用户、问题、评分
用于构建矩阵，数据来源于answeredHistory以及question、user、
'''
class userQuestionMark(models.Model):
	userid = models.CharField(max_length=100)
	questionid = models.CharField(max_length=100)
	predict_mark=models.FloatField()

	def __str__(self):
		return self.userid
	class Meta:
		unique_together=(("userid","questionid"),)
		verbose_name = "userQuestionMark"
		verbose_name_plural = verbose_name
	primary = ("userid","questionid")


import numpy as np
import theano
import theano.tensor as T

a = T.lscalar('a')
b = T.lscalar('b')
c = T.lscalar('c')
d = T.lscalar('d')

cost = a * b + c

print(a.type)
print(b.type)
print(c.type)
print(cost.type)

f= theano.function (
					inputs=[c],
					outputs=[cost],
					givens= {
							a: 10,
							b: 20
							}
					)

print(f(1))

python/Theano function inputs and givens.py


import copy
import pickle
from population import POPULATION

'''
Instructions:
Implement a genetic algorithm
https://www.reddit.com/r/ludobots/wiki/pyrosim/geneticalgorithm

Blue diamond is the y coordinate
'''

save_best = True
visualize_best = True
num_generations = 200

# Initial population
parents = POPULATION(pop_size=5, blind_mode=True)
parents.create_population()

parents.evaluate()
print('Generation 0...')
parents.print_pop()

for gen in range(num_generations):
    children = POPULATION(pop_size=5, blind_mode=True)
    children.print_pop()
    exit()
#     children = copy.deepcopy(parents)
#     children.mutate()
#     children.evaluate()
#
#     parents.replace(children)
#     print('Generation ', gen+1, '...')
#     parents.print_pop()
#
# fittest_idx = parents.find_fittest()
#
# print('-----------------------------------------')
# print('The best individual found after {} generations is individual {} with a fitness of {}'\
#       .format(num_generations, fittest_idx, parents.p[fittest_idx].fitness))
# print('-----------------------------------------')
#
# if visualize_best:
#     parents.p[fittest_idx].start_evaluation(blind_mode=False)
#     parents.p[fittest_idx].compute_fitness()
#
# if save_best:
#     f = open('robot.p', 'wb')
#     pickle.dump(parents.p[fittest_idx], f)
#     f.close()


# coding=utf-8
import logging

import pilasengine
from user.interface.actor.custom_actor import CustomActor

game_logger = logging.getLogger('game')

class ShowOpponentScene(pilasengine.escenas.Escena):
    def iniciar(self, game):
        self.game = game

        game_logger.info('ShowOpponentScene:: Se muestra al [UserPlayer] la [ShowOpponentScene]')

        fondo = self.pilas.fondos.Fondo()
        fondo.imagen = self.pilas.imagenes.cargar('user/images/background/show_opponent.png')

        player_first = self.game.current_round.computer_player_first
        player_second = self.game.current_round.computer_player_second
        self.computer_first_actor = CustomActor(self.pilas, imagen=player_first.image, escala=0.7, x=-175, y=75)
        self.computer_first_actor_name = CustomActor(self.pilas, imagen=player_first.image_name, escala=1.5, x=-175,
                                                     y=-100)
        self.computer_second_actor = CustomActor(self.pilas, imagen=player_second.image, escala=0.7, x=175, y=75)
        self.computer_second_actor_name = CustomActor(self.pilas, imagen=player_second.image_name, escala=1.5, x=175,
                                                      y=-100)

        if self.game.current_match().computer_participant.player.id == player_first.id:
            self.highlight_opponent(self.computer_first_actor, self.computer_first_actor_name,
                                    self.computer_second_actor, self.computer_second_actor_name,
                                    next_opponent_x=-200)
        else:
            self.highlight_opponent(self.computer_second_actor, self.computer_second_actor_name,
                                    self.computer_first_actor, self.computer_first_actor_name,
                                    next_opponent_x=200)

        self.create_click_to_continue_actor()

        self.pilas.eventos.click_de_mouse.conectar(self.start_match)

    def highlight_opponent(self, next_opponent, next_opponent_name, secondary_opponent, secondary_opponent_name,
                           next_opponent_x):
        secondary_opponent.escala = [0.6], 3
        secondary_opponent_name.escala = [1], 3

        next_opponent.escala = [0.8], 3
        next_opponent_name.y = [-150], 3

        self.create_your_opponent_actor(next_opponent_x)

    def create_click_to_continue_actor(self):
        click_to_continue_actor = self.pilas.actores.Actor(y=-500, imagen="user/images/actor/others/click.png")
        click_to_continue_actor.escala = 3

        click_to_continue_actor.escala = [0.85], 3  # de cuatro a uno en 1.5 segundos
        click_to_continue_actor.y = [-250], 1

    def create_your_opponent_actor(self, x):
        if x > 0:
            image_arrow = 'user/images/actor/others/arrow_left.png'
            arrow_x_bleed = 220
            text_x_bleed = 200
        else:
            image_arrow = 'user/images/actor/others/arrow_right.png'
            arrow_x_bleed = -220
            text_x_bleed = -200
        CustomActor(self.game.pilas, imagen=image_arrow, escala=0.45, x=x + arrow_x_bleed, y=-25)
        your_opponent_actor = CustomActor(self.game.pilas, imagen="user/images/actor/others/your_opponent.png",
                                          escala=1, x=x + text_x_bleed,
                                          y=100)

        your_opponent_actor.escala = [0.85], 0.5  # de cuatro a uno en 1.5 segundos

    def start_match(self, evento):
        self.pilas.escenas.MatchScene(self.game)


from django.shortcuts import render
from django.http import HttpResponse
from . import forms
from . models import picture

def analyze(request, faceid):
    faceidN = faceid + 1
    faceidP = faceid - 1
    template = 'eval/evaluate.html'
    facepic = picture.objects.get(pk=faceid)
    context = {
        'form': forms.testform2,
        'faceid': faceid,
        'facepic': facepic,
        'faceidN': faceidN,
        'faceidP': faceidP,
    }

    if request.method == 'POST':
        form = forms.testform2(request.POST)
        #dataform = forms.data_form(request.POST)
        if form.is_valid():
            inst = form.save(commit=False)
            inst.face = facepic.face.url
            inst.save()
            return HttpResponse('SUCCESS')

    return render(request, template, context)


from django.http import HttpResponse
from django.shortcuts import render

# index , about, contact

def show_index(request):
    lorem ="jdhfkjhsdjkfhjkdhsjkhfjkdshfjksdhsdhghfgsdhgfsdffffffffffffffffffffffffffffffffffffffffffffffffffffweyfgeglwegyfgwelfweygfgewlfeyfefyefefıefegıfeıefııgfıeıfıeffegf"

    names = [
        'ibrahim',
        'umit',
        'guven',
        'suayip',
        'yusuf',
    ]

    return render(
        request,
        'index.html',
        {"title": "Index page",# title dictionaryi üste context olarak tanımlayıp gönderebilirim.
        "url" : "https://google.com.tr" ,
        "names" : names,
        "lorem" : lorem,
        }
    )

def show_about(request):
    return render(
        request,
        'about.html',
        {"title": "About page"}
    )

def show_contact(request):
    return render(
        request,
        'contact.html',
        {"title": "Contact page"}
    )


from google.appengine.ext import db
from handlers.blog import Blog
from dbmodels.user import User

# Handler for /
class BlogFront(Blog):
    # Check login
    def get(self):
        if self.user:
            # add limit 10 to have only the ten last posts
            posts = db.GqlQuery(
                "select * from Post order by created desc limit 10")
            # Alternative to above:posts= Post.all().order('-created')
            # Looks all the post order by creation date and store them in posts
            # Render front.html with the results of all above query (posts)
            self.render('front.html', posts=posts)
        else:
            self.redirect("/login")


# A program to create a line graph to show the profits of a company in various years.

import matplotlib.pyplot as plt
years = [2016, 2017, 2018, 2019, 2020]
profit = [853900, 865500, 876050, 885700, 844500]
plt.plot(years, profit)
plt.title("Year vs Profit in Company")
plt.xlabel("Year")
plt.ylabel("Profit")
plt.show()


"""empty message

Revision ID: 2dcc37ce4718
Revises: 44b2dcbc8add
Create Date: 2018-03-02 13:55:59.796895

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import Text
import app

# revision identifiers, used by Alembic.
revision = '2dcc37ce4718'
down_revision = '44b2dcbc8add'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('authorize_qbo_blueprint_authentication_tokens', sa.Column('qbo_company_id', sa.BigInteger(), nullable=True))
    op.drop_column('authorize_qbo_blueprint_authentication_tokens', 'company_id')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('authorize_qbo_blueprint_authentication_tokens', sa.Column('company_id', sa.BIGINT(), autoincrement=False, nullable=True))
    op.drop_column('authorize_qbo_blueprint_authentication_tokens', 'qbo_company_id')
    # ### end Alembic commands ###


'''
40. 係り受け解析結果の読み込み（形態素）
形態素を表すクラスMorphを実装せよ．このクラスは表層形（surface），基本形（base），
品詞（pos），品詞細分類1（pos1）をメンバ変数に持つこととする．
さらに，CaboChaの解析結果（neko.txt.cabocha）を読み込み，
各文をMorphオブジェクトのリストとして表現し，3文目の形態素列を表示せよ．
'''
import pprint
from itertools import islice
from collections import namedtuple

Morph = namedtuple('Morph', ('surface', 'base', 'pos', 'pos1'))

def cabocha_into_morphs(f_name='neko.txt.cabocha'):
    sentence = []
    with open(f_name) as f:
        for line in map(lambda x: x.rstrip(), f):
            if line == "EOS":
                yield sentence
                sentence = []
            else:
                if line[0] == '*':
                    continue
                surface, details = line.split('\t')
                mecab_keys = ["品詞", "品詞細分類1", "品詞細分類2", "品詞細分類3",
                              "活用型", "活用形", "原形", "読み", "発音"]
                d = dict(zip(mecab_keys, details.split(',')))
                sentence.append(
                    Morph(
                        surface=surface,
                        base=d["原形"],
                        pos=d["品詞"],
                        pos1=d["品詞細分類1"],
                    )
                )

if __name__ == '__main__':
    for morphs in islice(cabocha_into_morphs(), 2, 3):
        pprint.pprint(morphs)

''' NOTE
* mecab と同じ出力フォーマット
    - 表層形\t品詞,品詞細分類1,品詞細分類2,品詞細分類3,活用型,活用形,原形,読み,発音
'''


def pole_trojkata(podstawa, wysokosc):
    # pole to zmienna lokalna - jest tylko w bloku
    # definicji funkcji
    pole = 0.5 * podstawa * wysokosc
    print(pole, "cm2")

pole_trojkata(23, 20)

# zmienna pole istnieje tylko wewnątrz definicji funkcji
print(pole)


import tensorflow as tf
import cv2
import numpy as np

def predict(model,filename):
    img=cv2.imread(filename)
    img_resize=cv2.resize(img,(28,28))
    img_gray = cv2.cvtColor(img_resize,cv2.COLOR_RGB2GRAY)
    img_array=np.array(img_gray)
    for i in range(img_array.shape[0]):
        for j in range(img_array.shape[1]):
            img_array[i][j]=255-img_array[i][j]
    result=img_array.reshape(1,28,28,1)
    return model.predict(result)

if __name__ == "__main__":
    model=tf.keras.models.load_model('result.h5')
    print('This number is {}'.format(predict(model,'test.png').argmax()))


import pytest

# Checking that the test is called via pytest ... and not python ...
from _pytest.assertion.rewrite import AssertionRewritingHook

if not isinstance(__loader__, AssertionRewritingHook):
    print(f"Tests should be called using this expression:\npytest {__file__}\n\n")

def test_task_stdout(capsys):
    """
    Task check
    """
    import task_4_2

    out, err = capsys.readouterr()
    correct_stdout = "AAAA.BBBB.CCCC"
    assert (
        out
    ), "Nothing is printed to stdout. It is necessary not only to get the correct result, but also to print it to the stdout using print"
    assert correct_stdout == out.strip(), "Wrong line is printed to stdout"


'''
Pre-requisites for running this file:
    1. make a folder named uploads in the same dir as this file
'''
import os
from flask import Flask, request, jsonify #jsonify converts a dict into json
from random import randint
from predict import predict_path
import fleep
from datetime import datetime

# Create a directory in a known location to save the correct files into it.
uploads_dir = os.path.join(os.getcwd(), 'uploads')
#if the sent file isn't in the correct format, it will be saved to rubbish folder not uploads, the purpose of this is to
uncorrectFiles_dir = os.path.join(os.getcwd(), 'uncorrectFiles')

def getAudioExtension(audio_path):
    with open(audio_path, "rb") as file:
        info = fleep.get(file.read(128))

    #return info.type #['audio']
    print("Extension: ", end='')
    print(info.extension)
    return info.extension # ['wav']
    #return info.mime #['audio/wav']

def saveRequestFile():

    if len(request.files) == 0 and len(request.form) == 0:
        return "fail message: empty request"
    elif not("baby_cry_record" in request.files):
        return "fail message: baby_cry_record key isn't found in the request files"

    file_sent = request.files['baby_cry_record'] #read sent file
    if file_sent.filename == '':
        return "fail message: no record sent"

    file_sent.save(os.path.join(uploads_dir, str(file_sent.filename))) #save the received file
    if not (os.path.exists(os.path.join(uploads_dir, str(file_sent.filename)))):
        return "fail message: file isn't saved"

    now = datetime.now()
    dt_string = now.strftime("%d-%m-%Y_%H-%M-%S")
    absolute_filename = os.path.join('uploads', file_sent.filename)
    audio_extension = getAudioExtension(absolute_filename)[0]
    file_new_name = dt_string + "__" + str(randint(1000, 9999)) + '.' + audio_extension #make a random file name for the names conflicts

    if (audio_extension != 'wav'):
        new_filename = os.path.join('uncorrectFiles', file_new_name)
        os.rename(absolute_filename, new_filename)
        return "fail message: File Format is not wav, it is: " + audio_extension

    new_filename = os.path.join('uploads', file_new_name)
    os.rename(absolute_filename, new_filename)

    return file_new_name

# Init
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return jsonify({'Connection': 'Succeeded'})
    #return "
Successful Connection
"

@app.route('/predict', methods=['POST'])
def upload():
    print("Request Files: ", end='')
    print(request.files)
    print("Request Form: ", end='')
    print(request.form)

    file_path = saveRequestFile()

    if "fail message: " in file_path:
        return jsonify({'operation': 'FAIL', 'baby_crying_reason': file_path})

    crying_reason = predict_path(os.path.join('uploads', file_path))
    return jsonify({'operation': 'SUCCESS', 'baby_crying_reason': crying_reason})

# Run Server
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)#, use_reloader=False)


class Solution:
    def dominantIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        largest, second = 0, -1
        for i, num in enumerate(nums):
            if i == 0:
                largest = 0
            elif nums[largest] < nums[i]:
                largest, second = i, largest
            elif second == -1 or nums[second] < nums[i]:
                second = i
        if second == -1 or nums[second] * 2 <= nums[largest]: return largest
        return -1


# uncompyle6 version 3.7.4
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/wmpy_util/json_util.py
# Compiled at: 2019-12-18 04:05:51
# Size of source mod 2**32: 2164 bytes
"""
@Author  : WeiWang Zhang
@Time    : 2019-09-19 14:33
@File    : json_util.py
@Desc    : json序列化工具类
"""
import os, json, numpy as np
from wmpy_util.time_util import timer

def json_dump_file(file, data, minify=False):
    prefix, ext = os.path.splitext(file)
    if ext == '':
        ext = '.json'
    file = prefix + ext
    with open(file, 'w', encoding='utf-8') as (f):
        json.dump(data, f, ensure_ascii=False, indent=4)
    if minify:
        file = '%s.min%s' % (prefix, ext)
        with open(file, 'w', encoding='utf-8') as (f):
            json.dump(data, f, ensure_ascii=False)
    return file

def minify_json_file(from_file, to_file):
    """
    压缩某个json文件
    :param from_file:
    :param to_file:
    :return:
    """
    with open(from_file, 'r', encoding='utf-8') as (f):
        datas = json.load(f)
        json_dump_file(to_file, datas, minify=True)

def read_json_file(file_path):
    if not os.path.isfile(file_path):
        raise IOError('File not existed! %s' % file_path)
    result = None
    with open(file_path, 'r', encoding='utf-8') as (f):
        result = json.load(f)
    return result

def json_power_dump(obj):
    """
    处理numpy无法序列化的问题
    :param obj:
    :return:
    """
    return json.dumps(obj, cls=NumpyEncoder, ensure_ascii=False)

def get_dict_type(dict_obj: dict):
    key, value = next(dict_obj.items().__iter__())
    return (type(key), type(value))

class NumpyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            if isinstance(obj, np.core.floating):
                return float(obj)
            else:
                if isinstance(obj, np.core.signedinteger):
                    return int(obj)
                if isinstance(obj, np.core.unsignedinteger):
                    return int(obj)
            return json.JSONEncoder.default(self, obj)

if __name__ == '__main__':
    a = dict((i, 2 * i) for i in range(1000000))
    for i in range(1000000):
        get_dict_type(a)


#!/usr/bin/python3
'''
The only purpose of this program is to allow the management data.json data.
'''
import json
import os
import platform

import psutil
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

from gmailworker import mailfunctions

# We are going to need to get some emails, so we are going to need some gmail api magic.
SCOPES = 'https://mail.google.com/'
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
	flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
	creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))

print('Email Manager\n'
      'TechdudeGames Inc.')
print('Checking to make sure that MailWatcher is currently off.')
for current_pid in psutil.pids():
	try:
		if ('python' in psutil.Process(current_pid).as_dict()['name']) or (
				'MailWatcher' in psutil.Process(current_pid).as_dict()['name']):
			proc = psutil.Process(current_pid)
			proc_data = proc.as_dict()
			if ('MailWatcher' in proc_data['cmdline'][-1]):
				proc.kill()
				print('Found MailWatcher, and killed it.')
	except psutil._exceptions.NoSuchProcess:
		pass

def getmenunumber(minnumber, maxnumber, prompt_text='\nInput:'):
	keeptrying = True
	attempted_input = ''
	while keeptrying:
		attempted_input = input(prompt_text)
		if attempted_input.isnumeric():
			if float(attempted_input) % 1 == 0.0:
				if (int(attempted_input) <= maxnumber) and (int(attempted_input) >= minnumber):
					keeptrying = False
				else:
					print('Invalid input, try again.')
			else:
				print('Invalid input, try again.')
		else:
			print('Invalid input, try again.')
	return int(attempted_input)

def getnewpath():
	invalid_input = True
	while invalid_input:
		new_path = input('New directory path:')
		if os.path.isdir(os.path.join(new_path)):
			return new_path
		else:
			print('Invalid path, please try again \n')

def getnewfile(startdir):
	invalid_input = True
	while invalid_input:
		file_name = input('Script/Executable Path:')
		if os.path.isfile(os.path.join(startdir, file_name)):
			if platform.win32_ver() == ('', '', '', ''):
				file_name = os.path.join('./', file_name)
			else:
				file_name = os.path.join('.\\', file_name)
			return file_name
		else:
			print('''We can't find that file, please try another filename.''')

mainmenu = '''
\n
What would you like to do?
1) Manage Servers
2) Manage Emails
3) Manage Server Background Tasks
4) Quit
'''

servers_submenu = '''
\n
What would you like to do?
1) Display all the current servers
2) Modify a preexisting server
3) Remove a preexisting server
4) Add a new server
5) Go back to the main menu
'''

emails_submenu = '''
What would you like to do?
1) List all the currently accepted senders
2) Add a new email
3) Remove a current email
4) Go back to the main menu
'''

passthroughevents = '''
What would you like to do?
1) List the current background tasks.
2) Modify a preexisting background task.
3) Remove a background task
4) Add a background task
5) Go back to the main menu.
'''

serverdata = None
if not os.path.isfile('data.json'):
	print('You seem to be missing data.json, creating one for you now.')
	serverdata = {'servers': [], 'allowed_emails': [], 'background_tasks' :[]}
	with open('data.json', 'w') as datawrite:
		json.dump(serverdata, datawrite, indent=4)
		datawrite.close()

keepongoing = True
with open('data.json', 'r') as file:
	if not serverdata:
		try:
			serverdata = json.load(file)
			file.close()
		except json.decoder.JSONDecodeError:
			# This only occurs if the json file is broken.
			print('Your data.json file is malformed, correcting it now...')
			serverdata = {'servers': [], 'allowed_emails': [], 'background_tasks' :[]}
			with open('data.json', 'w') as datawrite:
				json.dump(serverdata, datawrite, indent=4)
				datawrite.close()
if type(serverdata) != dict:
	print('Apparently, the data file is valid, however it has the incorrect starting object.')
	print('Fixing it now by overwriting it with the correct format.')
	serverdata = {'servers': [], 'allowed_emails': [], 'background_tasks' :[]}
	with open('data.json', 'w') as datawrite:
		json.dump(serverdata, datawrite, indent=4)
		datawrite.close()

while keepongoing:
	print(mainmenu)
	mainresponse = getmenunumber(1, 4)
	if mainresponse == 1:
		# Doing some
		if 'servers' not in serverdata:
			print('Somehow, someway are you missing the entire servers section. I am writing it to the file now.')
			serverdata['servers'] = []
			with open('data.json', 'w') as datawrite:
				json.dump(serverdata, datawrite, indent=4)
				datawrite.close()
		print(servers_submenu)
		servermain_responce = getmenunumber(1, 5)
		# Display server
		if servermain_responce == 1:
			for tmpserverdic in serverdata['servers']:
				if 'server' in tmpserverdic:
					print('\nServer Name: ', tmpserverdic['server'])
				else:
					print('\nServerName: ', None)
				if 'password' in tmpserverdic:
					print('Password: ', tmpserverdic['password'])
				else:
					print('Password: ', None)
				if 'directory' in tmpserverdic:
					print('Directory: ', tmpserverdic['directory'])
				else:
					print('Directory: ', None)
				if 'command' in tmpserverdic:
					print('Command: ', tmpserverdic['command'])
				else:
					print('Command: ', None)
				if 'port' in tmpserverdic:
					print('Port: ', tmpserverdic['port'])
				else:
					print('Port:', None)
			print('\nPress Enter to continue')
			input()

		# Modifing crap
		elif servermain_responce == 2:
			print('Type the server number you wish to modify.')
			for tmpnameindex in range(serverdata['servers'].__len__()):
				print(tmpnameindex, ': ', serverdata['servers'][tmpnameindex]['server'])
			modifing_server = True
			selectedserverindex = getmenunumber(0, serverdata['servers'].__len__())
			while modifing_server:
				# This is serverdata print statements
				# I use an if statement per to make sure I don't get an error
				print('\nType the number of the attrib you wish to modify and press Enter.')
				if 'server' in serverdata['servers'][selectedserverindex]:
					print('\n0: Server Name: ', serverdata['servers'][selectedserverindex]['server'])
				else:
					print('\n0: ServerName: ', None)
				if 'password' in serverdata['servers'][selectedserverindex]:
					print('1: Password: ', serverdata['servers'][selectedserverindex]['password'])
				else:
					print('1: Password: ', None)
				if 'directory' in serverdata['servers'][selectedserverindex]:
					print('2: Directory: ', serverdata['servers'][selectedserverindex]['directory'])
				else:
					print('2: Directory: ', None)
				if 'command' in serverdata['servers'][selectedserverindex]:
					print('3: Command: ', serverdata['servers'][selectedserverindex]['command'])
				else:
					print('3: Command: ', None)
				if 'port' in serverdata['servers'][selectedserverindex]:
					print('4: Port: ', serverdata['servers'][selectedserverindex]['port'])
				else:
					print('4: Port:', None)
				print('5: Exit modification mode')

				attrib_to_modify = getmenunumber(0, 5)
				if attrib_to_modify == 0:
					serverdata['servers'][selectedserverindex]['server'] = input('New name: ')

				elif attrib_to_modify == 1:
					serverdata['servers'][selectedserverindex]['password'] = input('New password:')
					if serverdata['servers'][selectedserverindex]['password'].__len__() == 0:
						print('Warning, please know that having no password is a BAD IDEA\n'
						      'Press enter to continue')
						input()

				elif attrib_to_modify == 2:
					serverdata['servers'][selectedserverindex]['directory'] = getnewpath()

				elif attrib_to_modify == 3:
					# I am only useing a var for this because this can get really long
					startdir = serverdata['servers'][selectedserverindex]['directory']
					serverdata['servers'][selectedserverindex]['command'] = getnewfile(startdir)

				elif attrib_to_modify == 4:
					new_port = getmenunumber(0, 99999999999, prompt_text='Type new port number:')
					serverdata['servers'][selectedserverindex]['port'] = new_port

				elif attrib_to_modify == 5:
					modifing_server = False

			# Change writing
			print('Write out the changes? (1=Yes 2=No)')
			confirm_serverchange = getmenunumber(1, 2)
			if confirm_serverchange == 1:
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
					datawrite.close()
				print('Changes written. Press Enter')
				input()
			else:
				print('Changes not saved. Press Enter')
				input()

		elif servermain_responce == 3:
			print('Type the server number you wish to remove.')
			for tmpnameindex in range(serverdata['servers'].__len__()):
				print(tmpnameindex, ': ', serverdata['servers'][tmpnameindex]['server'])
			server_index = getmenunumber(0, serverdata['servers'].__len__())
			print('Are you sure you want to remove this email? (1=Yes 2=No)')
			confirm_server_removal = getmenunumber(1, 2)
			if confirm_server_removal == 1:
				serverdata['servers'].remove(serverdata['servers'][server_index])
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
				print('Server Removed. Press Enter')
				input()
			else:
				print('Removal canceled. Press Enter')
				input()

		elif servermain_responce == 4:
			new_server = {}
			new_server['server'] = input('New Server Name: ')
			new_server['password'] = input('Password: ')
			new_server['directory'] = getnewpath()
			new_server['command'] = getnewfile(new_server['directory'])
			new_server['port'] = getmenunumber(0, 99999999999, prompt_text='New port number: ')
			print('\nWrite this new server to the data file? (1=Yes 2=No)')
			confirm_new_server = getmenunumber(1, 2)
			if confirm_new_server == 1:
				serverdata['servers'].append(dict(new_server))
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
					datawrite.close()
			else:
				print('Did not write server to file')

	# Mail management=======================================================================================
	elif mainresponse == 2:
		if 'allowed_emails' not in serverdata:
			print(
				'Somehow, someway are you missing the entire allowed_emails section. I am writing it to the file now.')
			serverdata['allowed_emails'] = []
			with open('data.json', 'w') as datawrite:
				json.dump(serverdata, datawrite, indent=4)
				datawrite.close()
		print(emails_submenu)
		emailsubmenu_input = getmenunumber(1, 4)
		if emailsubmenu_input == 1:
			for tmpemail_index in range(0, serverdata['allowed_emails'].__len__()):
				print(tmpemail_index, ':', serverdata['allowed_emails'][tmpemail_index])
			print('\nPress Enter to continue')
			input()

		elif emailsubmenu_input == 2:
			addingemail = True
			print('Please send an email with the text ADDME to the email address MailWatcher uses.')
			print('Press enter when you have done so.')
			input()
			while addingemail:
				gmaildata = mailfunctions.getlabeledemail(service)
				if gmaildata == None:
					print('We had an error getting the mail, retry? (1=Yes 2=No)')
					continueaddingemail = getmenunumber(1, 2)
					if continueaddingemail == 2:
						addingemail = False
				elif gmaildata['resultSizeEstimate'] == 0:
					print('''We can't find any new emails in your inbox. Continue? (1=Yes 2=No)''')
					print('(Note): 1 will check for the new emails again.')
					continueaddingemail = getmenunumber(1, 2)
					if continueaddingemail == 2:
						addingemail = False
				else:
					worthysenders = []
					for tmpmailobj in gmaildata['messages']:
						if tmpmailobj != None:
							observed_email = mailfunctions.getemaildata(service, tmpmailobj['id'])
							metadata = observed_email['payload']['headers']
							for name_data in metadata:
								if name_data['name'] == 'From':
									if observed_email['snippet'] == 'ADDME':
										worthysenders.append(name_data['value'])
										mailfunctions.deleteemail(service, tmpmailobj['id'])
					if worthysenders.__len__() == 0:
						print('It appears no emails have the ADDME text in them, retry? (1=Yes 2=No)')
						continueaddingemail = getmenunumber(1, 2)
						if continueaddingemail == 2:
							addingemail = False
					else:
						print('Available Emails:')
						for praisedsender in range(0, worthysenders.__len__()):
							print(praisedsender, ':', worthysenders[praisedsender])
						print('\nPick the number corresponding to the email you want to add.')
						mail_seclection = getmenunumber(0, worthysenders.__len__() - 1)
						if worthysenders[mail_seclection] in serverdata['allowed_emails']:
							print('Silly goose, that email is already on the list :)\n')
							print('Do you want to add another email? (1=Yes 2=No)')
							continueaddingemail = getmenunumber(1, 2)
							if continueaddingemail == 2:
								addingemail = False
						else:
							serverdata['allowed_emails'].append(worthysenders[mail_seclection])
							with open('data.json', 'w') as datawrite:
								json.dump(serverdata, datawrite, indent=4)
								datawrite.close()
							print('Email Added')
							print('Do you want to add another email? (1=Yes 2=No)')
							continueaddingemail = getmenunumber(1, 2)
							if continueaddingemail == 2:
								addingemail = False

		elif emailsubmenu_input == 3:
			removing_emails = True
			while removing_emails:
				for tmpemail_index in range(0, serverdata['allowed_emails'].__len__()):
					print(tmpemail_index, ':', serverdata['allowed_emails'][tmpemail_index])
				print('Which email shall I remove')
				remove_email_index = getmenunumber(0, serverdata['allowed_emails'].__len__())
				print('Are you sure you want to remove this email? (1=Yes 2=No)')
				confirmemailremove = getmenunumber(1, 2)
				if confirmemailremove == 1:
					emailtoremove = serverdata['allowed_emails'][remove_email_index]
					while emailtoremove in serverdata['allowed_emails']:
						serverdata['allowed_emails'].remove(emailtoremove)
					with open('data.json', 'w') as datawrite:
						json.dump(serverdata, datawrite, indent=4)
						datawrite.close()
					print('Email Removed')
					print('Do you want to remove another email? (1=Yes 2=No)')
					removingfeedback = getmenunumber(1, 2)
					if removingfeedback == 2:
						removing_emails = False
				else:
					print('Do you want to remove another email? (1=Yes 2=No)')
					removingfeedback = getmenunumber(1, 2)
					if removingfeedback == 2:
						removing_emails = False

	#Background task management===================

	elif mainresponse == 3:
		# Doing some
		if 'background_tasks' not in serverdata:
			print('Somehow, someway are you missing the background_task section. I am writing it to the file now.')
			serverdata['background_tasks'] = []
			with open('data.json', 'w') as datawrite:
				json.dump(serverdata, datawrite, indent=4)
				datawrite.close()
		print(passthroughevents)
		background_mainresponce = getmenunumber(1, 5)
		# Display server
		if background_mainresponce == 1:
			for tmpserverdic in serverdata['background_tasks']:
				if 'server' in tmpserverdic:
					print('\nBackground Task Name: ', tmpserverdic['server'])
				else:
					print('\nBackground Task: ', None)
				if 'password' in tmpserverdic:
					print('Password: ', tmpserverdic['password'])
				else:
					print('Password: ', None)
				if 'directory' in tmpserverdic:
					print('Directory: ', tmpserverdic['directory'])
				else:
					print('Directory: ', None)
				if 'command' in tmpserverdic:
					print('Command: ', tmpserverdic['command'])
				else:
					print('Command: ', None)
				if 'port' in tmpserverdic:
					print('Port: ', tmpserverdic['port'])
				else:
					print('Port:', None)
			print('\nPress Enter to continue')
			input()

		# Modifing crap
		elif background_mainresponce == 2:
			print('Type the server number you wish to modify.')
			for tmpnameindex in range(serverdata['background_tasks'].__len__()):
				print(tmpnameindex, ': ', serverdata['background_tasks'][tmpnameindex]['server'])
			modifing_server = True
			selectedserverindex = getmenunumber(0, serverdata['background_tasks'].__len__())
			while modifing_server:
				# This is serverdata print statements
				# I use an if statement per to make sure I don't get an error
				print('\nType the number of the attrib you wish to modify and press Enter.')
				if 'server' in serverdata['background_tasks'][selectedserverindex]:
					print('\n0: Background Task Name: ', serverdata['background_tasks'][selectedserverindex]['server'])
				else:
					print('\n0: ServerName: ', None)
				if 'password' in serverdata['background_tasks'][selectedserverindex]:
					print('1: Password: ', serverdata['background_tasks'][selectedserverindex]['password'])
				else:
					print('1: Password: ', None)
				if 'directory' in serverdata['background_tasks'][selectedserverindex]:
					print('2: Directory: ', serverdata['background_tasks'][selectedserverindex]['directory'])
				else:
					print('2: Directory: ', None)
				if 'command' in serverdata['background_tasks'][selectedserverindex]:
					print('3: Command: ', serverdata['background_tasks'][selectedserverindex]['command'])
				else:
					print('3: Command: ', None)
				if 'port' in serverdata['background_tasks'][selectedserverindex]:
					print('4: Port: ', serverdata['background_tasks'][selectedserverindex]['port'])
				else:
					print('4: Port:', None)
				print('5: Exit modification mode')

				attrib_to_modify = getmenunumber(0, 5)
				if attrib_to_modify == 0:
					serverdata['background_tasks'][selectedserverindex]['server'] = input('New name: ')

				elif attrib_to_modify == 1:
					serverdata['background_tasks'][selectedserverindex]['password'] = input('New password:')
					if serverdata['background_tasks'][selectedserverindex]['password'].__len__() == 0:
						print('Warning, please know that having no password is a BAD IDEA\n'
							  'Press enter to continue')
						input()

				elif attrib_to_modify == 2:
					serverdata['background_tasks'][selectedserverindex]['directory'] = getnewpath()

				elif attrib_to_modify == 3:
					# I am only useing a var for this because this can get really long
					startdir = serverdata['background_tasks'][selectedserverindex]['directory']
					serverdata['background_tasks'][selectedserverindex]['command'] = getnewfile(startdir)

				elif attrib_to_modify == 4:
					new_port = getmenunumber(0, 99999999999, prompt_text='Type new port number:')
					serverdata['background_tasks'][selectedserverindex]['port'] = new_port

				elif attrib_to_modify == 5:
					modifing_server = False

			# Change writing
			print('Write out the changes? (1=Yes 2=No)')
			confirm_taskchange = getmenunumber(1, 2)
			if confirm_taskchange == 1:
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
					datawrite.close()
				print('Changes written. Press Enter')
				input()
			else:
				print('Changes not saved. Press Enter')
				input()

		elif background_mainresponce == 3:
			print('Type the server number you wish to remove.')
			for tmpnameindex in range(serverdata['background_tasks'].__len__()):
				print(tmpnameindex, ': ', serverdata['background_tasks'][tmpnameindex]['server'])
			background_task_index = getmenunumber(0, serverdata['background_tasks'].__len__())
			print('Are you sure you want to remove this email? (1=Yes 2=No)')
			confirm_server_removal = getmenunumber(1, 2)
			if confirm_server_removal == 1:
				serverdata['background_tasks'].remove(serverdata['background_tasks'][background_task_index])
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
				print('Server Removed. Press Enter')
				input()
			else:
				print('Removal canceled. Press Enter')
				input()

		elif background_mainresponce == 4:
			new_background_job = {}
			new_background_job['server'] = input('Background Task Name: ')
			new_background_job['password'] = input('Password: ')
			new_background_job['directory'] = getnewpath()
			new_background_job['command'] = getnewfile(new_background_job['directory'])
			new_background_job['port'] = getmenunumber(0, 99999999999, prompt_text='New port number: ')
			print('\nWrite this new background task to the data file? (1=Yes 2=No)')
			confirm_new_server = getmenunumber(1, 2)
			if confirm_new_server == 1:
				serverdata['background_tasks'].append(dict(new_background_job))
				with open('data.json', 'w') as datawrite:
					json.dump(serverdata, datawrite, indent=4)
					datawrite.close()
			else:
				print('Did not write server to file')

	elif mainresponse == 4:
		keepongoing = False
#
# Clear crap
# if platform.win32_ver() == ('', '', '', ''):
#	os.system('clear')
# else:
#	os.system('cls')


from flask import render_template, redirect, url_for, g, flash, request
from flask_login import current_user
from . import item
from .. import db
from .forms import additemForm, shoppingcartForm, checkoutForm
from ..search.forms import searchForm
from ..models import  User, Wallet, marketItem, ShoppingCart, Shipping, Orders, Feedback, Feedbackcomments, Customerbought
from sqlalchemy.sql import func
from datetime import datetime
from forex_python.bitcoin import BtcConverter
from ..query import countryList

@item.route('/cart/<username>', methods=['GET', 'POST'])
def shoppingcart(username):

    form = shoppingcartForm()
    #0 = regular car
    #1 = saved for later
    ##CURRENT CART
    cart = db.session.query(ShoppingCart).filter(ShoppingCart.customer==current_user.username,
                                                 ShoppingCart.savedforlater==0).all()

    ##SAVED FOR LATER CART
    cartsaved = db.session.query(ShoppingCart).filter(ShoppingCart.customer == current_user.username,
                                                 ShoppingCart.savedforlater == 1).all()

    ##SUBTOTAL
    subtotal = db.session.query(func.sum(ShoppingCart.price_of_item)).filter\
                                                    (ShoppingCart.customer==current_user.username,
                                                     ShoppingCart.savedforlater==0).all()
    if (subtotal[0][0]) != None:
        sub = float(subtotal[0][0])
        subprice = ("%.2f" % sub)

    else:
        subprice = 0

    ##QUANITY IN CART

    ##QUANITY IN CART saved for later
    totalincart = db.session.query(func.sum(ShoppingCart.quantity_of_item)).filter\
                                                    (ShoppingCart.customer==current_user.username,
                                                     ShoppingCart.savedforlater==0).all()

    tot = ((totalincart[0][0]))
    if tot == None:
        tot = 0

    return render_template('/item/shoppingcart.html', cart=cart, cartsaved=cartsaved,
                           subtotal=subtotal, subprice=subprice, tot=tot, form=form)

@item.route('/deletepicture/<int:id>', methods=['GET', 'POST'])
def deletecartitem(id):
    item =ShoppingCart.query.get(id)

    db.session.delete(item)
    db.session.commit()

    return redirect(url_for('item.shoppingcart', username=current_user.username))

@item.route('/saveforlater/<int:id>', methods=['GET', 'POST'])
def savecartitem(id):
    item =ShoppingCart.query.get(id)

    item.savedforlater=1

    db.session.add(item)
    db.session.commit()

    return redirect(url_for('item.shoppingcart', username=current_user.username))

@item.route('/movefornow/<int:id>', methods=['GET', 'POST'])
def movecartitem(id):
    item =ShoppingCart.query.get(id)

    item.savedforlater=0

    db.session.add(item)
    db.session.commit()

    return redirect(url_for('item.shoppingcart', username=current_user.username))

@item.route('/checkout/<username>', methods=['GET', 'POST'])
def checkout(username):
    b = BtcConverter()
    checkout = checkoutForm()
    User = db.session.query(Shipping).filter_by(username=current_user.username).first()
    cart = db.session.query(ShoppingCart).filter(ShoppingCart.customer==current_user.username,
                                                 ShoppingCart.savedforlater==0).all()
    ##SUBTOTAL
    subtotal = db.session.query(func.sum(ShoppingCart.price_of_item)).filter\
                                                    (ShoppingCart.customer==current_user.username,
                                                     ShoppingCart.savedforlater==0).all()
    if (subtotal[0][0]) != None:
        sub = float(subtotal[0][0])
        subprice = ("%.2f" % sub)
    else:
        subprice = 0
    print(subprice)
    y = float(subprice)
    ##QUANITY IN CART
    pricebtc = b.convert_to_btc(y, 'USD')
    print(pricebtc)
    subbtcprice = ("%.5f" % pricebtc)
    ##TODO insert payment verification here

    if checkout.MakePayment.data:
        ##TODO vendor cant buy there own thing
        print("adding to orders database")
        for k in cart:
            order = Orders(

            vendor = current_user.username,
            title =k.title_of_item,
            price =k.price_of_item,
            new_order =1,
            accepted_order =0,
            waiting_order =0,
            customer =current_user.username,

            age =datetime.now(),
            private_note ='',
            escrow=0,
            disputed_order = 0,
            carrier = 0,
            tracking = '',
            othercarrier = '',
            item_id = k.item_id,
            pic = k.image_of_item,
            request_cancel = 0,
            reason_cancel = 0,
            overallreason = 0,
            request_return = 0,

            )
            db.session.add(order)
            db.session.commit()
            print("Deleting from cart ")
            deletecart = ShoppingCart.query.get(k.id)

            db.session.delete(deletecart)
            db.session.commit()

            print("Order accepted..adding to customerbought ")

            sold = Customerbought(
                vendor=k.vendor,
                vendor_id = k.vendor_id,
                customer=current_user.username,
                title=k.title_of_item,
                price=k.price_of_item,
                price_btc=0,
                order_status=1,
                disputed_order=0,
                age=datetime.now(),
                escrow=0,

                carrier='',
                tracking='',
                othercarrier='',
                item_id=k.item_id,
                pic= k.image_of_item,
                feedback= 0,
                sale_id = order.id,
                request_cancel = 0,
                request_return = 0,

            )

            db.session.add(sold)
            db.session.commit()

        return redirect(url_for('index'))

    return render_template('/item/checkout.html', cart=cart, User = User,
                           subtotal=subtotal, subprice=subprice, checkout=checkout, subbtcprice=subbtcprice)

@item.route('/<int:id>', methods=['GET', 'POST'])
def Itemforsale(id):

    formcart =additemForm(request.form)
    formsearch = searchForm(request.form)
    vendoritem = marketItem.query.get(id)

    wallet = db.session.query(Wallet).filter_by(username=current_user.username).first()
    specific_folder = str(id)
    user = db.session.query(User).filter_by(username=current_user.username).first()
    link = 'listing'
    spacer = '/'
    totalincart = db.session.query(func.sum(ShoppingCart.quantity_of_item)).filter\
                                                    (ShoppingCart.customer==current_user.username,
                                                     ShoppingCart.savedforlater==0).all()
    tot = ((totalincart[0][0]))
    if tot == None:
        tot = 0

    itempicture = (link + spacer + specific_folder + spacer +vendoritem.imageone)

    list = countryList()
    destination1 = vendoritem.destinationcountry
    destination2 = vendoritem.destinationcountrytwo
    destination3 = vendoritem.destinationcountrythree
    destination4 = vendoritem.destinationcountryfour
    destination5 = vendoritem.destinationcountryfive

    fulldestination1 = (list[destination1])
    dest1 = (fulldestination1[1])

    fulldestination2 = (list[destination2])
    dest2 = (fulldestination2[1])

    fulldestination3 = (list[destination3])
    dest3 = (fulldestination3[1])
    fulldestination4 = (list[destination4])
    dest4 = (fulldestination4[1])

    fulldestination5 = (list[destination5])
    dest5 = (fulldestination5[1])

    feedback = db.session.query(Feedback).filter_by(item_id=id).order_by(Feedback.timestamp.desc()).all()
    userfeedback = db.session.query(Feedback).filter_by().order_by(Feedback.timestamp.desc()).all()

    if request.method == 'POST':
        try:
            if formsearch.search.data:
                print("search data")
                function = 'mainSearch'
                searchterm = formsearch.searchString.data
                if request.method == 'POST':
                    formsearch.searchString.default = searchterm
                    print(searchterm)
                    return redirect(url_for('search.searchMaster',
                                            searchterm=searchterm, function=function))
        except Exception as e:
            print(str(e))
        try:
            if formcart.addtocart1.data:
                ##TODO vendor cant buy there own thing
                print("cart data")
                item = ShoppingCart(
                        customer=current_user.username,
                        vendor = vendoritem.username,
                        vendor_id =vendoritem.vendor_id,
                        title_of_item = vendoritem.itemtitle,
                        image_of_item = str(itempicture),
                        price_of_item = vendoritem.startingprice,
                        quantity_of_item = 1,
                        shipping_price_of_item = vendoritem.shippingprice1,
                        username_of_item = vendoritem.username,
                        return_policy = '',
                        savedforlater = 0,
                        item_id = vendoritem.auctionid,

                            )
                db.session.add(item)
                db.session.commit()
                flash("Item Added to Cart")
                return redirect(url_for('item.Itemforsale', id=vendoritem.id))
        except Exception as e:
            print(str(e))

    return render_template('/item/Item.html',  item=vendoritem, wallet=wallet, pic = itempicture,
                           user=user, formcart=formcart,form=formsearch, tot=tot, feedback=feedback,
                           userfeedback=userfeedback, dest1=dest1, dest2=dest2, dest3=dest3, dest4=dest4, dest5=dest5)


import re
from decimal import Decimal

from django.utils.html import format_html
from django.conf import settings
from django.utils.formats import number_format

def get_money(value, use_l10n=True):
    """
    Convert an integer to a string containing commas every three digits.
    For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
    """
    if settings.USE_L10N and use_l10n:
        try:
            if not isinstance(value, (float, Decimal)):
                value = int(value)
        except (TypeError, ValueError):
            return get_money(value, False)
        else:
            return number_format(value, decimal_pos=2, force_grouping=True)
    orig = str(value)
    new = re.sub(r"^(-?\d+)(\d{3})", r'\g<1>,\g<2>', orig)
    if orig == new:
        return new
    else:
        return get_money(new, use_l10n)

def number_to_rome(number):
    """ Convert integer to rome numerals """
    numerals = {
        1: "i", 5: "v", 9: "ix", 10: "x", 40: "xl",
        50: "l", 90: "xc", 100: "c", 400: "cd", 500: "d",
        900: "cm", 1000: "m"
    }
    result = ""
    for value, numeral in sorted(numerals.items(), reverse=True):
        while number >= value:
            result += numeral
            number -= value
    return result

def format_money(number):
    text = '
{}
'
    return format_html(text.format(get_money(number)))

def text_right(text):
    html_text = '
{}
'
    return format_html(html_text.format(text or '-'))

def text_left(text):
    html_text = '
{}
'
    return format_html(html_text.format(text or '-'))

def text_center(text):
    html_text = '
{}
'
    return format_html(html_text.format(text or '-'))

def make_link(url, text):
    html_text = '{}'
    return format_html(html_text.format(url, text))

def number_to_text_id(nilai):
    """
    Konversi bilangan ke kalimat number_to_text_id
    :param nilai: interger
    :return: string
    """
    huruf = ["", "satu", "dua", "tiga", "empat", "lima",
             "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas"]
    nilai = int(nilai)
    if nilai == 0:
        return ""
    elif nilai < 12 and nilai != 0:
        return "" + huruf[nilai]
    elif nilai < 20:
        return number_to_text_id(nilai - 10) + " belas "
    elif nilai < 100:
        return number_to_text_id(nilai / 10) + " puluh " + number_to_text_id(nilai % 10)
    elif nilai < 200:
        return "seratus " + number_to_text_id(nilai - 100)
    elif nilai < 1000:
        return number_to_text_id(nilai / 100) + " ratus " + number_to_text_id(nilai % 100)
    elif nilai < 2000:
        return "seribu " + number_to_text_id(nilai - 1000)
    elif nilai < 1000000:
        return number_to_text_id(nilai / 1000) + " ribu " + number_to_text_id(nilai % 1000)
    elif nilai < 1000000000:
        return number_to_text_id(nilai / 1000000) + " juta " + number_to_text_id(nilai % 1000000)
    elif nilai < 1000000000000:
        return number_to_text_id(nilai / 1000000000) + " milyar " + number_to_text_id(nilai % 1000000000)
    elif nilai < 100000000000000:
        return number_to_text_id(nilai / 1000000000000) + " trilyun " + number_to_text_id(nilai % 1000000000000)
    elif nilai <= 100000000000000:
        return "Maaf Tidak Dapat di Proses Karena Jumlah nilai Terlalu Besar"


from helpers import alphabet_position, rotate_character

def encrypt(text, rot):
    alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    transformed = ''
    transformation = []
    rot = int(rot)
    for charxt in text:
        if charxt not in alphabet:
            transformed = transformed + charxt
            chary = charxt
            transformation.append(chary)
        else:
            rotated_index = alphabet.index(charxt) + rot
            if rotated_index < 26:
                transformed = transformed + alphabet[rotated_index]
                if ord(charxt) < 97:
                    chary = charxt.upper()
                    chary = rotate_character(charxt, rot)
                    transformation.append(chary)
                else:
                    chary = charxt.lower()
                    chary = rotate_character(charxt, rot)
                    transformation.append(chary)
            else:
                transformed = transformed + alphabet[rotated_index % 26]
                if ord(charxt) < 97:
                    chary = charxt.upper()
                    chary = rotate_character(charxt, rot)
                    transformation.append(chary)
                else:
                    chary = charxt.lower()
                    chary = rotate_character(charxt, rot)
                    transformation.append(chary)

    transformation = ''.join(transformation)
    #print(transformation)

    return transformation
#https://docs.python.org/3/reference/compound_stmts.html

def main():
    #from sys import argv
    #print("This is what the user typed on the command line:", argv)
    text = input('Type a message:')
    rot = input('Rotate by: ')
    print(encrypt(text, rot))
    #print(alphabet_position('a'))
    #print(alphabet_position('A'))
    #print(alphabet_position('b'))
    #print(alphabet_position('y'))
    #print(alphabet_position('z'))
    #print(alphabet_position('Z'))
    #print('end of alphabet position test')
    #print(rotate_character('a', 13) + '  -> n')
    #print(rotate_character('a', 14) + '  -> o')
    #print(rotate_character('a', 0) + '  -> a')
    #print(rotate_character('c', 26)+ '  -> c')
    #print(rotate_character('c', 27)+ '  -> d')
    #print(rotate_character('A', 13)+ '  -> N')
    #print(rotate_character('z', 1)+ '   -> a')
    #print(rotate_character('Z', 2)+ '   -> B')
    #print(rotate_character('z', 37)+ '  -> k')
    #print(rotate_character('!', 37)+ '  -> !')
    #print(rotate_character('6', 13)+ '  -> 6')
    #print('end of rotate character test')
    #print("Hello no comma")
    #print(encrypt('Hello', 5))
    #print("Hello with comma no space")
    #print(encrypt('Hello,', 5))
    #print("Hello with comma and with space")
    #print(encrypt('Hello, ', 5))
    #print(encrypt('World', 5))
    #print("Should print out full encrypted Hello, World")
    #print(encrypt('a', 13))
    #print(encrypt('abcd', 13))
    #print(encrypt('LaunchCode', 13))
    #print(encrypt('LaunchCode', 1))
    #print(encrypt('Hello, World!', 5))

if __name__ == "__main__":
    main()