# Pulls noun phrases, selects answer among those, reconstructs in original context
from random import sample
from functools import reduce
import os
from nltk.parse.corenlp import CoreNLPServer, CoreNLPParser
from requests.exceptions import HTTPError
import itertools
import requests
from qanet_integration import getAnswer, setupQANet

# import tensorflow as tf
# from tensorflow import keras
# import numpy as np
# import matplotlib.pyplot as plt

config = {
    'isManagingServer': False,
    'debugSentenceElimination': False,
    'coreNLPServerURL': 'http://localhost:9000'
}
parser = CoreNLPParser(url=config['coreNLPServerURL'])
server = None
STANFORD = os.path.join("models", "stanford-corenlp-full-2018-10-05")
contextCache = {}

def setup(manageServerInternally=False):
    global server

    config['isManagingServer'] = manageServerInternally

    if manageServerInternally:
        print("Starting CoreNLP server...")

        server = CoreNLPServer(
            os.path.join(STANFORD, "stanford-corenlp-3.9.2.jar"),
            os.path.join(STANFORD, "stanford-corenlp-3.9.2-models.jar"),
        )
        server.start()
    else:
        try:
            print("Checking connection to CoreNLP server...")

            requests.get(f'{config["coreNLPServerURL"]}/live')
        except BaseException:
            print("Error connecting to CoreNLP instance! Make sure the server is running in the background.")
            print("The relevant command can be found in the README.")

            exit(1)

    setupQANet()

def accumulateLongestSequence(acc, token):
    if type(acc) == dict:
        sequenceOne = accumulateLongestSequence(None, acc)

        return accumulateLongestSequence(sequenceOne, token)

    if acc is None:
        return [[token]]

    lastSequence = acc[-1]
    lastTokenInSequence = lastSequence[-1]

    if lastTokenInSequence['index'] + 1 == token['index']:
        acc[-1].append(token)
    else:
        acc.append([token])

    return acc

def accumulateString(acc, token):
    if type(acc) == dict:
        sequenceOne = accumulateString("", acc)

        return accumulateString(sequenceOne, token)

    before, after, text = token['before'], token['after'], token['originalText']

    if acc is None:
        acc = ""

    if acc[-len(before):] != before:
        acc += before

    acc += text
    acc += after

    return acc

def extractor(context, contextPOS, contextTokens, contextNamedEntities, contextInformationExtraction,
              questionText, questionPOS, questionTokens, questionNamedEntities, questionInformationExtraction,
              realAnswers = None):
    i = -1
    answers = []
    knowledgeBase = {}
    nextGlobalStats = {
        'numImpossible': 0,
        'numPossible': 0,
        'numPossibleWithRelevantSentences': 0,
        'numIntentionallyImpossible': 0,
    }
    allPotentialSubjects = []
    potentialNPSubjects = []
    relevantSentences = []

    print("ANALYSIS OF QUESTION:")
    questionPOS.pretty_print()

    print("QUESTION NAMED ENTITIES:")
    print(questionNamedEntities)

    print("QUESTION INFORMATION EXTRACTION:")
    print(questionInformationExtraction)

    if len(questionNamedEntities) > 0:
        allPotentialSubjects += list(map(lambda x: x['text'], questionNamedEntities))

    if len(questionInformationExtraction) > 0:
        allPotentialSubjects += list(map(lambda x: x['subject'], questionInformationExtraction))

    for t in questionPOS.subtrees(lambda t: t.label() == 'NP'):
        potentialNPSubjects.append(t)

    for subject in potentialNPSubjects:
        startingTokenTree = list(filter(lambda token: next(subject.subtrees(lambda t:
                                                                            t.label() == token['pos'] and token[
                                                                                'originalText'] in list(
                                                                                t.leaves())), False),
                                        questionTokens))
        sequences = reduce(accumulateLongestSequence, startingTokenTree, None)

        if sequences:
            longestSequence = reduce(lambda acc, seq: seq if len(seq) > len(acc) else acc, sequences)
            longestSequenceAsTokens = reduce(accumulateString, longestSequence, "").strip()
            allPotentialSubjects += [longestSequenceAsTokens]

    allPotentialSubjects = list(set(allPotentialSubjects))
    allPotentialSubjects.sort(key=len, reverse=True)

    print("ALL POTENTIAL SUBJECTS:")
    print(allPotentialSubjects)

    for sent in contextPOS:
        i += 1
        potentialAnswers = []
        sentTokens = contextTokens[i]
        sentInformation = contextInformationExtraction[i]
        sentNamedEntities = contextNamedEntities[i]
        fullContext = reduce(accumulateString, sentTokens, "").strip()

        for item in sentInformation:
            object = item['object']
            subject = item['subject']

            if subject in allPotentialSubjects or object in allPotentialSubjects:
                if fullContext not in relevantSentences:
                    relevantSentences.append(fullContext)

            if object in knowledgeBase:
                knowledgeBase[object].append(item)
            else:
                knowledgeBase[object] = [item]

        for item in sentNamedEntities:
            text = item['text']

            if text in allPotentialSubjects:
                if fullContext not in relevantSentences:
                    relevantSentences.append(fullContext)

        # sent.pretty_print()

        for t in sent.subtrees(lambda t: t.label() == 'NP'):
            potentialAnswers.append(t)
        #            print(t.leaves())

        for answer in potentialAnswers:
            startingTokenTree = list(filter(lambda token: next(answer.subtrees(lambda t:
                                                                               t.label() == token['pos'] and token[
                                                                                'originalText'] in list(t.leaves())),
                                                               False), sentTokens))
            sequences = reduce(accumulateLongestSequence, startingTokenTree, None)
            longestSequenceAsTokens = None

            if sequences:
                longestSequence = reduce(lambda acc, seq: seq if len(seq) > len(acc) else acc, sequences)
                longestSequenceAsTokens = reduce(accumulateString, longestSequence, "").strip()

            try:
                if not longestSequenceAsTokens:
                    raise AssertionError("No noun phrases in sentence, eliminating:")

                if not any(entity.lower() in fullContext.lower() for entity in allPotentialSubjects):
                    raise AssertionError("No named entity found in sentence, eliminating:")

                index = context.index(longestSequenceAsTokens)
                answers.append((index, longestSequenceAsTokens))

                if fullContext not in relevantSentences:
                    relevantSentences.append(fullContext)
            except AssertionError as e:
                if config['debugSentenceElimination']:
                    print(e.args[0])
                    print(fullContext)

                break
            except ValueError:
                print("***")
                if longestSequenceAsTokens:
                    print(longestSequenceAsTokens.strip())

                print(context)
                print("couldn't reconstruct original phrase :(")

    print("RELEVANT CONTEXT JUDGMENT:")
    if len(relevantSentences) == 0:
        print("No relevant sentences.")
    else:
        print(
            f"{len(relevantSentences)}/{len(contextPOS)} relevant sentences. The following will be passed as context:")
        print(*relevantSentences)

    flatKnowledgeBase = list(itertools.chain.from_iterable(knowledgeBase.values()))
    simpleFlatKnowledgeBase = list(map(lambda x: (x['subject'].lower(), x['relation'].lower(), x['object'].lower()),
                                       flatKnowledgeBase))
    hasAnswerInKnowledgeBase = any((entity.lower() in x for x in simpleFlatKnowledgeBase)
                                   for entity in allPotentialSubjects)
    answers = list(set(answers))
    answers = list(filter(lambda x: x[1].lower() not in list(map(lambda y: y.lower(), allPotentialSubjects)), answers))

    print("FEASIBILITY ANALYSIS:")
    if realAnswers is not None:
        if len(realAnswers) > 0:
            if any(realAnswer.lower() in map(lambda x: x[1].lower(), answers) for realAnswer in realAnswers):
                print("Real answer in answers db.")

                nextGlobalStats['numPossible'] += 1
            elif any((realAnswer.lower() in x.lower() for x in relevantSentences) for realAnswer in realAnswers):
                print("Possible with relevant sentence.")

                nextGlobalStats['numPossibleWithRelevantSentences'] += 1
            else:
                print("Question not answerable with current strategies.")

                nextGlobalStats['numImpossible'] += 1
        else:
            nextGlobalStats['numIntentionallyImpossible'] += 1

    if not hasAnswerInKnowledgeBase:
        print("No subjects found in knowledge base.")

        return True, 0, 0, nextGlobalStats

    if len(relevantSentences) == 0:
        print("No relevant context found.")

        return True, 0, 0, nextGlobalStats

    if len(answers) == 0:
        print("No answers found.")

        return True, 0, 0, nextGlobalStats
    else:
        networkAnswer = getAnswer(context, questionText)
        print("NETWORK ANSWERED:")
        print(networkAnswer)
        try:
            index = context.index(networkAnswer)
        except ValueError:
            print("Failed to reconstruct based on faulty tokenization...")
            # todo: don't pick random answer lol
            finalAnswer = sample(answers, 1)[0]

            return False, finalAnswer[0], len(finalAnswer[1]) + finalAnswer[0], nextGlobalStats

        return False, index, len(networkAnswer) + index, nextGlobalStats

# (impossible (bool), starting index, ending index)
# answer can be provided for obtaining stats about
def eval(context, question, answers = None):
    questionPOS, questionTokens, questionNamedEntities, questionInformationExtraction = None, None, None, None

    # todo: dependency tree stuff
    print("Requesting parse information from CoreNLP server...")
    questionParsed = parser.api_call(question, properties={
        'outputFormat': 'json',
        'annotators': 'tokenize,parse,ner,natlog,openie',
        'tokenizer.options': 'ptb3Escaping=false'
    })

    # todo: dump stale items from cache
    if context in contextCache:
        contextParsed = contextCache[context]
    else:
        try:
            contextParsed = parser.api_call(context, properties={
                'outputFormat': 'json',
                'annotators': 'tokenize,parse,ner,natlog,openie',
                'tokenizer.options': 'ptb3Escaping=false'
            })
            contextCache[context] = contextParsed
        except HTTPError:
            print("CoreNLP parse failed, retrying...")

            return eval(context, question)

    for parsed_sent in questionParsed['sentences']:
        questionPOS = parser.make_tree(parsed_sent)
        questionTokens = parsed_sent['tokens']
        questionNamedEntities = parsed_sent['entitymentions']
        questionInformationExtraction = parsed_sent['openie']

    contextResponse = list(map(lambda parsed_sent: (parser.make_tree(parsed_sent),
                                                    parsed_sent['tokens'],
                                                    parsed_sent['entitymentions'],
                                                    parsed_sent['openie']), contextParsed['sentences']))
    contextPOS, contextTokens, contextNamedEntities, contextInformationExtraction = \
        list(map(lambda x: x[0], contextResponse)), list(map(lambda x: x[1], contextResponse)), \
        list(map(lambda x: x[2], contextResponse)), list(map(lambda x: x[3], contextResponse))

    return extractor(context, contextPOS, contextTokens, contextNamedEntities, contextInformationExtraction,
                     question, questionPOS, questionTokens, questionNamedEntities, questionInformationExtraction,
                     answers)

# Teardown code:
def stop():
    if config['isManagingServer']:
        server.stop()


from rest_framework import serializers

from goods.models import SKU

class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品ID", min_value=1, required=True)
    count = serializers.IntegerField(label="购买数量", min_value=1)
    selected = serializers.BooleanField(label="时候勾选", default=True)

    def validate(self, attrs):
        """校验商品存不存在"""
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return attrs

class SKUCartSerializer(serializers.ModelSerializer):
    """购物车查询序列化器"""

    count = serializers.IntegerField(label='购买数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')

class CartDeletedSerializer(serializers.Serializer):
    """购物车删除序列化器"""
    sku_id = serializers.IntegerField(label="商品ID", min_value=1, required=True)

    def validate(self, attrs):
        """校验商品存不存在"""
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return attrs


#!/usr/bin/env python

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

"""Utility functions for mozrunner"""

import os
import sys

import mozinfo

__all__ = ["findInPath", "get_metadata_from_egg"]

# python package method metadata by introspection
try:
    import pkg_resources

    def get_metadata_from_egg(module):
        ret = {}
        try:
            dist = pkg_resources.get_distribution(module)
        except pkg_resources.DistributionNotFound:
            return {}
        if dist.has_metadata("PKG-INFO"):
            key = None
            value = ""
            for line in dist.get_metadata("PKG-INFO").splitlines():
                # see http://www.python.org/dev/peps/pep-0314/
                if key == "Description":
                    # descriptions can be long
                    if not line or line[0].isspace():
                        value += "\n" + line
                        continue
                    else:
                        key = key.strip()
                        value = value.strip()
                        ret[key] = value

                key, value = line.split(":", 1)
                key = key.strip()
                value = value.strip()
                ret[key] = value
        if dist.has_metadata("requires.txt"):
            ret["Dependencies"] = "\n" + dist.get_metadata("requires.txt")
        return ret

except ImportError:
    # package resources not avaialable
    def get_metadata_from_egg(module):
        return {}

def findInPath(fileName, path=os.environ["PATH"]):
    """python equivalent of which; should really be in the stdlib"""
    dirs = path.split(os.pathsep)
    for dir in dirs:
        if os.path.isfile(os.path.join(dir, fileName)):
            return os.path.join(dir, fileName)
        if mozinfo.isWin:
            if os.path.isfile(os.path.join(dir, fileName + ".exe")):
                return os.path.join(dir, fileName + ".exe")

if __name__ == "__main__":
    for i in sys.argv[1:]:
        print(findInPath(i))

def _find_marionette_in_args(*args, **kwargs):
    try:
        m = [a for a in args + tuple(kwargs.values()) if hasattr(a, "session")][0]
    except IndexError:
        print("Can only apply decorator to function using a marionette object")
        raise
    return m

def _raw_log():
    import logging

    return logging.getLogger(__name__)

def test_environment(
    xrePath, env=None, crashreporter=True, debugger=False, useLSan=False, log=None
):
    """
    populate OS environment variables for mochitest and reftests.

    Originally comes from automationutils.py. Don't use that for new code.
    """

    env = os.environ.copy() if env is None else env
    log = log or _raw_log()

    assert os.path.isabs(xrePath)

    if mozinfo.isMac:
        ldLibraryPath = os.path.join(os.path.dirname(xrePath), "MacOS")
    else:
        ldLibraryPath = xrePath

    envVar = None
    if mozinfo.isUnix:
        envVar = "LD_LIBRARY_PATH"
    elif mozinfo.isMac:
        envVar = "DYLD_LIBRARY_PATH"
    elif mozinfo.isWin:
        envVar = "PATH"
    if envVar:
        envValue = (
            (env.get(envVar), str(ldLibraryPath))
            if mozinfo.isWin
            else (ldLibraryPath, env.get(envVar))
        )
        env[envVar] = os.path.pathsep.join([path for path in envValue if path])

    # crashreporter
    env["GNOME_DISABLE_CRASH_DIALOG"] = "1"
    env["XRE_NO_WINDOWS_CRASH_DIALOG"] = "1"

    if crashreporter and not debugger:
        env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
        env["MOZ_CRASHREPORTER"] = "1"
        env["MOZ_CRASHREPORTER_SHUTDOWN"] = "1"
    else:
        env["MOZ_CRASHREPORTER_DISABLE"] = "1"

    # Crash on non-local network connections by default.
    # MOZ_DISABLE_NONLOCAL_CONNECTIONS can be set to "0" to temporarily
    # enable non-local connections for the purposes of local testing.  Don't
    # override the user's choice here.  See bug 1049688.
    env.setdefault("MOZ_DISABLE_NONLOCAL_CONNECTIONS", "1")

    # Set WebRTC logging in case it is not set yet
    env.setdefault("MOZ_LOG", "signaling:3,mtransport:4,DataChannel:4,jsep:4")
    env.setdefault("R_LOG_LEVEL", "6")
    env.setdefault("R_LOG_DESTINATION", "stderr")
    env.setdefault("R_LOG_VERBOSE", "1")

    # Ask NSS to use lower-security password encryption. See Bug 1594559
    env.setdefault("NSS_MAX_MP_PBE_ITERATION_COUNT", "10")

    # ASan specific environment stuff
    if "ASAN_SYMBOLIZER_PATH" in env and os.path.isfile(env["ASAN_SYMBOLIZER_PATH"]):
        llvmsym = env["ASAN_SYMBOLIZER_PATH"]
    else:
        if mozinfo.isMac:
            llvmSymbolizerDir = ldLibraryPath
        else:
            llvmSymbolizerDir = xrePath
        llvmsym = os.path.join(
            llvmSymbolizerDir, "llvm-symbolizer" + mozinfo.info["bin_suffix"]
        )
    asan = bool(mozinfo.info.get("asan"))
    if asan:
        try:
            # Symbolizer support
            if os.path.isfile(llvmsym):
                env["ASAN_SYMBOLIZER_PATH"] = llvmsym
                log.info("INFO | runtests.py | ASan using symbolizer at %s" % llvmsym)
            else:
                log.error(
                    "TEST-UNEXPECTED-FAIL | runtests.py | Failed to find"
                    " ASan symbolizer at %s" % llvmsym
                )

            # Returns total system memory in kilobytes.
            if mozinfo.isWin:
                # pylint --py3k W1619
                totalMemory = (
                    int(
                        os.popen(
                            "wmic computersystem get TotalPhysicalMemory"
                        ).readlines()[1]
                    )
                    / 1024
                )
            elif mozinfo.isMac:
                # pylint --py3k W1619
                totalMemory = (
                    int(os.popen("sysctl hw.memsize").readlines()[0].split()[1]) / 1024
                )
            else:
                totalMemory = int(os.popen("free").readlines()[1].split()[1])

            # Only 4 GB RAM or less available? Use custom ASan options to reduce
            # the amount of resources required to do the tests. Standard options
            # will otherwise lead to OOM conditions on the current test machines.
            message = "INFO | runtests.py | ASan running in %s configuration"
            asanOptions = []
            if totalMemory <= 1024 * 1024 * 4:
                message = message % "low-memory"
                asanOptions = ["quarantine_size=50331648", "malloc_context_size=5"]
            else:
                message = message % "default memory"

            if useLSan:
                log.info("LSan enabled.")
                asanOptions.append("detect_leaks=1")
                lsanOptions = ["exitcode=0"]
                # Uncomment out the next line to report the addresses of leaked objects.
                # lsanOptions.append("report_objects=1")
                env["LSAN_OPTIONS"] = ":".join(lsanOptions)

            if len(asanOptions):
                env["ASAN_OPTIONS"] = ":".join(asanOptions)

        except OSError as err:
            log.info(
                "Failed determine available memory, disabling ASan"
                " low-memory configuration: %s" % err.strerror
            )
        except Exception:
            log.info(
                "Failed determine available memory, disabling ASan"
                " low-memory configuration"
            )
        else:
            log.info(message)

    tsan = bool(mozinfo.info.get("tsan"))
    if tsan and mozinfo.isLinux:
        # Symbolizer support.
        if os.path.isfile(llvmsym):
            env["TSAN_OPTIONS"] = "external_symbolizer_path=%s" % llvmsym
            log.info("INFO | runtests.py | TSan using symbolizer at %s" % llvmsym)
        else:
            log.error(
                "TEST-UNEXPECTED-FAIL | runtests.py | Failed to find TSan"
                " symbolizer at %s" % llvmsym
            )

    ubsan = bool(mozinfo.info.get("ubsan"))
    if ubsan and (mozinfo.isLinux or mozinfo.isMac):
        log.info("UBSan enabled.")

    return env

def get_stack_fixer_function(utilityPath, symbolsPath, hideErrors=False):
    """
    Return a stack fixing function, if possible, to use on output lines.

    A stack fixing function checks if a line conforms to the output from
    MozFormatCodeAddressDetails.  If the line does not, the line is returned
    unchanged.  If the line does, an attempt is made to convert the
    file+offset into something human-readable (e.g. a function name).
    """
    if not mozinfo.info.get("debug"):
        return None

    if os.getenv("MOZ_DISABLE_STACK_FIX", 0):
        print(
            "WARNING: No stack-fixing will occur because MOZ_DISABLE_STACK_FIX is set"
        )
        return None

    def import_stack_fixer_module(module_name):
        sys.path.insert(0, utilityPath)
        module = __import__(module_name, globals(), locals(), [])
        sys.path.pop(0)
        return module

    if symbolsPath and os.path.exists(symbolsPath):
        # Run each line through fix_stacks.py, using breakpad symbol files.
        # This method is preferred for automation, since native symbols may
        # have been stripped.
        stack_fixer_module = import_stack_fixer_module("fix_stacks")

        def stack_fixer_function(line):
            return stack_fixer_module.fixSymbols(
                line,
                slowWarning=True,
                breakpadSymsDir=symbolsPath,
                hide_errors=hideErrors,
            )

    elif mozinfo.isLinux or mozinfo.isMac or mozinfo.isWin:
        # Run each line through fix_stacks.py. This method is preferred for
        # developer machines, so we don't have to run "mach buildsymbols".
        stack_fixer_module = import_stack_fixer_module("fix_stacks")

        def stack_fixer_function(line):
            return stack_fixer_module.fixSymbols(
                line, slowWarning=True, hide_errors=hideErrors
            )

    else:
        return None

    return stack_fixer_function


from annotation_utils.coco.structs import COCO_Dataset
from common_utils.path_utils import get_script_dir
import argparse

parser = argparse.ArgumentParser(description='Fix coco json file for pasonatron package')

parser.add_argument('img_dir', type=str,
                    help="path to image directory")
parser.add_argument('coco_ann_path', type=str,
                    help="path to json file")
parser.add_argument('coco_ann_output', type=str,
                    help="path to save a fixed json file")

args = parser.parse_args()

# img_dir = "/home/pasonatech/Blender2Detectron/BlenderProc-master/projectCrescent/crescent_test2/output3/coco_data/"
# coco_ann_path = "/home/pasonatech/Blender2Detectron/BlenderProc-master/projectCrescent/crescent_test2/output3/coco_data/coco_annotations.json"
# coco_ann_output ="/home/pasonatech/Blender2Detectron/BlenderProc-master/projectCrescent/crescent_test2/output3/coco_data/coco_annotations1.json"

# dataset = COCO_Dataset.load_from_path(coco_ann_path, strict=False, img_dir=get_script_dir())
dataset = COCO_Dataset.load_from_path(args.coco_ann_path, strict=False, img_dir=args.img_dir)
dataset.save_to_path(args.coco_ann_output, strict=True, overwrite=True)
print("Coco Json Fixed Successfully ")


from datetime import datetime
from decorators import debug_log

@debug_log
def validate_request(request):
    if 'action' in request and 'time' in request:
        return True
    return False

@debug_log
def make_response(request, code, data=None):
    return{
        'action': request.get('action'),
        'time': datetime.now().timestamp(),
        'code': code,
        'data': data
    }


import numpy as np

def encrypt():

    global text # ensuring that this variable is accessible  by the decrypt  function

    text = 'Plain text' #input text
    t_length = len(text) # length of text

    # Declaring number of columns which are equal to the length of the text
    C = t_length

    global array1,array2,a_length,a_length2 #ensuring that these variables are accessible by the decrypt function

    array1= ['']*C # creating first  array  which acts  as row  1
    array2=['']*C # creating second  array  which acts  as row  2

    a_length = len(array1)
    a_length2 = len(array2)
    #encrypted1= ''
    #encrypted2 = ''

    # inserting the text in the array while  skipping one space and starting from index 0
    for i,j in zip(range(0,t_length,2),range(0,a_length,2)):
        array1[j]= text[i]
        #encrypted1+=array1[j]
    # inserting the text in the array while  skipping one space and starting from index 1
    for i,j in zip(range(1,t_length,2),range(1,a_length2,2)):
        array2[j]= text[i]
        #encrypted2 += array2[j]

    matrix= np.stack([array1, array2], axis=0) #combining the arrays to make a matrix

    #encrypted= encrypted1 + encrypted2

    print('Input: ' + text)
    print('Encrypted message: ')
    print(str(matrix))
    #print('The encrypted message as text: ' + encrypted)

def decrypt():

    encrypt()#calling the encrypt function

    msg2=[]
    msg_len= len(text)
    decrypted= ''

    for x,y,z,a in zip(range(0,a_length,2),range(1,a_length2,2), range(0,msg_len,2),range(1,msg_len,2)):

        msg2.insert(z, array1[x]) #inserting only the letters from array1 into an array skipping one space, and starting from index 0
        msg2.insert(a, array2[y])#inserting only the letters from array2 into the  same  array skipping one space, and starting from index 1

    for letter in msg2:
        decrypted += letter# adding the letters from  the array with decrypted message to the decrypted string

    print( 'The decrypted message  is: '+ decrypted)

decrypt()

#factors that make the algorithm simple and clear:

    #The arrays were looped through in one for loop to make the algorithm more concise and simple.
    #The function and variable names are straight forward and descriptive making the algorithm more clear
    #There is sufficient commenting to add to the clarity


# 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
#
# 示例 1:
#
# 输入: "abcabcbb"
# 输出: 3
# 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
# 示例 2:
#
# 输入: "bbbbb"
# 输出: 1
# 解释: 因为无重复字符的最长子串是 "b"，所以其长度为 1。
# 示例 3:
#
# 输入: "pwwkew"
# 输出: 3
# 解释: 因为无重复字符的最长子串是 "wke"，所以其长度为 3。
#      请注意，你的答案必须是 子串 的长度，"pwke" 是一个子序列，不是子串。
#
# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        string = {}
        i, ans = 0, 0
        for j in range(len(s)):

            if s[j] in string:
                i = max(i, string[s[j]])

            ans = max(ans, j - i + 1)
            string[s[j]] = j + 1

        return ans

if __name__ == '__main__':
    demo = Solution()
    print(demo.lengthOfLongestSubstring('abcabcbb'))
    print(demo.lengthOfLongestSubstring('bbbbb'))
    print(demo.lengthOfLongestSubstring('pwwkew'))

算法/3.无重复字符的最长子串.py

3.无重复字符的最长子串.py


from unittest.mock import patch

from tests.lava_dispatcher.test_basic import Factory, StdoutTestCase

class UserCommandFactory(Factory):
    def create_b2260_job(self, filename):
        return self.create_job("b2260-01.jinja2", filename)

class TestUserCommand(StdoutTestCase):
    @patch(
        "lava_dispatcher.actions.deploy.tftp.which", return_value="/usr/bin/in.tftpd"
    )
    def test_pipeline(self, which_mock):
        factory = UserCommandFactory()
        job = factory.create_b2260_job("sample_jobs/b2260-user-command.yaml")
        job.validate()
        description_ref = self.pipeline_reference("b2260-user-command.yaml", job=job)
        self.assertEqual(description_ref, job.pipeline.describe())


def solve(str1):
    data = []
    if str1[0].isdigit():
        data.append(0)
    for i in range(1, len(str1)):
        if str1[i].isdigit() ^ str1[i-1].isdigit():
            data.append(i)
    if str1[-1].isdigit():
        data.append(len(str1))
    strmax = ""
    for i in range(len(data)):
        if i < len(data) / 2:
            start = data[i*2]
            end = data[i*2 + 1]
            if start != 0:
                if str1[start-1] == "+" or line[start - 1] == "-":
                    start -= 1
            if end < len(str1) and str1[end] == "." and (i+1) * 2 < len(data) and data[(i+1)*2] == end + 1:
                end = data[(i+1)*2 + 1]
            if len(strmax) <= end - start:
                strmax = str1[start: end]
    print(data)
    return "".join(strmax)

if __name__ == '__main__':
    while True:
        line = str(input()).strip()
        print(solve(line))


import json
import os
from time import sleep
import unittest
from appium import webdriver

PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

class FunkyTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '7.1.1'
        desired_caps['deviceName'] = 'Android Emulator'
        desired_caps['app'] = PATH(
            'C:\\workspace\\LearningApp\\app\\build\\outputs\\apk\\debug\\app-debug.apk'
        )
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    def tearDown(self):
        # end the session
        self.driver.quit()

    # example sending app to background ~~~
    def test_app_to_background(self):
        self.driver.background_app(1)
        assert True

    # check app is installed
    def test_app_is_installed(self):
        self.assertFalse(self.driver.is_app_installed('sdfdsfsdfsdf'))
        self.assertTrue(self.driver.is_app_installed('qa.learningapp'))

    # retrieve file
    def test_retrive_file(self):
        data = self.driver.pull_file('data/local/tmp/strings.json')
        xstrings = json.loads(data.decode('base64', 'strict'))
        print("Strings are: " + str(xstrings))

    # lock
    def test_lock(self):
        print("device is now locked...")
        self.driver.lock(2)
        sleep(1)

        # example custom adb command
        os.popen('adb shell input keyevent 82')  # unlock device

        # adb shell input keyevent 26 #Pressing the lock button
        # adb shell input touchscreen swipe 930 880 930 380 #Swipe UP
        # adb shell input text XXXX #Entering your passcode
        # adb shell input keyevent 66 #Pressing Enter

        assert True

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(FunkyTests)
    unittest.TextTestRunner(verbosity=2).run(suite)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# countdownp2.py
# A simple performance test of CPU-bound processes. Compare to the thread example module

import time
import multiprocessing

# Functions as threads
def countdown(count):
    while count > 0:
        count -= 1
    return

start = time.time()
countdown(10000000)
countdown(10000000)
end = time.time()
print("Sequential      ", end-start)

start = time.time()
p1 = multiprocessing.Process(target=countdown, args=(10000000,))     # Create the thread object
p2 = multiprocessing.Process(target=countdown, args=(10000000,))     # Create the thread object

p1.start()                                              # Launch the thread
p2.start()

p1.join()
p2.join()
end = time.time()
print("Multiproceessing", end-start)
print("Macintosh 1984")


"""
This file contains the code that learns, represents, and abstracts recipes.
"""
import re
import numpy as np
import jax.numpy as jnp
from typing import Iterable
from itertools import combinations, product
from collections import defaultdict
from frozendict import frozendict
from copy import deepcopy

# The total number of features in the envrionment
N_FEATURES = 2

class Statement:

    def __init__(self,
                 input_conditions: Iterable,
                 output_condition: dict
                 ):
        self.input_conditions = {
            "X": input_conditions[0],
            "Y": input_conditions[1]
        }
        self.output_condition = output_condition
        self.cached_values = {}

    def check_inputs_apply(self, x, y):
        input_feats = frozendict({"X": x, "Y": y})

        for input_name, input_condition in self.input_conditions.items():
            feats = input_feats[input_name]
            for feat, val in input_condition.items():
                # If the first half of the implementation isn't satisfied, return true
                if feats[feat] != val:
                    return False

        return True

    def check_output_consistent(self, z):
        # if we make it here, the input conditions have been satisfied
        for feat, val in self.output_condition.items():
            if z[feat] != val:
                return False

        # if we make it here, we meet both the output conditions
        return True

    def get_features_and_values(self):
        # get all the features and their values that are mentioned in this statement
        feature_values = {}
        for condition in list(self.input_conditions.values()) + [self.output_condition]:
            for feature, value in condition.items():
                if feature in feature_values:
                    feature_values[feature].add(value)
                else:
                    feature_values[feature] = set((value,))

        return feature_values

    def get_matrix(self, items):

        matrix = np.zeros((len(items) ** 2, len(items)))
        for i, xy in enumerate(product(items, repeat=2)):
            x, y = xy
            for j, z in enumerate(items):
                matrix[i,j] = int(self(x, y, z))

        return jnp.array(matrix)

    def is_abstract(self):
        """Return whether this rule is an abstract rule"""
        for input_name, conds in self.input_conditions.items():
            if len(conds) < N_FEATURES:
                return True

        if len(self.output_condition) < N_FEATURES:
            return True

        return False

    def __call__(self, x, y, z):

        triple = (x, y, z)
        if triple in self.cached_values:
            return self.cached_values[triple]

        inputs_apply = self.check_inputs_apply(x, y)
        if not inputs_apply:
            ret = True
        else:
            ret = self.check_output_consistent(z)

        self.cached_values[triple] = ret
        return ret

    def __str__(self):

        ret = ""
        input_conditions = []
        for x_feat, x_val in self.input_conditions["X"].items():
            input_conditions.append(f"{x_feat}(X) = {x_val}")
        for y_feat, y_val in self.input_conditions["Y"].items():
            input_conditions.append(f"{y_feat}(Y) = {y_val}")

        ret += " and ".join(input_conditions)

        output_conditions = []
        for z_feat, z_val in self.output_condition.items():
            output_conditions.append(f"{z_feat}(Z) = {z_val}")
        ret += " -> " + " and ".join(output_conditions)

        return ret

    def __hash__(self):
        """Hash a rule using the hash of its string"""
        return hash(self.__str__())

    def __eq__(self, other):
        return self.__str__() == other.__str__()

def check_input_consistency(rule1, rule2):
    """Check if the input conditions of rule1 include those in rule2"""
    for input_name in ("X", "Y"):
        all_features = set(rule1.input_conditions[input_name].keys()) | set(rule2.input_conditions[input_name].keys())
        for feature in all_features:
            if feature in rule1.input_conditions[input_name] and \
               feature in rule2.input_conditions[input_name] and \
               rule1.input_conditions[input_name][feature] != rule2.input_conditions[input_name][feature]:
                return False

    return True

def check_output_consistency(rule1, rule2):
    """Make sure that the outputs of the two rules don't contradict each other"""
    for feature in set(rule1.output_condition.keys()) | set(rule2.output_condition.keys()):
        # check if both talk about the same feature and necessitate different values
        if feature in rule1.output_condition and \
           feature in rule2.output_condition and \
           rule1.output_condition[feature] != rule2.output_condition[feature]:
            return False
    return True

def contradicts(rule1, rule2):
    """Check if rule1 contradicts rule2"""
    # check if the input conditions of rule1 entail the input conditions of rule2
    if check_input_consistency(rule1, rule2):
        return not check_output_consistency(rule1, rule2)
    else:
        return False

def inputs_generalize(rule1, rule2):
    """Check if the inputs to rule1 are more general than the inpnuts to rule2"""
    for input_name in rule1.input_conditions.keys():
        if input_name not in rule2.input_conditions:
            continue
        for feature, value in rule1.input_conditions[input_name].items():
            if feature not in rule2.input_conditions[input_name] or \
               rule2.input_conditions[input_name][feature] != value:
                return False

    return True

def subsumes(rule1, rule2):
    """Check if rule1 subsumes rule2"""
    if rule1.output_condition == rule2.output_condition:
        return inputs_generalize(rule1, rule2)
    else:
        return False

def check_mutual_consistency(
        statements: Iterable[Statement]
):
    """Check that all statements in a list of statements are compatible with each other"""

    # if both input conditions can be satisfied at the same time, then there must be an item that
    for i, statement1 in enumerate(statements):
        for j, statement2 in enumerate(statements):
            if j == i:
                continue
            if contradicts(statement1, statement2):
                return False

    return True

def get_possible_rules():
    # compute all of the possible conditions

    possible_feature_values = {
        "color": ["green", "red", "blue"],
        "shape": ["triangle", "square", "pentagon"]
    }
    possible_conditions = [{}]
    single_feature_rules = defaultdict(list)
    for feature, values in possible_feature_values.items():
        for value in values:
            single_feature_rules[feature].append({feature: value})
    possible_conditions.extend(single_feature_rules["color"])
    possible_conditions.extend(single_feature_rules["shape"])
    for combo in product(*single_feature_rules.values()):
        possible_conditions.append(combo[0] | combo[1])

    possible_rules = []
    for rule_conditions in product(possible_conditions, repeat=3):
        x_cond, y_cond, z_cond = rule_conditions
        if (len(x_cond) == 2 and len(y_cond) == 2) or len(z_cond) == 0:
            continue
        possible_rules.append(Statement([x_cond, y_cond], z_cond))

    return possible_rules

def abstract(
        knowledge_base: Iterable[Statement],
        known_items: Iterable[dict]
):
    """
    Infer generalizations about recipes. Returns a list of warranted abstractions.
    """

    possible_rules = get_possible_rules()

    # iterate over possible rules, keeping only those that don't contradict any known rules
    valid_abstractions = set()
    for proposed_rule in possible_rules:
        contradicts_known_rules = False
        pos_examples = 0
        for known_rule in knowledge_base:
            is_pos_example = False
            if check_input_consistency(proposed_rule, known_rule):
                if check_output_consistency(proposed_rule, known_rule):
                    pos_examples += 1
                else:
                    contradicts_known_rules = True
                    break

            if is_pos_example:
                pos_examples += 1
            if contradicts_known_rules:
                break

        if pos_examples >= 2 and not contradicts_known_rules:
            valid_abstractions.add(proposed_rule)

    return valid_abstractions

def anti_unify(statements):
    """
    Compute the least-general generalization of a set of statements
    """
    # aggregate all the output conditions
    total_output_condition = {}
    for statement in statements:
        for feature, value in statement.output_condition.items():
            if feature in total_output_condition:
                if total_output_condition[feature] != value:
                    return None
            else:
                total_output_condition[feature] = value

    general_input_conditions = dict([(cond_name, dict(cond)) for cond_name, cond in statements[0].input_conditions.items()])
    to_remove = []
    for statement in statements:
        for input_name in general_input_conditions.keys():
            for feature, value in general_input_conditions[input_name].items():
                if feature not in statement.input_conditions[input_name] or \
                   statement.input_conditions[input_name][feature] != value:
                    to_remove.append((input_name, feature))

    for input_name, feature in to_remove:
        del general_input_conditions[input_name][feature]

    general_statement = Statement([general_input_conditions["X"], general_input_conditions["Y"]], total_output_condition)

    return general_statement

if __name__ == "__main__":

    known_items = [
        {"color": "green", "shape": "triangle"},
        {"color": "green", "shape": "square"},
        {"color": "green", "shape": "pentagon"},
        {"color": "red", "shape": "triangle"},
        {"color": "red", "shape": "square"},
        {"color": "red", "shape": "pentagon"},
        {"color": "blue", "shape": "triangle"},
        {"color": "blue", "shape": "square"},
        {"color": "blue", "shape": "pentagon"}
    ]

    # learn some recipes
    knowledge = []
    knowledge.append(Statement(
        [
            {"color": "green", "shape": "triangle"},
            {"color": "red", "shape": "square"}
        ],
        {"color": "blue", "shape": "pentagon"}
    ))
    knowledge.append(Statement(
        [
            {"color": "green", "shape": "square"},
            {"color": "red", "shape": "square"}
        ],
        {"color": "blue", "shape": "triangle"}
    ))

    # print the knowledge
    print("\nbackground knowledge:")
    print(knowledge[0])
    print(knowledge[1])

    print("\n")

    # generate some abstractions
    abstractions = abstract(knowledge, known_items)

    print(f"{len(abstractions)} consistent abstractions:")
    for abstr in abstractions:
        print(abstr)

    print("\n")

    # test contradiction
    rule1 = Statement(
        input_conditions=[{"color": "red"}, {"shape": "square"}],
        output_condition={"color": "blue"}
    )

    rule2 = Statement(
        input_conditions=[{"color": "red"}, {"color": "green"}],
        output_condition={"color": "red"}
    )

    breaking_input = {'color': 'red', 'shape': 'triangle'}, {'color': 'green', 'shape': 'square'}

    print(contradicts(rule1, rule2))

    # test anti-unification


class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i = 1 if len(nums) > 0 else 0
        for index, num in enumerate(nums):
            if num > nums[i - 1]:
                nums[i] = num
                i += 1
        return i


# -*- coding: utf-8 -*-
from flask import *  # 必要なライブラリのインポート
import mask_test

import os
import numpy as np
import cv2

import datetime

# 画像保存ディレクトリを定義
SAVE_DIR = "./images"
if not os.path.isdir(SAVE_DIR):
    os.mkdir(SAVE_DIR)

app = Flask(__name__)  # アプリの設定

@app.route('/')
def index():
    return render_template('index.html', images=os.listdir(SAVE_DIR)[::-1])

@app.route('/images/<path:path>')
def send_js(path):
    return send_from_directory(SAVE_DIR, path)

@app.route('/upload', methods=['POST'])
def upload():
    if request.files['image']:
        # 画像として読み込み
        stream = request.files['image'].stream
        img_array = np.asarray(bytearray(stream.read()), dtype=np.uint8)
        img = cv2.imdecode(img_array, 1)

        # 変換
        # img = mask_test.collage(img)
        img = mask_test.collage(img)

        # 保存
        save_path = os.path.join(SAVE_DIR, datetime.datetime.now().strftime('%Y%m%d%H%M%S%f') + ".jpg")
        cv2.imwrite(save_path, img)

        print("save", save_path)

        return redirect('/')

if __name__ == "__main__":  # 実行されたら
    # # デバッグモード、localhost:8888 で スレッドオンで実行
    # app.run(debug=True, host='0.0.0.0', port=8888, threaded=True)
    app.run()


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

from keras.applications.nasnet import preprocess_input
from keras.preprocessing import image
from PIL import Image
import numpy as np
import os

def check_directory(dir_path):
    if not os.path.exists(dir_path):
        print('Create directory: {}'.format(dir_path))
        os.makedirs(dir_path, exist_ok=True)

def preprocess(img_file, target_size, transform=True):
    img = Image.open(img_file)
    w, h = img.size

    if transform:
        if w > h:
            ratio = (min(target_size) * 1.2) / float(h)
        else:
            ratio = (min(target_size) * 1.2) / float(w)
        output = img.resize((int(w * ratio), int(h * ratio)))
        output = output.convert("RGB")
        output = image.img_to_array(output)

        # Random rotation
        output = image.random_rotation(output, 30, row_axis = 0, col_axis = 1, channel_axis = 2, fill_mode = 'nearest')
        # Random crop
        left = np.random.randint(0, output.shape[1] - target_size[0] + 1)
        upper = np.random.randint(0, output.shape[0] - target_size[1] + 1)
        output = output[upper:upper + target_size[1], left:left + target_size[0]]

        # Random horizontal flip
        if np.random.rand() < 0.5:
            output = output[:, ::-1, :]
    else:
        if w > h:
            left = (w - h) // 2
            output = img.crop((left, 0, left + h, h))
        else:
            upper = (h - w) // 2
            output = img.crop((0, upper, w, upper + w))
        output = output.resize(target_size)
        output = output.convert("RGB")
        output = image.img_to_array(output)

    output = preprocess_input(output)

    return output


'''
DatasetBundle is a Bundle type that simply inherits from UploadedBundle.
'''
from codalab.objects.bundle import Bundle

class PrivateBundle(Bundle):
    """
    Dummy placeholder subclass of Bundle that is used to mask private bundles.
    """
    BUNDLE_TYPE = 'private'
    METADATA_SPECS = ()


def main():
    """
    This program takes a user's number input and prints
    that number multiplied by 2.
    """

    # Setting necessary global variables
    is_valid = False
    num = ''

    # This loop runs until the user enters a valid number
    while not is_valid:
        try:
            num = int(input("Enter a number: "))
            is_valid = True

        # If the value is not the correct type, then this will run
        except ValueError:
            print("The value entered is not valid")

    # Print the result
    print(f'The result is: {num * 2}')

if __name__ == "__main__":
    main()