import json
import logging
import requests
from datetime import datetime
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.core.mail.message import EmailMessage
from django.views.decorators.csrf import csrf_exempt

from reference_data.models import HumanPhenotypeOntology

from seqr.models import Individual, MatchmakerResult, MatchmakerContactNotes, SavedVariant
from seqr.model_utils import update_seqr_model
from seqr.utils.gene_utils import get_genes, get_gene_ids_for_gene_symbols
from seqr.utils.slack_utils import post_to_slack
from seqr.views.apis.auth_api import API_LOGIN_REQUIRED_URL
from seqr.views.utils.json_to_orm_utils import update_model_from_json
from seqr.views.utils.json_utils import create_json_response
from seqr.views.utils.orm_to_json_utils import _get_json_for_model, get_json_for_saved_variants
from seqr.views.utils.permissions_utils import check_permissions

from settings import MME_HEADERS, MME_LOCAL_MATCH_URL, MME_EXTERNAL_MATCH_URL, SEQR_HOSTNAME_FOR_SLACK_POST,  \
    MME_SLACK_SEQR_MATCH_NOTIFICATION_CHANNEL, MME_ADD_INDIVIDUAL_URL, MME_DELETE_INDIVIDUAL_URL

logger = logging.getLogger(__name__)

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def get_individual_mme_matches(request, individual_guid):
    """
    Looks for matches for the given individual. Expects a single patient (MME spec) in the POST
    data field under key "patient_data"
    Args:
        project_id,indiv_id and POST all data in POST under key "patient_data"
    Returns:
        Status code and results
    """
    individual = Individual.objects.get(guid=individual_guid)
    project = individual.family.project
    check_permissions(project, request.user)

    results = MatchmakerResult.objects.filter(individual=individual)

    saved_variants = get_json_for_saved_variants(
        SavedVariant.objects.filter(family=individual.family), add_tags=True, add_details=True,
        project=project, user=request.user)

    gene_ids = set()
    for variant in saved_variants:
        gene_ids.update(variant['transcripts'].keys())

    return _parse_mme_results(
        individual, results, request.user, additional_genes=gene_ids, response_json={
            'savedVariantsByGuid': {variant['variantGuid']: variant for variant in saved_variants}})

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def search_individual_mme_matches(request, individual_guid):
    """
    Looks for matches for the given individual. Expects a single patient (MME spec) in the POST
    data field under key "patient_data"
    Args:
        project_id,indiv_id and POST all data in POST under key "patient_data"
    Returns:
        Status code and results
    """

    individual = Individual.objects.get(guid=individual_guid)
    project = individual.family.project
    check_permissions(project, request.user)
    return _search_individual_matches(individual, request.user)

def _search_individual_matches(individual, user):
    patient_data = individual.mme_submitted_data
    if not patient_data:
        return create_json_response(
            {}, status=404, reason='No matchmaker submission found for {}'.format(individual.individual_id),
        )

    local_result = requests.post(url=MME_LOCAL_MATCH_URL, headers=MME_HEADERS, data=json.dumps(patient_data))
    if local_result.status_code != 200:
        try:
            response_json = local_result.json()
        except Exception:
            response_json = {}
        return create_json_response(response_json, status=local_result.status_code, reason='Error in local match')
    external_result = requests.post(url=MME_EXTERNAL_MATCH_URL, headers=MME_HEADERS, data=json.dumps(patient_data))
    if external_result.status_code != 200:
        try:
            response_json = external_result.json()
        except Exception:
            response_json = {}
        return create_json_response(response_json, status=external_result.status_code, reason='Error in external match')

    results = local_result.json()['results'] + external_result.json()['results']

    initial_saved_results = {
        result.result_data['patient']['id']: result for result in MatchmakerResult.objects.filter(individual=individual)
    }

    new_results = []
    saved_results = {}
    for result in results:
        saved_result = initial_saved_results.get(result['patient']['id'])
        if not saved_result:
            saved_result = MatchmakerResult.objects.create(
                individual=individual,
                result_data=result,
                last_modified_by=user,
            )
            new_results.append(result)
        saved_results[result['patient']['id']] = saved_result

    if new_results:
        _generate_slack_notification_for_seqr_match(individual, new_results)

    logger.info('Found {} matches for {} ({} new)'.format(len(results), individual.individual_id, len(new_results)))

    removed_patients = set(initial_saved_results.keys()) - set(saved_results.keys())
    removed_count = 0
    for patient_id in removed_patients:
        saved_result = initial_saved_results[patient_id]
        if saved_result.we_contacted or saved_result.host_contacted or saved_result.comments:
            if not saved_result.match_removed:
                saved_result.match_removed = True
                saved_result.save()
                removed_count += 1
            saved_results[patient_id] = saved_result
        else:
            saved_result.delete()
            removed_count += 1

    if removed_count:
        logger.info('Removed {} old matches for {}'.format(removed_count, individual.individual_id))

    return _parse_mme_results(individual, saved_results.values(), user)

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def update_mme_submission(request, individual_guid):
    """
    Create or update the submission for the given individual.
    """
    individual = Individual.objects.get(guid=individual_guid)
    project = individual.family.project
    check_permissions(project, request.user)

    submission_json = json.loads(request.body)

    submission_json.pop('individualGuid', {})
    phenotypes = submission_json.pop('phenotypes', [])
    gene_variants = submission_json.pop('geneVariants', [])
    if not phenotypes and not gene_variants:
        return create_json_response({}, status=400, reason='Genotypes or phentoypes are required')

    if not submission_json.get('patient', {}).get('id'):
        return create_json_response({}, status=400, reason='Patient id is required')

    genomic_features = []
    for gene_variant in gene_variants:
        if not gene_variant.get('geneId'):
            return create_json_response({}, status=400, reason='Gene id is required for genomic features')
        feature = {'gene': {'id': gene_variant['geneId']}}
        if 'numAlt' in gene_variant:
            feature['zygosity'] = gene_variant['numAlt'] % 2
        if gene_variant.get('pos'):
            feature['variant'] = {
                'alternateBases': gene_variant['alt'],
                'referenceBases': gene_variant['ref'],
                'referenceName': gene_variant['chrom'],
                'start': gene_variant['pos'],
                'assembly': gene_variant['genomeVersion'],
            }
        genomic_features.append(feature)

    submission_json['patient']['genomicFeatures'] = genomic_features
    submission_json['patient']['features'] = phenotypes

    response = requests.post(url=MME_ADD_INDIVIDUAL_URL, headers=MME_HEADERS, data=json.dumps(submission_json))

    if response.status_code not in (200, 409):
        try:
            response_json = response.json()
        except Exception:
            response_json = {}
        return create_json_response(response_json, status=response.status_code, reason=response.content)

    submitted_date = datetime.now()
    individual.mme_submitted_data = submission_json
    individual.mme_submitted_date = submitted_date
    individual.mme_deleted_date = None
    individual.mme_deleted_by = None
    individual.save()

    # update the project contact information if anything new was added
    new_contact_names = set(submission_json['patient']['contact']['name'].split(',')) - set(project.mme_primary_data_owner.split(','))
    new_contact_urls = set(submission_json['patient']['contact']['href'].replace('mailto:', '').split(',')) - set(project.mme_contact_url.replace('mailto:', '').split(','))
    updates = {}
    if new_contact_names:
        updates['mme_primary_data_owner'] = '{},{}'.format(project.mme_primary_data_owner, ','.join(new_contact_names))
    if new_contact_urls:
        updates['mme_contact_url'] = '{},{}'.format(project.mme_contact_url, ','.join(new_contact_urls))
    if updates:
        update_seqr_model(project, **updates)

    # search for new matches
    return _search_individual_matches(individual, request.user)

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def delete_mme_submission(request, individual_guid):
    """
    Create or update the submission for the given individual.
    """
    individual = Individual.objects.get(guid=individual_guid)
    project = individual.family.project
    check_permissions(project, request.user)

    if individual.mme_deleted_date:
        return create_json_response(
            {}, status=402, reason='Matchmaker submission has already been deleted for {}'.format(individual.individual_id),
        )

    matchbox_id = individual.mme_submitted_data['patient']['id']
    response = requests.delete(url=MME_DELETE_INDIVIDUAL_URL, headers=MME_HEADERS, data=json.dumps({'id': matchbox_id}))

    if response.status_code != 200:
        try:
            response_json = response.json()
        except Exception:
            response_json = {}
        return create_json_response(response_json, status=response.status_code, reason=response.content)

    deleted_date = datetime.now()
    individual.mme_deleted_date = deleted_date
    individual.mme_deleted_by = request.user
    individual.save()

    for saved_result in MatchmakerResult.objects.filter(individual=individual):
        if not (saved_result.we_contacted or saved_result.host_contacted or saved_result.comments):
            saved_result.delete()

    return create_json_response({'individualsByGuid': {individual_guid: {'mmeDeletedDate': deleted_date}}})

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def update_mme_result_status(request, matchmaker_result_guid):
    """
    Looks for matches for the given individual. Expects a single patient (MME spec) in the POST
    data field under key "patient_data"
    Args:
        project_id,indiv_id and POST all data in POST under key "patient_data"
    Returns:
        Status code and results
    """
    result = MatchmakerResult.objects.get(guid=matchmaker_result_guid)
    project = result.individual.family.project
    check_permissions(project, request.user)

    request_json = json.loads(request.body)
    update_model_from_json(result, request_json, allow_unknown_keys=True)

    return create_json_response({
        'mmeResultsByGuid': {matchmaker_result_guid: {'matchStatus': _get_json_for_model(result)}},
    })

@login_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def send_mme_contact_email(request, matchmaker_result_guid):
    """
    Sends the given email and updates the contacted status for the match
    Args:
        matchmaker_result_guid
    Returns:
        Status code and results
    """
    result = MatchmakerResult.objects.get(guid=matchmaker_result_guid)
    project = result.individual.family.project
    check_permissions(project, request.user)

    request_json = json.loads(request.body)
    email_message = EmailMessage(
        subject=request_json['subject'],
        body=request_json['body'],
        to=map(lambda s: s.strip(), request_json['to'].split(',')),
        from_email='matchmaker@broadinstitute.org',
    )
    try:
        email_message.send()
    except Exception as e:
        message = e.message
        json_body = {}
        if hasattr(e, 'response'):
            message = e.response.content
            try:
                json_body = e.response.json()
            except Exception:
                pass
        return create_json_response(json_body, status=getattr(e, 'status_code', 400), reason=message)

    update_model_from_json(result, {'weContacted': True})

    return create_json_response({
        'mmeResultsByGuid': {matchmaker_result_guid: {'matchStatus': _get_json_for_model(result)}},
    })

@staff_member_required(login_url=API_LOGIN_REQUIRED_URL)
@csrf_exempt
def update_mme_contact_note(request, institution):
    """
    Looks for matches for the given individual. Expects a single patient (MME spec) in the POST
    data field under key "patient_data"
    Args:
        project_id,indiv_id and POST all data in POST under key "patient_data"
    Returns:
        Status code and results
    """
    institution = institution.strip().lower()
    note, _ = MatchmakerContactNotes.objects.get_or_create(institution=institution)

    request_json = json.loads(request.body)
    note.comments = request_json.get('comments', '')
    note.save()

    return create_json_response({
        'mmeContactNotes': {institution: _get_json_for_model(note, user=request.user)},
    })

def get_mme_genes_phenotypes(results, additional_genes=None):
    hpo_ids = set()
    genes = additional_genes if additional_genes else set()
    for result in results:
        hpo_ids.update({feature['id'] for feature in result['patient'].get('features', []) if feature.get('id')})
        genes.update({gene_feature['gene']['id'] for gene_feature in result['patient'].get('genomicFeatures', [])})

    gene_ids = {gene for gene in genes if gene.startswith('ENSG')}
    gene_symols = {gene for gene in genes if not gene.startswith('ENSG')}
    gene_symbols_to_ids = get_gene_ids_for_gene_symbols(gene_symols)
    gene_ids.update({new_gene_ids[0] for new_gene_ids in gene_symbols_to_ids.values()})
    genes_by_id = get_genes(gene_ids)

    hpo_terms_by_id = {hpo.hpo_id: hpo.name for hpo in HumanPhenotypeOntology.objects.filter(hpo_id__in=hpo_ids)}

    return hpo_terms_by_id, genes_by_id, gene_symbols_to_ids

def _parse_mme_results(individual, saved_results, user, additional_genes=None, response_json=None):
    results = []
    contact_institutions = set()
    for result_model in saved_results:
        result = result_model.result_data
        result['matchStatus'] = _get_json_for_model(result_model)
        results.append(result)
        contact_institutions.add(result['patient']['contact'].get('institution', '').strip().lower())

    results_for_genes = [individual.mme_submitted_data] if individual.mme_submitted_data else []
    results_for_genes += results
    hpo_terms_by_id, genes_by_id, gene_symbols_to_ids = get_mme_genes_phenotypes(
        results_for_genes, additional_genes=additional_genes)

    parsed_results = [_parse_mme_result(result, hpo_terms_by_id, gene_symbols_to_ids, individual.guid) for result in results]
    parsed_results_gy_guid = {result['matchStatus']['matchmakerResultGuid']: result for result in parsed_results}

    contact_notes = {note.institution: _get_json_for_model(note, user=user)
                     for note in MatchmakerContactNotes.objects.filter(institution__in=contact_institutions)}

    submitted_data = parse_mme_patient(
        individual.mme_submitted_data, hpo_terms_by_id, gene_symbols_to_ids, individual.guid
    ) if individual.mme_submitted_data else None

    response = {
        'mmeResultsByGuid': parsed_results_gy_guid,
        'mmeContactNotes': contact_notes,
        'individualsByGuid': {individual.guid: {
            'mmeResultGuids': parsed_results_gy_guid.keys(),
            'mmeSubmittedData': submitted_data,
            'mmeSubmittedDate': individual.mme_submitted_date,
            'mmeDeletedDate': individual.mme_deleted_date,
        }},
        'genesById': genes_by_id,
    }
    if response_json:
        response.update(response_json)
    return create_json_response(response)

def _parse_mme_result(result, hpo_terms_by_id, gene_symbols_to_ids, individual_guid):
    parsed_result = parse_mme_patient(result, hpo_terms_by_id, gene_symbols_to_ids, individual_guid)
    parsed_result.update({
        'id': result['patient']['id'],
        'score': result['score']['patient'],
    })
    return parsed_result

def parse_mme_patient(result, hpo_terms_by_id, gene_symbols_to_ids, individual_guid):
    phenotypes = [feature for feature in result['patient'].get('features', [])]
    for feature in phenotypes:
        feature['label'] = hpo_terms_by_id.get(feature['id'])

    gene_variants = []
    for gene_feature in result['patient'].get('genomicFeatures', []):
        gene_id = gene_feature['gene']['id']
        if not gene_id.startswith('ENSG'):
            gene_ids = gene_symbols_to_ids.get(gene_feature['gene']['id'])
            gene_id = gene_ids[0] if gene_ids else None

        gene_variant = {'geneId': gene_id}
        if gene_id:
            if gene_feature.get('variant'):
                gene_variant.update({
                    'alt': gene_feature['variant'].get('alternateBases'),
                    'ref': gene_feature['variant'].get('referenceBases'),
                    'chrom': gene_feature['variant'].get('referenceName'),
                    'pos': gene_feature['variant'].get('start'),
                    'genomeVersion':  gene_feature['variant'].get('assembly'),
                })
            gene_variants.append(gene_variant)

    parsed_result = {
        'geneVariants': gene_variants,
        'phenotypes': phenotypes,
        'individualGuid': individual_guid,
    }
    parsed_result.update(result)
    return parsed_result

def _generate_slack_notification_for_seqr_match(individual, results):
    """
    Generate a SLACK notifcation to say that a match happened initiated from a seqr user.
    """
    matches = []
    hpo_terms_by_id, genes_by_id, _ = get_mme_genes_phenotypes(results)
    for result in results:
        patient = result['patient']

        gene_message = ''
        if patient.get('genomicFeatures'):
            gene_symbols = set()
            for gene in patient['genomicFeatures']:
                gene_symbol = gene['gene']['id']
                if gene_symbol.startswith('ENSG'):
                    gene_symbol = genes_by_id.get(gene_symbol, {}).get('geneSymbol', gene_symbol)
                gene_symbols.add(gene_symbol)

            gene_message = ' with genes {}'.format(' '.join(sorted(gene_symbols)))

        phenotypes_message = ''
        if patient.get('features'):
            phenotypes_message = ' with phenotypes {}'.format(' '.join(
                ['{} ({})'.format(feature['id'], hpo_terms_by_id.get(feature['id'])) for feature in patient['features']]
            ))

        matches.append(' - From {contact} at institution {institution}{gene_message}{phenotypes_message}.'.format(
            contact=patient['contact'].get('name', '(none given)'),
            institution=patient['contact'].get('institution', '(none given)'),
            gene_message=gene_message, phenotypes_message=phenotypes_message,
        ))

    message = u"""
    A search from a seqr user from project {project} individual {individual_id} had the following new match(es):

    {matches}

    {host}/{project_guid}/family_page/{family_guid}/matchmaker_exchange
    """.format(
        project=individual.family.project.name, individual_id=individual.individual_id, matches='\n\n'.join(matches),
        host=SEQR_HOSTNAME_FOR_SLACK_POST, project_guid=individual.family.project.guid, family_guid=individual.family.guid,
    )

    post_to_slack(MME_SLACK_SEQR_MATCH_NOTIFICATION_CHANNEL, message)


import openpyxl
from openpyxl import load_workbook
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

wb = load_workbook('tg.xlsx')
wb2 = load_workbook('test.xlsx')

sheet = wb['CS']
sheet2 = wb2['Sheet1']

driver = webdriver.Chrome(executable_path='D:\chromedriver_win32\chromedriver.exe')
driver.get('https://web.karunya.edu/exam/login_may20.asp')

j=2

for i in range(3,349):
    try:
        print(i)
        elem = driver.find_element_by_xpath('/html/body/table/tbody/tr/td/form/div/table/tbody/tr/td/p[1]/input')
        elem.send_keys(sheet.cell(row=i,column=2).value)

        elem = driver.find_element_by_xpath('/html/body/table/tbody/tr/td/form/div/table/tbody/tr/td/p[3]/input')
        elem.send_keys(sheet.cell(row=i,column=5).value.date().strftime("%d%m%Y"))

        elem = driver.find_element_by_xpath('/html/body/table/tbody/tr/td/form/div/table/tbody/tr/td/p[8]/input[1]')
        elem.click()

        elem = driver.find_element_by_xpath('/html/body/table[2]/tbody/tr[2]/td[1]').text
        sheet2.cell(row=j,column=1).value=elem

        elem = driver.find_element_by_xpath('/html/body/table[2]/tbody/tr[2]/td[2]').text
        sheet2.cell(row=j,column=2).value=elem
        print(elem)

        elem = driver.find_element_by_xpath('/html/body/center[2]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]/font/b').text
        sheet2.cell(row=j,column=3).value=elem

        elem = driver.find_element_by_xpath('/html/body/center[2]/table/tbody/tr/td[3]/table/tbody/tr[2]/td/font/b').text
        sheet2.cell(row=j,column=4).value=elem

        elem = driver.find_element_by_xpath('/html/body/table[1]/tbody/tr/td[2]/p/a/b')
        elem.click()
        j=j+1
        wb2.save('test.xlsx')

    except Exception as ex:
        print("invalid")
        elem = driver.find_element_by_xpath('/html/body/table[1]/tbody/tr/td[2]/p/a/b')
        elem.click()
        wb2.save('test.xlsx')

wb2.save('test.xlsx')
driver.quit


import numpy as np
import pandas as pd

dates = pd.date_range('20181010', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)),
                  index=dates,
                  columns=['A', 'B', 'C', 'D'])

# 制造缺失值
df.iloc[0, 1] = np.nan
df.iloc[1, 2] = np.nan

# 我们可以使用dropna这个方法来去掉带有nan的行或者列
# axis=0表示去除含有nan的行;axis=1表示去除含有nan的列
# how='any'表示'或运算'(只要含有就去除);
# how='all'表示'与运算'(全部都是nan才去除)
print(df.dropna(axis=0, how='any'))

# 我们可以使用fillna来填充nan
print(df.fillna(value=0))

# 检查df是否有nan,要是缺失就返回ture
print(df.isnull())

# 检查举证中是否有缺失，这里相当于检查上一个矩阵中是否有True
# any表示只要有一个元素与==右边的相等就返回True
print(np.any(df.isnull()) == True)


#!/usr/bin/env python

import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped
import time

if __name__ == "__main__":
	rospy.init_node("initial_pose_publisher_script")
	pub = rospy.Publisher("/initialpose", PoseWithCovarianceStamped, queue_size=10)
	print("Created publisher.")
	rospy.sleep(1.0)
	msg = PoseWithCovarianceStamped()
	msg.pose.pose.position.x = 71.86
	msg.pose.pose.position.y = 97.99
	pub.publish(msg)
	print("Published message.")
	rospy.spin()


#!/usr/bin/env python3

"""Convert files to/from MFA format for use in ESPnet TTS.

If you wish to add functions to create .lab files for MFA, add them like this:

def make_labs_[dataset]:
     ...
"""

import argparse
import os
import re
import sys
import traceback
from pathlib import Path

from praatio import textgrid
from tacotron_cleaner import cleaners

ROOT_DIR = os.getcwd()

TEXTGRID_DIR = f"{ROOT_DIR}/textgrids"
TRAIN_TEXT_PATH = f"{ROOT_DIR}/data/train/text"
DURATIONS_PATH = f"{ROOT_DIR}/data/train/durations"

punctuation = "!',.?" + '"'

fs = 22050
hop_length = 256

def get_parser():
    """Get argument parser."""
    parser = argparse.ArgumentParser(
        description=(
            "Utilities to format from MFA to ESPnet.\n"
            "Usage: python scripts/utils/mfa_format.py ACTION [dataset] [options]\n"
            "python scripts/utils/mfa_format.py labs ljspeech\n"
            "python scripts/utils/mfa_format.py validate\n"
            "python scripts/utils/mfa_format.py durations\n"
        )
    )

    parser.add_argument(
        "type",
        choices=["labs", "validate", "durations"],
        help='Must be "labs, "validate" or "durations',
    )
    parser.add_argument(
        "--dataset",
        choices=["ljspeech"],
        help='Currently only supports "ljspeech"',
    )
    parser.add_argument(
        "--wavs_dir",
        help="Path to wavs dir, lab files will be added here",
    )
    parser.add_argument(
        "--textgrid_dir",
        default=TEXTGRID_DIR,
        help="Path to output MFA .TextGrid files",
    )
    parser.add_argument(
        "--train_text_path",
        default=TRAIN_TEXT_PATH,
        help="Path to output list of utterances to phonemes",
    )
    parser.add_argument(
        "--durations_path",
        default=DURATIONS_PATH,
        help="Path to output durations file",
    )

    return parser

def make_labs_ljspeech(args):
    """Make lab file for ljspeech dataset."""
    wavs_dir = Path(args.wavs_dir)
    with open(wavs_dir / "../metadata.csv") as f:
        for line in f:
            items = line.rstrip().split("|")
            filename = items[0]
            text = items[-1]
            with open(wavs_dir / f"{filename}.lab", "w") as lab_f:
                # Same as custom_english_cleaners but without uppercasing.
                text = cleaners.convert_to_ascii(text)
                text = cleaners.lowercase(text)
                text = cleaners.expand_numbers(text)
                text = cleaners.expand_abbreviations(text)
                text = cleaners.expand_symbols(text)
                text = cleaners.remove_unnecessary_symbols(text)
                text = cleaners.collapse_whitespace(text)
                # Convert single quotes into double quotes
                #   so that MFA doesn't confuse them with clitics.
                # Find ' not preceded by a letter to the last ' not followed by a letter
                text = re.sub(r"(\W|^)'(\w[\w .,!?']*)'(\W|$)", r'\1"\2"\3', text)
                lab_f.write(text)
                print(filename)
    print("Finished writing .lab files")

def get_phoneme_durations(tg: textgrid.Textgrid, original_text: str):
    """Get phohene durations."""
    orig_text = original_text.replace(" ", "").rstrip()
    text_pos = 0

    words = tg.tierDict["words"].entryList
    phones = tg.tierDict["phones"].entryList

    prev_end = 0.0
    time2punc = {}
    phrase_words = []
    word = None
    for word in words:
        start = word.start
        if start == prev_end:
            phrase_words.append(word.label)
        else:
            # find punctuation at end of previous phrase
            phrase = "".join(phrase_words)
            for letter in phrase:
                char = orig_text[text_pos]
                while char != letter:
                    text_pos += 1
                    char = orig_text[text_pos]
                text_pos += 1

            timing = (prev_end, start)
            puncs = []
            while text_pos < len(orig_text):
                char = orig_text[text_pos]
                if char.isalpha():
                    break
                else:
                    puncs.append(char)
                    text_pos += 1
            time2punc[timing] = puncs if puncs else ["sil"]

            phrase_words = [word.label]
        prev_end = word.end

    # We preserve the start/end timings and not interval lengths
    #   due to rounding errors when converted to frames.
    timings = [0.0]
    new_phones = []
    prev_end = 0.0
    for phone in phones:
        start = phone.start
        if start > prev_end:
            # insert punctuation
            try:
                puncs = time2punc[(prev_end, start)]
            except KeyError:
                # In some cases MFA word segmentation fails
                #   and there is a pause inside the word.
                puncs = ["sil"]
            new_phones.extend(puncs)
            num_puncs = len(puncs)
            pause_time = (start - prev_end) / num_puncs
            for i in range(1, len(puncs) + 1):
                timings.append(prev_end + pause_time * i)

        new_phones.append(phone.label)
        timings.append(phone.end)
        prev_end = phone.end

    # Add end-of-utterance punctuations
    if word.end < tg.maxTimestamp:
        text_pos = len(orig_text) - 1
        while orig_text[text_pos] in punctuation:
            text_pos -= 1
        puncs = orig_text[text_pos + 1 :]
        if not puncs:
            puncs = ["sil"]
        new_phones.extend(puncs)
        num_puncs = len(puncs)
        pause_time = (tg.maxTimestamp - word.end) / num_puncs
        for i in range(1, len(puncs) + 1):
            timings.append(prev_end + pause_time * i)

    assert len(new_phones) + 1 == len(timings)

    total_durations = int(tg.maxTimestamp * fs) // hop_length + 1
    timing_frames = [int(timing * fs / hop_length + 0.5) for timing in timings]
    durations = [
        timing_frames[i + 1] - timing_frames[i] for i in range(len(timing_frames) - 1)
    ]

    assert sum(durations) == total_durations

    return new_phones, durations

def validate(args):
    """Validate arguments."""
    valid = True
    tg_paths = sorted(Path(args.textgrid_dir).glob("*.TextGrid"))
    for tg_path in tg_paths:
        filename = tg_path.stem
        tg = textgrid.openTextgrid(tg_path, False)
        phones = tg.tierDict["phones"].entryList
        for phone in phones:
            if phone.label == "spn":
                with open(Path(args.wavs_dir) / f"{filename}.lab") as f:
                    original_text = f.read()
                    print(f"{filename} contains spn. Text: {original_text}")
                valid = False
    assert valid

def make_durations(args):
    """Make durations file."""
    wavs_dir = Path(args.wavs_dir)
    textgrid_dir = args.textgrid_dir
    train_text_path = args.train_text_path
    durations_path = args.durations_path

    os.makedirs(os.path.dirname(train_text_path), exist_ok=True)
    with open(train_text_path, "w") as text_file:
        with open(durations_path, "w") as durations_file:
            lab_paths = sorted(wavs_dir.glob("*.lab"))
            for lab_path in lab_paths:
                filename = lab_path.stem
                with open(lab_path) as lab_file:
                    original_text = lab_file.read()
                tg_path = os.path.join(textgrid_dir, f"{filename}.TextGrid")
                tg = textgrid.openTextgrid(tg_path, False)
                new_phones, durations = get_phoneme_durations(tg, original_text)
                text_file.write(f'{filename} {" ".join(new_phones)}\n')
                durations = " ".join(str(d) for d in durations)
                durations_file.write(f"{filename} {durations} 0\n")

if __name__ == "__main__":
    args = get_parser().parse_args()
    try:
        if args.type == "labs":
            func = globals()[f"make_labs_{args.dataset}"]
            func(args)
        elif args.type == "validate":
            validate(args)
        elif args.type == "durations":
            make_durations(args)
        else:
            raise NotImplementedError
    except Exception:
        traceback.print_exc()
        sys.exit(1)


import pickle
from unittest import TestCase

import pytest
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from app.models import Base, DatasetSample
from app.wrapper import ModelServingWrapper, ShapeMismatchError

class TestModelServingWrapper(TestCase):

    TESTBASE_PATH = "sqlite:///base.sqlite"

    @pytest.fixture(autouse=True)
    def temp_database(self, tmpdir):
        tmpdir.chdir()
        engine = create_engine(self.TESTBASE_PATH)
        Base.metadata.create_all(engine)

    def get_session(self):
        engine = create_engine(self.TESTBASE_PATH)
        Session = sessionmaker(bind=engine)
        session = Session()
        return session

    def test__fit(self):
        session = self.get_session()

        session.add(DatasetSample(image=pickle.dumps(np.array([0])), label=0))
        session.add(DatasetSample(image=pickle.dumps(np.array([1])), label=1))

        session.commit()

        t = ModelServingWrapper(LinearRegression(), self.TESTBASE_PATH)
        t._fit()

        self.assertAlmostEqual(t._model.coef_[0], 1)
        self.assertAlmostEqual(t._model.intercept_, 0)

    def test_predict(self):
        session = self.get_session()

        session.add(DatasetSample(image=pickle.dumps(np.array([0])), label=0))
        session.add(DatasetSample(image=pickle.dumps(np.array([1])), label=1))

        session.commit()

        t = ModelServingWrapper(LogisticRegression(), self.TESTBASE_PATH)
        t.fit()

        self.assertEqual(t.predict(np.array([1])), 1)

    def test_predict_incorrect_shape(self):
        session = self.get_session()

        session.add(DatasetSample(image=pickle.dumps(np.array([0, 2])), label=1))
        session.add(DatasetSample(image=pickle.dumps(np.array([0, 1])), label=0))
        session.commit()

        t = ModelServingWrapper(LogisticRegression(), self.TESTBASE_PATH)
        t.fit()

        with self.assertRaises(ShapeMismatchError):
            t.predict(np.array([0]))

    def test_predict_not_fitted(self):
        t = ModelServingWrapper(LogisticRegression(), self.TESTBASE_PATH)

        with self.assertRaises(ValueError):
            t.predict(np.array([0, 1, 2]))

    def test__init__with_fitted_model(self):
        fitted_model = LogisticRegression()
        fitted_model.fit(np.array([[0, 1, 2], [4, 5, 6]]), np.array([0, 1]))

        with self.assertRaises(ValueError):
            ModelServingWrapper(fitted_model, self.TESTBASE_PATH)

    def test__get_training_dataset_empty(self):

        t = ModelServingWrapper(LinearRegression(), self.TESTBASE_PATH)

        with self.assertRaises(ValueError):
            t._get_training_dataset()

    def test__get_training_dataset_one_sample(self):
        session = self.get_session()

        test_vector = np.random.random(100)
        test_label = np.random.randint(0, 128)

        session.add(DatasetSample(image=pickle.dumps(test_vector), label=test_label))
        session.commit()

        t = ModelServingWrapper(LinearRegression(), self.TESTBASE_PATH)
        images, labels, shape = t._get_training_dataset()

        self.assertTrue(np.array_equal(images, np.vstack([test_vector])))
        self.assertTrue(np.array_equal(labels, np.array([test_label])))
        self.assertEqual(shape, test_vector.shape)

    def test__get_training_dataset_shapes_mismatch(self):
        session = self.get_session()

        session.add(DatasetSample(image=pickle.dumps(np.array([0])), label=0))
        session.add(DatasetSample(image=pickle.dumps(np.array([0, 1])), label=0))
        session.commit()

        t = ModelServingWrapper(LinearRegression(), self.TESTBASE_PATH)

        with self.assertRaises(ValueError):
            images, labels, shape = t._get_training_dataset()


# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: Dwarika
# @Env: python 3.6
# @Github: https://github.com/Dwarkeshsahu/InfluenceCoding

import phonenumbers
from phonenumbers import geocoder as GC
from phonenumbers import carrier as CR
from phonenumbers import timezone as TZ

def PHONE_NO_DETAILS() :

    usernumber = input("Enter Your Number :")

    phone_no = phonenumbers.parse(usernumber)

    DETAILS_1 = GC.description_for_number(phone_no , "en")

    DETAILS_2 = CR.name_for_number(phone_no , "en")

    DETAILS_3 = TZ.time_zones_for_number(phone_no)

    # Number Details
    print(DETAILS_1)

    # Number Informatiom
    print(DETAILS_2)

    # Number Time Zone
    print(DETAILS_3)

PHONE_NO_DETAILS()

"""
    User Mobile Number Details

    How To Use
    Example :
    If You From India Enter Your Number
    This Formate

    Enter : +91****

    This Code Not Run In SL
    Run Your PC
    You will get better parformace

    Thank You

"""


import sys
from collections import defaultdict
inp = lambda : sys.stdin.readline()
N, H = map(int, inp().split())
def_dict = defaultdict(int)
top, down = [], []
for i in range(N):
    if i % 2:
        top.append(int(inp()))
    else:
        down.append(int(inp()))
top.sort()
down.sort()
left, right = 1, H
min_cnt = 2000001
while left < right:
    left_cnt, right_cnt = 0, 0
    for i in range(N//2):
        if left <= down[i]:
            left_cnt += 1
        if left > H - top[i]:
            left_cnt += 1
        left += 1
        def_dict[left_cnt] += 1
        if H - right <= top[i]:
            right_cnt += 1
        if down[i] < right:
            right_cnt += 1
        right -= 1
        def_dict[right_cnt] += 1
print(def_dict)


"""
Search (Chapters 3-4)
The way to use this code is to subclass Problem to create a class of problems,
then create problem instances and solve them with calls to the various search
functions.
"""

import sys
from collections import deque

from pac_man.utils import *
from pac_man.node import Node

# ______________________________________________________________________________
# Uninformed Search algorithms

def breadth_first_tree_search(problem):
    """
    [Figure 3.7]
    Search the shallowest nodes in the search tree first.
    Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    Repeats infinitely in case of loops.
    """

    frontier = deque([Node(problem.initial)])  # FIFO queue

    while frontier:
        node = frontier.popleft()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None

def depth_first_tree_search(problem):
    """
    [Figure 3.7]
    Search the deepest nodes in the search tree first.
    Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    Repeats infinitely in case of loops.
    """

    frontier = [Node(problem.initial)]  # Stack

    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None

def depth_first_graph_search(problem):
    """
    [Figure 3.7]
    Search the deepest nodes in the search tree first.
    Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    Does not get trapped by loops.
    If two paths reach a state, only use the first one.
    """
    frontier = [(Node(problem.initial))]  # Stack

    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        frontier.extend(
            child
            for child in node.expand(problem)
            if child.state not in explored and child not in frontier
        )
    return None

def breadth_first_graph_search(problem):
    """[Figure 3.11]
    Note that this function can be implemented in a
    single line as below:
    return graph_search(problem, FIFOQueue())
    """
    node = Node(problem.initial)
    if problem.goal_test(node.state):
        return node
    frontier = deque([node])
    explored = set()
    while frontier:
        node = frontier.popleft()
        explored.add(node.state)
        for child in node.expand(problem):
            if child.state not in explored and child not in frontier:
                if problem.goal_test(child.state):
                    return child
                frontier.append(child)
    return None

def best_first_graph_search(problem, f, display=False):
    """Search the nodes with the lowest f scores first.
    You specify the function f(node) that you want to minimize; for example,
    if f is a heuristic estimate to the goal, then we have greedy best
    first search; if f is node.depth then we have breadth-first search.
    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
    values will be cached on the nodes as they are computed. So after doing
    a best first search you can examine the f values of the path returned."""
    f = memoize(f, "f")
    node = Node(problem.initial)
    frontier = PriorityQueue("min", f)
    frontier.append(node)
    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            if display:
                print(
                    len(explored),
                    "paths have been expanded and",
                    len(frontier),
                    "paths remain in the frontier",
                )
            return node
        explored.add(node.state)
        for child in node.expand(problem):
            if child.state not in explored and child not in frontier:
                frontier.append(child)
            elif child in frontier:
                if f(child) < frontier[child]:
                    del frontier[child]
                    frontier.append(child)
    return None

def uniform_cost_search(problem, display=False):
    """[Figure 3.14]"""
    return best_first_graph_search(problem, lambda node: node.path_cost, display)

def depth_limited_search(problem, limit=50):
    """[Figure 3.17]"""

    def recursive_dls(node, problem, limit):
        if problem.goal_test(node.state):
            return node
        elif limit == 0:
            return "cutoff"
        else:
            cutoff_occurred = False
            for child in node.expand(problem):
                result = recursive_dls(child, problem, limit - 1)
                if result == "cutoff":
                    cutoff_occurred = True
                elif result is not None:
                    return result
            return "cutoff" if cutoff_occurred else None

    # Body of depth_limited_search:
    return recursive_dls(Node(problem.initial), problem, limit)

def iterative_deepening_search(problem):
    """[Figure 3.18]"""
    for depth in range(sys.maxsize):
        result = depth_limited_search(problem, depth)
        if result != "cutoff":
            return result

# ______________________________________________________________________________
# Bidirectional Search
# Pseudocode from https://webdocs.cs.ualberta.ca/%7Eholte/Publications/MM-AAAI2016.pdf

def bidirectional_search(problem):
    e = 0
    if isinstance(problem, GraphProblem):
        e = problem.find_min_edge()
    gF, gB = {Node(problem.initial): 0}, {Node(problem.goal): 0}
    openF, openB = [Node(problem.initial)], [Node(problem.goal)]
    closedF, closedB = [], []
    U = np.inf

    def extend(U, open_dir, open_other, g_dir, g_other, closed_dir):
        """Extend search in given direction"""
        n = find_key(C, open_dir, g_dir)

        open_dir.remove(n)
        closed_dir.append(n)

        for c in n.expand(problem):
            if c in open_dir or c in closed_dir:
                if g_dir[c] <= problem.path_cost(g_dir[n], n.state, None, c.state):
                    continue

                open_dir.remove(c)

            g_dir[c] = problem.path_cost(g_dir[n], n.state, None, c.state)
            open_dir.append(c)

            if c in open_other:
                U = min(U, g_dir[c] + g_other[c])

        return U, open_dir, closed_dir, g_dir

    def find_min(open_dir, g):
        """Finds minimum priority, g and f values in open_dir"""
        # pr_min_f isn't forward pr_min instead it's the f-value
        # of node with priority pr_min.
        pr_min, pr_min_f = np.inf, np.inf
        for n in open_dir:
            f = g[n] + problem.h(n)
            pr = max(f, 2 * g[n])
            pr_min = min(pr_min, pr)
            pr_min_f = min(pr_min_f, f)

        return pr_min, pr_min_f, min(g.values())

    def find_key(pr_min, open_dir, g):
        """Finds key in open_dir with value equal to pr_min
        and minimum g value."""
        m = np.inf
        node = Node(-1)
        for n in open_dir:
            pr = max(g[n] + problem.h(n), 2 * g[n])
            if pr == pr_min:
                if g[n] < m:
                    m = g[n]
                    node = n

        return node

    while openF and openB:
        pr_min_f, f_min_f, g_min_f = find_min(openF, gF)
        pr_min_b, f_min_b, g_min_b = find_min(openB, gB)
        C = min(pr_min_f, pr_min_b)

        if U <= max(C, f_min_f, f_min_b, g_min_f + g_min_b + e):
            return U

        if C == pr_min_f:
            # Extend forward
            U, openF, closedF, gF = extend(U, openF, openB, gF, gB, closedF)
        else:
            # Extend backward
            U, openB, closedB, gB = extend(U, openB, openF, gB, gF, closedB)

    return np.inf

# ______________________________________________________________________________
# Informed (Heuristic) Search

greedy_best_first_graph_search = best_first_graph_search

# Greedy best-first search is accomplished by specifying f(n) = h(n).

def astar_search(problem, h=None, display=False):
    """A* search is best-first graph search with f(n) = g(n)+h(n).
    You need to specify the h function when you call astar_search, or
    else in your Problem subclass."""
    h = memoize(h or problem.h, "h")
    return best_first_graph_search(problem, lambda n: n.path_cost + h(n), display)

# ______________________________________________________________________________
# Other search algorithms

def recursive_best_first_search(problem, h=None):
    """[Figure 3.26]"""
    h = memoize(h or problem.h, "h")

    def RBFS(problem, node, flimit):
        if problem.goal_test(node.state):
            return node, 0  # (The second value is immaterial)
        successors = node.expand(problem)
        if len(successors) == 0:
            return None, np.inf
        for s in successors:
            s.f = max(s.path_cost + h(s), node.f)
        while True:
            # Order by lowest f value
            successors.sort(key=lambda x: x.f)
            best = successors[0]
            if best.f > flimit:
                return None, best.f
            if len(successors) > 1:
                alternative = successors[1].f
            else:
                alternative = np.inf
            result, best.f = RBFS(problem, best, min(flimit, alternative))
            if result is not None:
                return result, best.f

    node = Node(problem.initial)
    node.f = h(node)
    result, bestf = RBFS(problem, node, np.inf)
    return result

def hill_climbing(problem):
    """
    [Figure 4.2]
    From the initial node, keep choosing the neighbor with highest value,
    stopping when no neighbor is better.
    """
    states = []
    current = Node(problem.initial)
    dead_ends = set()

    while current.state != problem.goal:
        states.append(current.state)
        all_neighbors = current.expand(problem)
        neighbors = [n for n in all_neighbors if n.state not in dead_ends]

        # if the current node has only one neighbor and it is equal to the
        # last visited node, it is a dead end
        if len(neighbors) == 1 and len(states) > 1 and neighbors[0].state == states[-2]:
            dead_ends.add(current.state)

        if not neighbors:
            break

        neighbor = argmax_random_tie(
            neighbors, key=lambda node: problem.value(node.state)
        )

        #if problem.value(neighbor.state) < problem.value(current.state):
        #    break

        current = neighbor
        problem.record_choice(current)

    return current.state, states

def exp_schedule(k=20, lam=0.005, limit=100):
    """One possible schedule function for simulated annealing"""
    return lambda t: (k * np.exp(-lam * t) if t < limit else 0)

def simulated_annealing(problem, schedule=exp_schedule()):
    """[Figure 4.5] CAUTION: This differs from the pseudocode as it
    returns a state instead of a Node."""
    current = Node(problem.initial)
    for t in range(sys.maxsize):
        T = schedule(t)
        if T == 0:
            return current.state
        neighbors = current.expand(problem)
        if not neighbors:
            return current.state
        next_choice = random.choice(neighbors)
        delta_e = problem.value(next_choice.state) - problem.value(current.state)
        if delta_e > 0 or probability(np.exp(delta_e / T)):
            current = next_choice

def simulated_annealing_full(problem, schedule=exp_schedule()):
    """ This version returns all the states encountered in reaching
    the goal state."""
    states = []
    current = Node(problem.initial)
    for t in range(sys.maxsize):
        states.append(current.state)
        T = schedule(t)
        if T == 0:
            return states
        neighbors = current.expand(problem)
        if not neighbors:
            return current.state
        next_choice = random.choice(neighbors)
        delta_e = problem.value(next_choice.state) - problem.value(current.state)
        if delta_e > 0 or probability(np.exp(delta_e / T)):
            current = next_choice

def and_or_graph_search(problem):
    """[Figure 4.11]Used when the environment is nondeterministic and completely observable.
    Contains OR nodes where the agent is free to choose any action.
    After every action there is an AND node which contains all possible states
    the agent may reach due to stochastic nature of environment.
    The agent must be able to handle all possible states of the AND node (as it
    may end up in any of them).
    Returns a conditional plan to reach goal state,
    or failure if the former is not possible."""

    # functions used by and_or_search
    def or_search(state, problem, path):
        """returns a plan as a list of actions"""
        if problem.goal_test(state):
            return []
        if state in path:
            return None
        for action in problem.actions(state):
            plan = and_search(problem.result(state, action), problem, path + [state])
            if plan is not None:
                return [action, plan]

    def and_search(states, problem, path):
        """Returns plan in form of dictionary where we take action plan[s] if we reach state s."""
        plan = {}
        for s in states:
            plan[s] = or_search(s, problem, path)
            if plan[s] is None:
                return None
        return plan

    # body of and or search
    return or_search(problem.initial, problem, [])


f = open("input","r")
two = three = 0
for i in f:
  l = [0]*26
  for j in i.strip():
    l[ord(j)-ord('a')] += 1
  if(2 in l):
    two+=1
  if(3 in l):
    three+=1
print(two*three)


from django.urls import path, include
from .views import *

app_name = 'evcharger'

urlpatterns = [
    path('',EvchargerListView.as_view()),
    path('<int:pk>/',EvchargerDetailView.as_view()),
    path('<int:pk>/delete/',EvchargerDelete),
    path('register/',EvchargerRegisterView.as_view()),
    path('<int:pk>/update/',EvchargerUpdateView.as_view(),name='cpupdate'),

]


# loop aninhado

lot_2D = [
    ['Toyota', 'Audi', 'BMW'],
    ['Lexus', 'Jeep'],
    ['Honda', 'Kia', 'Mazda']
]

#print(lot_2D[0][0])  # lista 0 , elemento 0 da lista 0

# for linha in lot_2D:
#     for carro in linha:
#         print(carro)

lot_3D =[
    [
        ['Tesla', 'Fiat', 'BMW'],
        ['Honda', 'Jeep'],
        ['Saab','Kia', 'Ford']
    ],
    [
        ['Subaru', 'Nissan'],
        ['Volkswagen'],
        ['Mercedez']
    ],
    [
        ['Chevrolet', 'GMC'],
        ['Ferrari', 'Lamborghini']
    ]
]
#print(lot_3D[0])
# print(lot_3D[0][0])
#print(lot_3D[0][0][1])
for grupo in lot_3D:
    for line in grupo:
        for carro in line:
            print(carro)


import collections
import logging
import pendulum
import time

from http_monitor.interval import Interval
from http_monitor.request_buffer import RequestBuffer

class Monitor:
    """
    monitors statistics for metrics intervals for a stream of http requests
    also responsible for setting alert state
    """
    def __init__(self
                 , request_file_path
                 , refresh_rate
                 , avg_hits_threshold
                 , poll_delay=1.0
                 , alert_window=120
                 , is_live_monitor=True
                 ):
        """
        :param request_file_path: the http request file to monitor
        :param refresh_rate: the time interval to aggregate metrics around
        :param avg_hits_threshold: alert threshold for avg requests per second
        :param poll_delay: poll delay for empty request buffer
        :param alert_window: look back seconds to monitor alerts
        :param is_live_monitor: whether to keep tailing file and monitoring or stop once all requests are read
        """
        self.request_file_path = request_file_path
        self.refresh_rate = refresh_rate
        self.avg_hits_threshold = avg_hits_threshold
        self.poll_delay = poll_delay
        self.alert_window = alert_window
        self.alert_state = False
        self.latest_alert_timestamp = 0
        self.interval_queue = collections.deque()
        self.is_live_monitor = is_live_monitor

    def start_monitor(self):
        request_buffer = RequestBuffer(self.request_file_path)
        request_buffer.start()
        current_interval = None
        while True:
            # TODO: clean this up, break this up! too many if else if else if else
            if request_buffer.request_queue.empty():
                now = int(time.time())
                if current_interval and now > current_interval.end_ts:
                    prev_end_ts = current_interval.end_ts
                    prev_hits = current_interval.hits
                    self._process_metrics_interval(current_interval)
                    # start live monitoring at current time if there is no more requests to bucket
                    if prev_hits == 0:
                        if self.is_live_monitor:
                            current_interval = Interval(now, self.refresh_rate)
                        else:
                            logging.info("All http request logs processed! Not in live monitoring mode so we're done!")
                            request_buffer.stop()
                            return
                    else:
                        current_interval = Interval(prev_end_ts, self.refresh_rate)
                time.sleep(self.poll_delay)
            else:
                request = request_buffer.request_queue.get()
                if current_interval is None:
                    # metrics interval starts with the timestamp of the first request
                    current_interval = Interval(request.date, self.refresh_rate)
                while not current_interval.process_request(request):
                    prev_end_ts = current_interval.end_ts
                    self._process_metrics_interval(current_interval)
                    current_interval = Interval(prev_end_ts, self.refresh_rate)

    def _process_metrics_interval(self, interval):
        """
        this method wraps up a completed metrics interval and really does too much:
        1. append to the interval_queue to keep track to be able to able to looks back numerous data points
        2. display the metrics around this interval
        3. check if there is any alerts in the last 120 seconds of metric intervals
        """
        self.interval_queue.append(interval)
        # display some stats
        interval.display_stats()

        alert_window_hits = sum([i.hits for i in self.interval_queue])
        alert_dt = pendulum.from_timestamp(interval.end_ts)

        if (alert_window_hits / self.alert_window) > self.avg_hits_threshold:
            self._set_alert(True, alert_dt, alert_window_hits)
        else:
            self._set_alert(False, alert_dt, alert_window_hits)

        # popping off older intervals beyond the alert window to clean up
        num_intervals_lookback = int(self.alert_window / self.refresh_rate)
        if len(self.interval_queue) == num_intervals_lookback:
            self.interval_queue.popleft()

    def _set_alert(self, is_alert_state, alert_dt, alert_window_hits):
        """
        sets monitor alert state
        """
        if self.alert_state == is_alert_state:
            return
        elif self.alert_state is True and is_alert_state is False:
            logging.critical(
                f'Woohoo high traffic alert recovered - hits = {alert_window_hits}, recovered at time={alert_dt}'
            )
            self.alert_state = False
        elif self.alert_state is False and is_alert_state is True:
            logging.critical(
                f'High traffic generated an alert - hits = {alert_window_hits}, triggered at time={alert_dt}'
            )
            self.alert_state = True
            self.latest_alert_timestamp = alert_dt.int_timestamp


import cv2 as cv
from threading import Thread
from reader import video_reader, audio_player

def main():
    try:
        video = Thread(target=video_reader, args=(
            cv.VideoCapture("bad_apple.mp4"), 400, 250))
        audio = Thread(target=audio_player, args=("bad_apple.mp3",))
        video.start()
        audio.start()
        video.join()
        audio.join()
    except Exception as e:
        print("Either the video ends or an error occured: " + str(e))
    finally:
        cv.destroyAllWindows()

if __name__ == "__main__":
    main()


class Solution:
    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:

        if m*k > len(bloomDay):
            return -1

        def linearsearch(bloomDay, k, m):

            answer = []

            cnt = 0
            for i in range(len(bloomDay)-1):
                if bloomDay[i] <= 0:
                    cnt += 1
                if bloomDay[i+1] > 0:
                    answer.append(cnt)
                    cnt = 0
            else:
                if bloomDay[-1] <= 0:
                    answer.append(cnt+1)
                else:
                    answer.append(cnt)

            ans = 0

            for num in answer:
                ans += (num // k)

            return ans >= m

        sorted_bloom = sorted(list(set(bloomDay)))

        left, right = 0, len(sorted_bloom)-1

        while left <= right:
            mid = (left+right) // 2
            bloom = list(map(lambda x: x-sorted_bloom[mid], bloomDay))

            if linearsearch(bloom, k, m):
                right = mid - 1

            else:
                left = mid + 1

        return sorted_bloom[left]

1482. Minimum Number of Days to Make m Bouquets.py


import os
from flask import Flask, request, jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from models import setup_db, Actor, Movie
from auth import AuthError, requires_auth

def create_app(test_config=None):
    app = Flask(__name__)
    setup_db(app)
    # CORS(app)
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE,OPTIONS')
        return response

# -------------------------------------------------------------
# Endpoints
# -------------------------------------------------------------

    # @app.route('/')
    # def index():
    #     return "Welcome to the cast-it agency"

# -----------------------------------
# Movies Endpoints
# -----------------------------------

    # Retrieves list of all movies
    @app.route('/movies', methods=['GET'])
    @requires_auth('get:movies')
    def get_movies(payload):
        movies = Movie.query.all()
        formatted_movies = [movie.format() for movie in movies]
        return jsonify({
            'success': True,
            'movies': formatted_movies
        })

    #Adds a new movie to DB
    @app.route('/movies', methods=['POST'])
    @requires_auth('post:movies')
    def add_movie(payload):
        body = request.get_json()
        title = body.get('title', None)
        release_date = body.get('release_date', None)
        # try:
        entry = Movie(title=title, release_date=release_date)
        entry.insert()
        return jsonify({
            'success': True,
            'movies': entry.format()
        })
        # except:
        #     abort(422)

    @app.route('/movies/<int:movie_id>', methods=['PATCH'])
    @requires_auth('patch:movies')
    def update_movie(payload, movie_id):
        movie = Movie.query.filter(Movie.id == movie_id).one_or_none()
        try:
            if movie is None:
                abort(404)
            else:
                body = request.get_json()
                movie.title = body.get('title', None)
                movie.release_date = body.get('release_date', None)
                movie.update()
                return jsonify({
                'success': True,
                'movieid': movie_id
                }),200
        except:
            abort(422)

    @app.route('/movies/<int:movie_id>', methods=['DELETE'])
    @requires_auth('delete:movies')
    def delete_movie(payload, movie_id):
        movie = Movie.query.filter(Movie.id == movie_id).one_or_none()
        try:
            if movie is None:
                abort(404)
            else:
                movie.delete()
                return jsonify({
                'success': True,
                'movieid': movie_id
                })
        except:
            abort(422)

# -----------------------------------
# Actors Endpoints
# -----------------------------------

    # Retrives list of all actors

    @app.route('/actors', methods=['GET'])
    @requires_auth('get:actors')
    def get_actors(payload):
        actors = Actor.query.all()
        formatted_actors = [actor.format() for actor in actors]
        return jsonify({
        'success': True,
        'actors': formatted_actors
        })

    @app.route('/actors', methods=['POST'])
    @requires_auth('post:actors')
    def add_actor(payload):
        body = request.get_json()
        name = body.get('name', None)
        age = body.get('age', None)
        gender = body.get('gender', None)

        try:
            entry = Actor(name=name, age=age, gender=gender)
            entry.insert()
            return jsonify({
                'success': True,
                'movies': entry.format()
            })
        except:
            abort(422)

    @app.route('/actors/<int:actor_id>', methods=['PATCH'])
    @requires_auth('patch:actors')
    def update_actor(payload, actor_id):
        actor = Actor.query.filter(Actor.id == actor_id).one_or_none()
        try:
            if actor is None:
                abort(404)
            else:
                body = request.get_json()
                actor.name = body.get('name', None)
                actor.age = body.get('age', None)
                actor.gender = body.get('gender', None)
                actor.update()
                return jsonify({
                'success': True,
                'movieid': actor_id
                }),200
        except:
            abort(422)

    @app.route('/actors/<int:actor_id>', methods=['DELETE'])
    @requires_auth('delete:actors')
    def delete_actor(payload, actor_id):
        actor = Actor.query.filter(Actor.id == actor_id).one_or_none()
        try:
            if actor is None:
                abort(404)
            else:
                actor.delete()
                return jsonify({
                'success': True,
                'movieid': actor_id
                })
        except:
            abort(422)

# after_request decorator to set Access-Control-Allow
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return response

# Error Handling
    '''
    Example error handling for unprocessable entity
    '''
    @app.errorhandler(AuthError)
    def handle_auth_error(ex):
        response = jsonify(ex.error)
        response.status_code = ex.status_code
        return response

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    @app.errorhandler(404)
    def resource_not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    @app.errorhandler(500)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 500,
            "message": "Internal Server Error"
        }), 500

    @app.errorhandler(401)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 401,
            "message": "Authorization header is expected"
        }), 401

    @app.errorhandler(403)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 403,
            "message": "forbidden"
        }), 403

    @app.errorhandler(400)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "unprocessable"
        }), 400

    return app

app = create_app()
db = SQLAlchemy(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)


import MySQLdb
import pickle
from sys import argv
"""(('Com_delete', '1'), ('Com_insert', '3'), ('Com_select', '44'), ('Com_update', '1'))"""
qry_exec = """show global status where Variable_name in ("Com_select","Com_Insert", "Com_update","Com_delete");"""
arg_a = int(argv[1])
arg_b = int(argv[2])

def file_picker(req_file):
    return {
        0: '/home/ubuntu/scripts/mysql_query_tracker/delete_db',
        1: '/home/ubuntu/scripts/mysql_query_tracker/insert_db',
        2: '/home/ubuntu/scripts/mysql_query_tracker/select_db',
        3: '/home/ubuntu/scripts/mysql_query_tracker/update_db'
    }.get(req_file)

def wrt_pkle(file_name_write, dump_value):
    with open(file_name_write, 'wb') as FileOpenForWrite:
        pickle.dump(dump_value, FileOpenForWrite)

def read_pkle(file_name_read):
    with open(file_name_read, 'rb') as FileOpenForRead:
        old_stats_val = pickle.load(FileOpenForRead)
    return old_stats_val

def destroy_pkle(file_name_empty):
    open(file_name_empty, 'w').close()

def query_calculator(new_val, old_val):
    cur_stats = int(new_val - old_val)
    return cur_stats

def query_calculator_store(new_val_after_Cal, old_val):
    cur_stats_to_store = new_val_after_Cal + old_val
    return cur_stats_to_store

def con_to_db(exec_query):
    con_db = MySQLdb.connect('localhost', 'root', 'root', 'temp')
    cursor = con_db.cursor()
    cursor.execute(exec_query)
    query_out = cursor.fetchall()
    return query_out

val_stats = con_to_db(qry_exec)
print (arg_a, arg_b)
print (val_stats)
print (val_stats[arg_a][arg_b])
val_stm = int(val_stats[arg_a][arg_b])
file_to_be_access = file_picker(arg_a)
old_stats = read_pkle(file_to_be_access)
new_stats = query_calculator(val_stm, old_stats)
destroy_pkle(file_to_be_access)
new_stats_tobe_stored = query_calculator_store(new_stats,old_stats)
wrt_pkle(file_to_be_access, new_stats_tobe_stored)
print (new_stats)
print (new_stats_tobe_stored)


import sys
from data import Data
from districts import Districts
import statistics

THRESHOLD_NOT_GREEN = 10

def question1(data1):
    print("Question 1:")
    district = Districts(data1)
    district.filter_districts({'S', 'L'})
    district.print_details(["hospitalized_with_symptoms", "intensive_care", "total_hospitalized", "home_insulation"],
                           [statistics.mean, statistics.median])

def question2(data2):
    print("\nQuestion 2:")
    district = Districts(data2)
    district.determine_day_type()
    dictionary = district.get_districts_class()
    count_not_green = 0
    lockdown = "No"
    total_districts = len(dictionary.keys())
    for value in dictionary.values():
        if value == "not green":
            count_not_green += 1
    if count_not_green > THRESHOLD_NOT_GREEN:
        lockdown = "Yes"

    print(f"Number of districts: {total_districts}")
    print(f"Number of not green districts: {count_not_green}")
    print(f"Will a lockdown be forced on whole of Italy?: {lockdown}")

def main(argv):
    data1 = Data(argv[1])
    question1(data1)
    data2 = Data(argv[1])
    question2(data2)

if __name__ == '__main__':
    main(sys.argv)


import json
import time
from gsmmodem.exceptions import CommandError
from twisted.web.resource import Resource

__author__ = 'kbsoft'

from libs import modem_manager

class ModemService(Resource):
    def __init__(self, serviceType):
        Resource.__init__(self)
        self.serviceType = serviceType

    def getChild(self, path, request):
        if path == 'ping':
            return Ping()
        elif path == 'all':
            return ModemsInfo()
        elif path == 'dial':
            return Dial()
            # def render_GET(self, request):
            # pass

class Ping(Resource):
    isLeaf = True

    def render_GET(self, request):
        request.responseHeaders.addRawHeader(b"content-type", b"application/json")
        timestamp = int(time.time())
        live = []
        if len(request.args) != 0 and request.args['fd']:
            modem = modem_manager.modems.get(request.args['fd'][0])
            live = modem.port
        else:
            for modem in modem_manager.modems.itervalues():
                if modem.alive:
                    live.append(modem.port)
        return_value = {
            u'result': u'true',
            u'timestamp': timestamp,
            u'modems_count': modem_manager.modems.count,
            u'live': live,
            u'status': u'pong',
        }

        return json.dumps(return_value)

class ModemsInfo(Resource):
    isLeaf = True

    def render_GET(self, request):
        request.responseHeaders.addRawHeader(b"content-type", b"application/json")
        timestamp = int(time.time())
        modems = []
        failures = 0
        if len(request.args) != 0 and request.args['fd']:
            modem = modem_manager.modems.get(request.args['fd'][0])
            modems = self._modem_to_dict(modem)
            if not modems['alive']:
                failures += 1

        else:
            for modem in modem_manager.modems.itervalues():
                modem_dic = self._modem_to_dict(modem)
                if not modem_dic['alive']:
                    failures += 1
                modems.append(modem_dic)
        return_value = {
            u'result': u'true',
            u'timestamp': timestamp,
            u'modems': modems,
            u'status': u'pong',
            u'failures': failures
        }

        return json.dumps(return_value)

    def _modem_to_dict(self, modem):
        if modem.alive:
            return_value = {
                u'port': modem.port,
                u'baudrate': modem.baudrate,
                u'alive': modem.alive,
                u'imei': modem.imei,
                u'imsi': modem.imsi,
                u'manufacturer': modem.manufacturer,
                u'model': modem.model,
                u'networkName': modem.networkName,
                u'revision': modem.revision,
                u'signalStrength': modem.signalStrength,
                u'smsc': modem.smsc
            }
        else:
            return_value = {
                u'port': modem.port,
                u'baudrate': modem.baudrate,
                u'alive': modem.alive
            }
        return return_value

class Dial(Resource):
    isLeaf = True

    def render_POST(self, request):
        request.responseHeaders.addRawHeader(b"content-type", b"application/json")
        timestamp = int(time.time())
        number = request.args['number'].pop()
        modem = modem_manager.modems.get_random_modem()
        if 'fd' in request.args:
            fd = request.args['fd'].pop()
            modem = modem_manager.modems.get(fd)
        try:
            modem.dial(number)
            return_value = {
                u'result': u'true',
                u'timestamp': timestamp,
                u'status': u'dialed',
                u'fd': modem.port
            }
        except CommandError as error:
            # TODO: Send error exception string
            return_value = {
                u'result': u'false',
                u'timestamp': timestamp,
                u'status': u'fail',
                u'fd': modem.port,
                u'reason': error.message
            }

        return json.dumps(return_value)


import numpy as np
import math
import skued as sk
import random

def iaawt(x, xdist=[], N=1, accerror=.001, error_change=100):

    if len(xdist)==0:
        xdist=x
        print("Taking the dsitribution of x for xdist")

    n = len(x)
    sgates = []

    numlevels = math.floor(math.log(n)/math.log(2))
    count = 0

    # wavelet decomp
    Y = sk.dtcwt(x, 'sym2', 'qshift2', level=numlevels)
    Yl = Y[0]
    Yh = Y[1:len(Y)]

    #  real and amplitudes
    ampYh = []
    phaseYh = []
    for yh in Yh:
        ampYh.append(abs(yh))
        phaseYh.append(np.angle(yh))

    sortval = np.sort(x)
    stdval = np.std(sortval)

    sortval2 = np.sort(xdist)
    stdval2 = np.std(sortval2)

    for k in range(0,N):
        print("surrogate nr. ", k+1)
        z = sortval
        random.shuffle(z)
        z[0] = 0
        Z = sk.dtcwt(z, 'sym2', 'qshift2', level=numlevels)
        Zh = Z[1:len(Z)]
        newphase = []
        for zh in Zh:
            newphase.append(np.angle(zh))

        amperror = [100]
        waverror = [100]
        counter = 0

        newZh = []

        while (amperror[counter] > accerror) & (waverror[counter] > accerror):

                # wavelet construction
                oldz = z
                newZh = [Yl]
                for i in range(0,len(ampYh)):
                  newZh.append(ampYh[i] * np.exp(newphase[i] * 1j))

                z = sk.idtcwt(newZh,'sym2', 'qshift2')
                wavdiff = np.mean(np.mean(abs(z.real - oldz.real)))
                waverror.append(wavdiff/stdval)

                # impose original values
                oldz = z
                data2sort = z[count:n]
                shuffind = np.argsort(data2sort)
                z[shuffind]  =  sortval2
                z[0:count] = 0
                ampdiff =np. mean(np.mean(abs(z.real-oldz.real)))
                amperror.append(ampdiff/stdval2)

                # Wavelet step
                nZ = sk.dtcwt(z, 'sym2', 'qshift2', level=numlevels)
                nZh = nZ[1:len(nZ)]

                # get phases and imag
                newphase = []
                for nzh in nZh:
                    newphase.append(np.angle(nzh))

                toterror = amperror[counter+1] + waverror[counter+1]
                oldtoterr = amperror[counter] + waverror[counter]
                if abs((oldtoterr-toterror)/toterror) < (accerror/error_change):
                    amperror[counter+1] = -1
                    waverror[counter+1] = -1
                counter = counter + 1
                del nZh

        sgates.append(z)

    return sgates


#!/usr/bin/env python
# encoding: utf-8
"""
cheetah.py

Created by Graham Dennis on 2009-02-28.
"""

try:
    from Cheetah.Template import Template
except ImportError:
    Template = None

from waflib import Task, TaskGen

def configure(conf):
    conf.start_msg('Checking for the Cheetah python module')
    if Template:
        conf.end_msg('ok')
    else:
        conf.end_msg('Not found')

class cheetah(Task.Task):
    ext_in  = ['.tmpl']
    ext_out = ['.py']
    vars = ['CHEETAH_SETTINGS']

    def run(self):
        env = self.env
        bld = self.generator.bld

        input_node = self.inputs[0]
        output_node = self.outputs[0]

        compilerSettings = 'CHEETAH_SETTINGS' in env and env['CHEETAH_SETTINGS'] or {}

        basename = input_node.change_ext('').name

        pysrc = Template.compile(
            file = input_node.abspath(),
            compilerSettings = compilerSettings,
            moduleName = basename,
            className = basename,
            returnAClass = False,
        )

        output_node.write(pysrc)
        return 0

@TaskGen.extension('.tmpl')
def cheetah_callback(self, node):
    out = node.change_ext('.py').name
    self.create_task('cheetah', node, node.parent.find_or_declare(out))


import os

import requests
from django.contrib import messages
from django.shortcuts import render, redirect

from order.models import Indent, IndentInventory
from user.models import Address
from .forms import storeForm, dishForm
from .models import Canteen, Store, Dish
from user.models import Manager

# Create your views here.

# 新增商铺
# def is_add_store(request):
#     if request.POST.get('add_store') is not None:
#         print('add_store')
#         return True
#     return False
# 整理菜品列表并输出
def get_order_dish_list(order_id):
    dish_list_ = None
    # 获取订单明细
    if order_id is not None:
        order = Indent.objects.get(indent_id=order_id)
        dish_list_ = IndentInventory.objects.filter(indent=order.indent_id)
        # 整理数据，方便输出
        dish_list = []
        for i in dish_list_:
            dish = {}
            dish['dish_price'] = i.dish.dish_price
            dish['dish_name'] = i.dish.dish_name
            dish['dish_num'] = i.dish_num
            dish_list.append(dish)
        return dish_list
    return None

# 整理菜品列表并输出
def get_dish_list(order_id):
    dish_list_ =None
    # 获取订单明细
    if order_id is not None:
        order = Indent.objects.get(indent_id=order_id)
        dish_list_ = IndentInventory.objects.filter(indent=order.indent_id)
    # 整理数据，方便输出
    dish_list = []
    for i in Dish.objects.all():
        dish = {}
        dish['dish_price'] = i.dish_price
        dish['dish_describe'] = i.dish_describe
        dish['dish_id'] = i.dish_id
        dish['store_id'] = i.store_id.store_id
        dish['dish_name'] = i.dish_name
        dish['dish_image'] = i.dish_image
        dish['get_order_url_add'] = i.get_order_url_add()
        dish['get_order_url_sub'] = i.get_order_url_sub()
        dish['dish_num'] = 0
        if dish_list_ is not None:
            try:
                cur_dish = dish_list_.get(dish_id=i.dish_id)
                dish['dish_num'] = cur_dish.dish_num
            except:
                dish['dish_num'] = 0
        dish_list.append(dish)
    return dish_list

def show_canteen(request):
    # 是否更改状态（只有食堂管理员能更改）
    canteen_id = request.POST.get('canteen_id')     # 选中的食堂
    # 是否更改状态
    if canteen_id is not None:
        user = Manager.objects.get(manager_label=1, manager_id=request.session.get('user_id'))
        # 用户管理的食堂
        canteen = user.manager_canteen
        # 用户只能修改自己管理的食堂
        if int(canteen_id) == canteen.canteen_id:
            pre_state = canteen.canteen_state   # 之前状态
            canteen.canteen_state = '营业中' if pre_state == '休息中' else '休息中'
            canteen.save()
        else:
            messages.warning(request,'管理员只能修改自己管理的食堂！')

    context = {
            'canteen_list': Canteen.objects.all(),
    }
    return render(request, 'canteen/canteen_list.html', context)

def show_store(request):
    # same_name_store = Store.objects.filter(store_name='猪肚鸡')
    # if len(same_name_store)==0:
    #     store = Store(canteen_id=Canteen.objects.get(canteen_id=9), store_name='猪肚鸡',
    #                   store_describe='猪肚包鸡，是一道广东省传统的地方名菜，属于客家菜系，又名猪肚煲鸡、凤凰投胎，流行于广东的深圳、惠州、河源、梅州等粤东一带，是广东客家地区酒席必备的餐前用汤，汤里浓中带清，有浓郁的药材味和胡椒香气。最早是客家女人坐月子时吃的一道菜肴。',
    #                   store_image='D:\hgs-3-1\DB\lab\DB4\img\猪肚鸡店铺.webp', store_state=1)
    #     store.save()
    #     dish = Dish(dish_name='柠檬猪肚鸡', dish_price=16, dish_image='../../../img/柠檬猪肚鸡_malpson.webp', dish_describe='经济实惠',
    #          dish_state=1)
    #     dish.save()
    #     store.dishes.add(dish)
    #     store.save()
    order_show, order = show_cur_order(request)
    # if is_add_store(request):
    #     print('is add')
    #     return redirect('/add_store/')
    context = {
        'canteen_list': Canteen.objects.all(),
        'store_list': Store.objects.all(),
        'order_show':order_show,
        'order':order,
        'order_state':['未下单','已下单','已发货','已送达','已评价'],
        'dish_list_':get_order_dish_list(request.session.get('order_id'))
    }
    # print(Canteen.objects.all()[0].canteen_id)
    # print(Store.objects.all()[0].canteen_id)
    # print(type(Canteen.objects.all()[0].canteen_id))
    # print(type(Store.objects.all()[0].canteen_id.canteen_id))
    # print(Canteen.objects.all()[0].canteen_id==Store.objects.all()[0].canteen_id)
    # print(Store.objects.all()[0].store_image)
    return render(request, 'canteen/store_list.html', context)

def show_dish(request):
    # dish_list = Dish.objects.all()
    # dishes = []
    # for item in dish_list:
    #     dishes.append()
    order_show, order = show_cur_order(request)
    context = {
        'canteen_list':Canteen.objects.all(),
        'store_list': Store.objects.all(),
        'dish_list': get_dish_list(request.session.get('order_id')),
        'order_show':order_show,
        'order':order,
        'order_state':['未下单','已下单','已发货','已送达','已评价'],
        'dish_list_':get_order_dish_list(request.session.get('order_id')),
    }
    if request.method == 'POST':
        dish_name = request.POST.get('dish_name')
        if dish_name is not None:
            try:
                dish = Dish.objects.get(dish_name=dish_name)
                return redirect('/dish/#{}'.format(dish.dish_id))
            except:
                # context['messages']=["该菜品不存在",]
                # return redirect('/dish/#{}'.format(context['dish_list'][0]['dish_id']))
                return redirect('/dish/')
    # print(Dish.objects.all()[0].dish_id)
    print(Store.objects.all())
    # print(dish_list_[0]['dish_id'])
    return render(request,'canteen/dish_list.html', context)

def show_cur_order(request):
    order_show = False
    order = None
    order_id = request.session.get('order_id')
    # dish_list = None
    # 每个菜品数量
    # if order_id is not None:
    #     order = Indent.objects.get(indent_id=order_id)
    #     dish_list = IndentInventory.objects.filter(indent=order.indent_id)

    # 能否获取到地址，能获取到则为下单
    order_address = request.POST.get('select_address')
    if order_address is not None:
        print('selected order_address:', order_address)
        order = Indent.objects.get(indent_id=order_id)
        order.indent_address = Address.objects.get(address_id=int(order_address))
        order.save()
        # 每道菜的数量设未0
        # for i in order.dishes.all():
        #     i.dish_order_num = 0
        #     i.save()
        # for i in dish_list:
        #     i.dish_num = 0
        #     i.save()
        order.indent_state='已下单'
        order.save()
        del request.session['order_id']
        messages.success(request,'下单成功！')
        return False, None

    show = request.POST.get('show')
    # 是否展示订单
    if show is not None:
        order_show = True
    else:
        if request.POST.get('close'):
            order_show = False
    if order_show:
        if not request.session.get('is_login', None) or request.session.get('label') != 0:
            messages.warning(request, "请先登录顾客账户~")
            return False, None
        if not request.session.get('order_id', None):
            messages.warning(request, "暂无订单~")
            return False, None
        order_id = request.session['order_id']
        order = Indent.objects.get(indent_id=order_id)
    return order_show, order

def del_store(request, store_id):
    print('del store:store_id:',store_id)
    Store.objects.get(store_id=store_id).delete()
    return redirect('/store/')

def update_store(request, store_id):
    print('update store:store_id:', store_id)
    print('user_id:',(request.session['user_id']))
    # 如果是商家，则只能修改自己的
    if request.session['label'] == 1:
        try:
            user = Manager.objects.get(manager_label=0,manager_id=request.session['user_id'])
            # print(type(user.manager_store.store_id))
            if user.manager_store.store_id != int(store_id):
                messages.warning(request, '商铺只允许被所属商家或食堂管理员修改！')
                return redirect('/store/')
        except:
            messages.warning(request, '商铺只允许被所属商家或食堂管理员修改！')
            return redirect('/store/')
    request.session['update_store_id'] = store_id
    return redirect('/add_store/')

def add_store(request):
    print('add_store')
    print(request.method)
    update_store_id = request.session.get('update_store_id')

    print('update_store_id:',update_store_id)
    # 判断是更新还是新增
    if update_store_id is not None:
        store = Store.objects.get(store_id=update_store_id)
        store_form = storeForm({
            'store_name':store.store_name,
            'store_des' :store.store_describe,
            'store_state' :store.store_state,
            'store_image' : store.store_image,
            # 'manager_name' = None,
        })
    else:
        store_form = storeForm()
    if request.method == "POST":
        store_form = storeForm(request.POST, request.FILES)    # 将表单用一个类封装起来 # request.POST返回一个字典，get是字典的内置方法
        message = '请检查填写内容！'
        print('store_form valid',store_form.is_valid())
        if store_form.is_valid():
            try:
                # 设置管理商铺的商家

                business = Manager.objects.get(manager_label=0,manager_name=store_form.cleaned_data.get('manager_name'))

            except:
                messages.warning(request,"商家不存在！")
                return render(request, 'canteen/add_store.html', locals())
            # 商铺属性
            name = store_form.cleaned_data.get('store_name')
            des = store_form.cleaned_data.get('store_des')
            image = store_form.cleaned_data.get('store_image')
            state = store_form.cleaned_data.get('store_state')
            # 创建商铺
            print(request.session['user_id'])
            # 是否为新建商铺
            if update_store_id is None:
                store = Store(canteen_id=Manager.objects.get(manager_label=1, manager_id=request.session['user_id']).manager_canteen,)

            store.store_name=name
            store.store_image=image
            store.store_state=state
            store.store_describe=des
            store.save()
            # 商铺与商家绑定
            if update_store_id is None:
                business.manager_store = store
                business.save()
            else:
                del request.session['update_store_id']

            return redirect('/store/')
    return render(request,'canteen/add_store.html',locals())

# 添加或修改菜品，store为要菜品对应的商铺
def add_dish(request, store_id):
    print('add_dish')
    print(request.method)
    update_dish_id = request.session.get('update_dish_id')

    print('update_dish_id:',update_dish_id)
    # 判断是更新还是新增
    if update_dish_id is not None:
        dish = Dish.objects.get(dish_id=update_dish_id)
        dish_form = dishForm({
            'dish_name':dish.dish_name,
            'dish_des' :dish.dish_describe,
            'dish_state' :dish.dish_state,
            'dish_image' : dish.dish_image,
            'dish_price' : dish.dish_price,
        })
    else:
        dish_form = dishForm()
    if request.method == "POST":
        dish_form = dishForm(request.POST, request.FILES)    # 将表单用一个类封装起来 # request.POST返回一个字典，get是字典的内置方法
        message = '请检查填写内容！'
        print('dish_form valid',dish_form.is_valid())
        if dish_form.is_valid():
            # 对应商铺
            print('store_id:',store_id)
            store = Store.objects.get(store_id=store_id)

            # 菜品属性
            name = dish_form.cleaned_data.get('dish_name')
            des = dish_form.cleaned_data.get('dish_des')
            image = dish_form.cleaned_data.get('dish_image')
            state = dish_form.cleaned_data.get('dish_state')
            price = dish_form.cleaned_data.get('dish_price')
            # 创建商铺
            print(request.session['user_id'])
            print('update_dish_id:',update_dish_id)
            # 是否为新建商铺
            if update_dish_id is None:
                dish = Dish(store_id=Store.objects.get(store_id=store_id))

            dish.dish_name=name
            dish.dish_image=image
            dish.dish_state=state
            dish.dish_describe=des
            dish.dish_price = price
            dish.save()
            if update_dish_id is not None:
                del request.session['update_dish_id']

            return redirect('/dish/')

    return render(request,'canteen/add_dish.html',locals())

def del_dish(request, dish_id):
    print('del dish:dish_id:',dish_id)
    dish = Dish.objects.get(dish_id=dish_id)
    # 如果是商家，则只能删除自己的
    if request.session['label'] == 1:
        try:
            user = Manager.objects.get(manager_label=0, manager_id=request.session['user_id'])
            if user.manager_store.store_id != dish.store_id.store_id:
                messages.warning(request, '菜品只允许被所属商家或食堂管理员删除！')
                return redirect('/dish/')
        except:
            messages.warning(request, '商铺只允许被所属商家或食堂管理员删除！')
            return redirect('/dish/')
    dish.delete()
    return redirect('/dish/')

def update_dish(request, dish_id):
    print('update dish:dish_id:', dish_id)
    print('user_id:',(request.session['user_id']))
    dish = Dish.objects.get(dish_id=dish_id)
    # 如果是商家，则只能修改自己的
    if request.session['label'] == 1:
        try:
            user = Manager.objects.get(manager_label=0,manager_id=request.session['user_id'])
            if user.manager_store.store_id != dish.store_id.store_id:
                messages.warning(request, '菜品只允许被所属商家或食堂管理员修改！')
                return redirect('/dish/')
        except:
            messages.warning(request, '菜品只允许被所属商家或食堂管理员修改！')
            return redirect('/dish/')
    request.session['update_dish_id'] = dish_id
    return redirect('/add_dish/{}'.format(dish.store_id.store_id))


x = int(input())
result = []
for i in range(x):
    input()
    start = [int(k) for k in input().split()]
    end = [int(k) for k in input().split()]
    obstacle = [int(k) for k in input().split()]
    if start[0] == end[0] and start[0] == obstacle[0] and (min(start[1], end[1]) < obstacle[1] < max(start[1], end[1])):
        result.append(abs(start[0]-end[0])+abs(start[1]-end[1])+2)
    elif start[1] == end[1] and start[1] == obstacle[1] and (min(start[0], end[0]) < obstacle[0] < max(start[0], end[0])):
        result.append(abs(start[0]-end[0])+abs(start[1]-end[1])+2)
    else:
        result.append(abs(start[0]-end[0])+abs(start[1]-end[1]))

for i in result:
    print(i)


def solution(n, left, right):
    x = []
    l = left//n
    r = right//n
    while l <= r+1:
        x += [l+1]*l + list(range(l+1,n+1))
        l += 1
    st = left%n
    en = st+right-left+1
    return x[st:en]

프로그래머스/lv2/87390. n＾2 배열 자르기/n＾2 배열 자르기.py

n＾2 배열 자르기.py


import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import datetime
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import make_column_transformer, make_column_selector
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GroupShuffleSplit
from tensorflow.keras import callbacks
from tensorflow.keras.callbacks import EarlyStopping
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)

# Carga de datos
logging.info('Loading data...')
visits = pd.read_csv('/content/drive/MyDrive/deep_learning/data/visits/entrenamiento1.csv')
visits_features = visits.copy()

# Conversión de fechas a formato numérico
logging.info('Converting dates to numerical format...')
visits_features['FECHA_ENTRADA_REV'] = pd.to_datetime(visits_features['FECHA_ENTRADA_REV']).astype(int) / 10**9
visits_features['FECHA_SALIDA_REV'] = pd.to_datetime(visits_features['FECHA_SALIDA_REV']).astype(int) / 10**9

# Separación de características y objetivo
logging.info('Separating features and target...')
visits_objective = visits_features.pop('FECHA_SALIDA_REV')

# Codificación de características categóricas
logging.info('Encoding categorical features...')
visits_features_transf = pd.get_dummies(visits_features, columns=['ID_ACCION'])

# Normalización de características numéricas
logging.info('Normalizing numerical features...')
scaler = StandardScaler()
visits_features_transf_fit = scaler.fit_transform(visits_features_transf)

# Definición del modelo
logging.info('Defining model...')
input_shape = [170]
model = tf.keras.Sequential([
    layers.Dense(512, input_shape = input_shape),
    layers.Dense(512, activation='relu'),
    layers.Dense(512, activation='relu'),
    layers.Dense(512, activation='relu'),
    layers.Dense(1)
])

# Compilación del modelo
logging.info('Compiling model...')
model.compile(optimizer='adam', loss='mae')

# Entrenamiento del modelo
logging.info('Training model...')
out = model.fit(visits_features_transf_fit, visits_objective, batch_size=256, epochs=100)

# Análisis del SGD: Gráfica de pérdidas
logging.info('Plotting loss graph...')
history_df = pd.DataFrame(out.history)
history_df.loc[5:, ['loss']].plot();

# Predicciones
logging.info('Making predictions...')
predictions = model.predict(visits_features_transf)
for i in range(len(predictions)):
        a = predictions[i][0]
        b = visits_features_transf.iloc[i]

        difference = a - b
        difference_in_minutes = difference.total_seconds() / 60
        logging.info(f"Prediction: {a}, Actual: {b}, Difference: {difference_in_minutes} minutos")


import torch
import os
from tqdm import tqdm
import torchvision

images = []
files = []
tx = torchvision.transforms.Resize((128, 128))
for f in tqdm(os.listdir("train")):
    img = torchvision.io.read_image("train/" + f)
    images.append(tx(img.float() / 255))
    files.append(f)

torch.save({
    'names': files,
    'images': torch.stack(images),
}, 'data/x_train_resized_normalized.pt')


import matplotlib.pyplot as plt

import xrayutilities as xu

matA = xu.materials.InAs
matB = xu.materials.InP
substrate = xu.materials.Si

alloy = xu.materials.CubicAlloy(matA, matB, 0)

hxrd001 = xu.HXRD([1, 1, 0], [0, 0, 1])
qinp, qout = (3.02829203, 4.28265165)

# draw two relaxation triangles for the given Alloy in the substrate
[qxt0, qzt0] = alloy.RelaxationTriangle([2, 2, 4], substrate, hxrd001)
alloy.x = 1.
[qxt1, qzt1] = alloy.RelaxationTriangle([2, 2, 4], substrate, hxrd001)

plt.figure()
plt.plot(qxt0, qzt0, '-r')
plt.plot(qxt1, qzt1, '-b')
plt.plot(qinp, qout, 'ok')

# print concentration of alloy B calculated from a reciprocal space point
print(alloy.ContentBasym(qinp, qout, [2, 2, 4], [0, 0, 1]))


import pandas as pd
import numpy as np
import os
from roller import Roller
from argparse import ArgumentParser

def main():
    # ------- Parse commandline arguements and Set all necessary variables ---------------- #
    # Working from within the directory where Roller.py is located
    parser = ArgumentParser()

    parser.add_argument("-i","--infile", help="Input excel or pickle file name", type=str)
    parser.add_argument("-o","--outfile", help="Output excel file name", type=str, default="new.xlsx")
    parser.add_argument("-c","--colnames", help="Comma separated list of column names in the input File", type=str)
    parser.add_argument("-a","--column2aggregate", help="Column names in the input Excel File", type=str)
    parser.add_argument("-f","--aggregate_functions", help="Comma delimited list of 2 functions to apply",
                        default="mean,std", type=str)
    parser.add_argument("-r","--rolling_interval", help="Rolling interval to use for aggregation", default=5, type=int)
    parser.add_argument("-s","--insheet", help="Rolling interval to use for aggregation", type=str)

    args = parser.parse_args()

    col_list = [col for col in args.colnames.split(",")]
    aggregate_functions = [function for function in args.aggregate_functions.split(",")]
    outsheeet =  f"edited-{args.insheet}"

    # Check to see if the input file is a pickle or excel file
    ispickle=False if args.infile.endswith("xlsx") else True
    # --- Create a Roller object#
    df = Roller(aggregate_functions, args.column2aggregate, args.rolling_interval,
              args.insheet, outsheeet, args.infile, args.outfile,
              ispickle, header=1, usecols=col_list)

    # Let roll baby
    df.run(True)

if __name__ == "__main__":
    main()


import sys
import math
sys.setrecursionlimit(10000)

N = int(sys.stdin.readline())

def is_prime(num):
    for i in range(2, int(math.sqrt(num) + 1)):
        if num % i == 0:
            return False
    return True

def DFS(number):
    if len(str(number))==N:
        print(number)
    else:
        for i in range(1, 10):
            if i % 2 == 0:
                continue

            if is_prime(number * 10 + i):
                DFS(number * 10 + i)
#N = 2
DFS(2)
#DFS(2) ==> number = 2 ==> len(str(number))=1 != N(2)
#is_prime(2 *10 +1) ==> False
#is_prime(2 *10 +3) == True ==> DFS(2*10 + 3) = DFS(23) ==> len(str(23)) =2 == N ==> print(23)
#is_pime(2 * 10 + 5) == False
#is_pime(2 * 10 + 7) == False
#is_pime(2 * 10 + 9) == True ==> DFS(2*10 + 9) = DFS(29) ==> len(str(29)) =2 == N ==> print(29)
DFS(3)
DFS(5)
DFS(7)
#%%

알고리즘_코테_책/5.탐색/신기한소수.py