# Ingresar por teclado "n" empleados, codigo de 4 digitos, nombre y apellido, calcular el sueldo bruto
# Para el sueldo bruto basico de 80mil, ingresar horas adicionales, precio de esas horas de 3mil

# Función para ingresar los datos de los empleados
def ingresarEmpleados():
    # Declaramos las variables globales para reutilizarlas
    # fuera de esta la funcion
    global listacodigo
    global listanombre
    global listasueldo
    global listahoras

    # Inicializamos las variables
    listacodigo = []
    listanombre = []
    listasueldo = []
    listahoras = []

    sueldo_basico = 80000
    valor_por_hora = 3000

    # Solicitamos al usuario que ingrese los datos de los empleados
    user = "y"
    while user == "y":
        # Hacemos la entrada de datos para agregarselas a las listas
        listacodigo.append(input("Ingrese el codigo del empleado: "))
        print(listacodigo)
        listanombre.append(input("Ingrese el nombre y apellido del empleado: "))
        print(listanombre)
        # Calculamos el sueldo bruto del empleado
        horas = int(input("Ingrese el horas del empleado: "))
        total_sueldo = sueldo_basico + (valor_por_hora * horas)
        listahoras.append(horas)
        print(listahoras)
        listasueldo.append(total_sueldo)
        print(listasueldo)

        # Solicitamos al usuario si desea ingresar otro empleado
        user = input("Desea ingresar un empleado nuevo? y/n: ")

# Función para buscar un empleado por código
def buscarEmpleado():
    # Declaramos las variables donde el usuario va a buscar
    buscar = input("Ingrese el codigo que quiere buscar: ")

    for i in range(len(listacodigo)):
        if buscar == listacodigo[i]:
            # Imprimimos los datos del empleado
            print(listacodigo[i])
            print(listanombre[i])
            print(listasueldo[i])
            print(listahoras[i])


import re

def get_baseform(entry={}, lemgram=''):
    if lemgram:
        return lemgram.split('.')[0]
    elif 'lemgram' in entry:
        return entry['lemgram'].split('.')[0]
    elif len(entry.get('WordForms', [])) > 0:
        return entry['WordForms'][0]['writtenForm']
    return 'default'

def get_pos(lemgram):
    print('get pos', lemgram)
    return re.search('.*\.\.(.*?)\.', lemgram).group(1)

def get_paradigm(entry):
    form = entry.get("FormRepresentations", [{}])[0]
    return form.get("paradigm", "")

def make_overview(obj):
    form = obj["FormRepresentations"][0]
    print('form', form)
    bklass = form.get("bklass", "")
    inherent = form.get("inherent", "")
    base = form.get("baseform", "")
    lemgram = form.get("lemgram", "")
    pos = form.get("partOfSpeech", "")
    paradigm = form.get("paradigm", "")
    fm_paradigm = form.get("fm_paradigm", "")
    out = [lemgram, base, pos, inherent, bklass, fm_paradigm, paradigm]
    fields = ["identifier", "baseform", "partOfSpeech", "inherent", "bklass", "fm_paradigm", "paradigm"]
    return out, fields

def karp_wftableize(paradigm, table, classes={}, baseform='', identifier='',
                   pos='', resource=''):
    " Url table format -> LMF format"
    table = table.split(',')
    obj = {'lexiconName': resource}
    wfs = []
    for l in table:
        if '|' in l:
            form, tag = l.split('|')
        else:
            form = l
            tag = ''
        wfs.append({'writtenForm': form, 'msd': tag})
        if not baseform:
            baseform = form

    obj['WordForms'] = wfs
    form = {}
    form['lemgram'] = identifier
    form['partOfSpeech'] = pos
    form['baseform'] = baseform
    form['paradigm'] = paradigm
    for key, val in classes.items():
        form[key] = val
    obj['FormRepresentations'] = [form]

    return obj

def yield_identifier(baseform, pos):
    for ix in range(1, 101):
        yield '%s..%s.%s' % (baseform, pos, ix)

def show_wordentry(entry):
    " LMF -> MFL format "
    result = {}
    form = entry.get("FormRepresentations", [{}])[0]
    result['bklass'] = form.get("bklass", "")
    result['inherent'] = form.get("inherent", "")
    result['baseform'] = form.get("baseform", "")
    result['identifier'] = form.get("lemgram", "")
    result['partOfSpeech'] = form.get("partOfSpeech", "")
    result['paradigm'] = form.get("paradigm", "")
    result['fm_paradigm'] = form.get("fm_paradigm", "")
    result['WordForms'] = entry.get('WordForms', [])
    return result

def defaulttable(pos):
    lookup = {
        'nn': ["sg indef nom", "sg indef gen", "sg def nom", "sg def gen",
               "pl indef nom", "pl indef gen", "pl def nom", "pl def gen"]
    }
    return lookup.get(pos, [])


import sys

from django.core.management.base import BaseCommand
from django.http import Http404

from health_check.mixins import CheckMixin

class Command(CheckMixin, BaseCommand):
    help = "Run health checks and exit 0 if everything went well."

    def add_arguments(self, parser):
        parser.add_argument("-s", "--subset", type=str, nargs=1)

    def handle(self, *args, **options):
        # perform all checks
        subset = options.get("subset", [])
        subset = subset[0] if subset else None
        try:
            errors = self.check(subset=subset)
        except Http404 as e:
            self.stdout.write(str(e))
            sys.exit(1)

        for plugin_identifier, plugin in self.filter_plugins(subset=subset).items():
            style_func = self.style.SUCCESS if not plugin.errors else self.style.ERROR
            self.stdout.write(
                "{:<24} ... {}\n".format(
                    plugin_identifier, style_func(plugin.pretty_status())
                )
            )

        if errors:
            sys.exit(1)


import pandas as pd
import numpy as np
import string

def stripStr(name):
	return name.rstrip(string.digits)

#read csv file
file = pd.read_csv("./ahs2017n.csv", quotechar = "'")

# Get all the valid column name:
columnNameSet = set()
f = open('./column_name')
for line in f.readlines():
	line = line.strip()
	if len(line) > 3 and line[-3:] == 'XXX':
		columnNameSet.add(line[:-3])
	else:
		columnNameSet.add(line)

#Get all the data with valid column from the csv
columnList = []
for i in range(len(file.columns)):
	if file.columns[i] in columnNameSet or stripStr(file.columns[i]) in columnNameSet:
		columnList.append(file.columns[i])

#replace all the non-applicable data
for j in range(-9, -5):
	file.replace(j, np.nan, inplace = True)

#drop columns where all the values are NaN
df = file[columnList]
df.dropna(axis = 1, how = 'all', thresh = 40051, inplace = True)

#drop columns which only contain 1 unique values. (variance ＝ 0)
df = df[[col for col in df if not df[col].nunique()==1]]

df.to_csv('./cleanData.csv', index = False)

#drop columns with low variance
import pandas
from sklearn.feature_selection import VarianceThreshold
sel =VarianceThreshold(threshold=1)
sel.fit_transform(data)

m=0
for i in sel.get_support(True):
	print(data.columns[i])
	m+=1
print(m)

#use selectFromModel
data=pandas.read_csv('/Users/sherry/Desktop/python/energyProject/cleanData.csv',quotechar="'")
data=data.astype('float64', inplace = True)
data.dropna(inplace=True)

feature = data[[col for col in data.columns if col!="GASAMT"]]
lrModel = LinearRegression()
selectFromModel = SelectFromModel(lrModel)
selectFromModel.fit_transform(feature,data['GASAMT'])

nums = selectFromModel.get_support(True)
lists=[]
for i in nums:
	lists.append(data.columns[i])
print(lists)

#use RFE
import pandas
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression

data=pandas.read_csv('/Users/sherry/Desktop/python/energyProject/cleanData.csv',quotechar="'")
data=data.astype('float64', inplace = True)
data.dropna(inplace=True)
data=data.loc[1:9]

feature =data[['TOTROOMS','TOTHCAMT','PERPOVLVL','DIVISION','BLD','HHMAR','HHAGE','HHGRAD','HHNATVTY']]

rfe =RFE(
    estimator=LinearRegression(),
    n_features_to_select=5
)
sFeature = rfe.fit_transform(
    feature,
    data['ELECAMT']
)

rfe.get_support()


"""
Создать телефонный справочник с возможностью импорта и экспорта данных в формате .txt.
Фамилия, имя, отчество, номер телефона - данные, которые должны находиться в файле.
1. Программа должна выводить данные
2. Программа должна сохранять данные в текстовом файле
3. Пользователь может ввести одну из характеристик для поиска определенной записи (Например имя или фамилию человека)
4. Использование функций. Ваша программа не должна быть линейной
"""

# Задача 38: Дополнить телефонный справочник возможностью изменения и удаления данных.
# Пользователь также может ввести имя или фамилию,
# и Вы должны реализовать функционал для изменения и удаления данных

# data = open('file.txt', 'a') # здесь указываем режим, в котором будем работать
# data.writelines() # разделителей не будет
# data.close()

# path = 'file.txt'
# data = open(path, 'r')
# for line in data:
# print(line)
# data.close()

import subprocess
import os

def selectAllReadPhoneNumber ():
    phoneBook = readData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt')
    for i in phoneBook:
        print (i)
def selectSomethingReadPhoneNumber ():
    print ("Выбран пункт 2")

def readData (fileName):               # чтение файла
    with open (fileName) as f:
        phoneBook = []
        for line in f:
            phoneBook.append(line.split(','))
    return phoneBook

def writeData (fileName, phoneBook):  # добавляем строку в конец файла
    with open (fileName, 'w') as f:
        for i in phoneBook:
            print (i)
            f.write (','.join(i))

        print ("Файл сохранён.")

def addPerson ():             # добавление нового абонента
    phoneBook = readData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt')
    print ("Введи данные:")
    number = str(len(phoneBook) + 1)
    surname = str(input("Введи фамилию: "))
    nameFirst = str(input("Введи имя: "))
    nameSecond = str(input("Введи отчество: "))
    phoneNumber = str(input("Введи номер телефона: "))
    phoneBook.append([number, surname, nameFirst, nameSecond, phoneNumber])
    print (phoneBook)
    writeData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt', phoneBook)

def reWritePerson ():             # добавление нового абонента
    phoneBook = readData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt')
    numberStroki = int(input("Введи номер перезаписываемой строки: "))
    print ("Введи данные:")
    number = str(len(phoneBook))
    surname = str(input("Введи фамилию: "))
    nameFirst = str(input("Введи имя: "))
    nameSecond = str(input("Введи отчество: "))
    phoneNumber = str(input("Введи номер телефона: "))
    phoneBook[numberStroki - 1] = [str(numberStroki), surname, nameFirst, nameSecond, phoneNumber + "\n"]
    print (phoneBook)
    writeData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt', phoneBook)

def delPerson():
    number = int(input("Введи номер удаляемой строки: "))
    phoneBook = readData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt')
    print('Строка "' + str(number) + '" удалена')
    phoneBook.pop(number - 1)
    writeData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt', phoneBook)

def clearConsol():
    subprocess.call('clear' if os.name =='posix' else 'cls', shell=True)    # Очистка консоли
    print ('''ПРИВЕТ, ПОЛЬЗОВАТЕЛЬ
         [1] -- нажми, чтобы ПОКАЗАТЬ ВСЁ
         [2] -- нажми, чтобы ВЫБРАТЬ
         [3] -- нажми, чтобы ДОБАВИТЬ ДАННЫЕ
         [4] -- нажми, чтобы УДАЛИТЬ ДАННЫЕ
         [5] -- нажми, чтобы ИЗМЕНИТЬ ДАННЫЕ''')

clearConsol()

while True:

    enteredNum = int(input())
    # try:
    if (enteredNum == 1):
        clearConsol()
        selectAllReadPhoneNumber()
    elif (enteredNum == 2):
        clearConsol()
        selectSomethingReadPhoneNumber()
        phoneBook = readData('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt')
        phoneBook.append(['5', 'H', 'R', 'T', '123\n'])
        writeData ('C:/Users/sasha/OneDrive/Рабочий стол/Pithon/Урок_8/phonebook.txt', phoneBook)
    elif (enteredNum == 3):
        clearConsol()
        addPerson()
    elif (enteredNum == 4):
        clearConsol()
        selectAllReadPhoneNumber()
        delPerson()
    elif (enteredNum == 5):
        clearConsol()
        selectAllReadPhoneNumber()
        reWritePerson()
    else:
        clearConsol()
        print("Введён неправильный номер. Попробуй снова")
        break
    # except:
    #     print ("You entered something, but it's not number")


#!/usr/bin/env python3
from collections import deque
def main():
    N = int(input())
    g = [[] for _ in range(N)]

    for _ in range(N-1):
        A, B = map(int,input().split())
        A, B = A-1, B-1
        g[A].append(B)
        g[B].append(A)

    colors = [-1] * N
    colors[0] = 0
    q = deque()
    q.append(0)

    while q:
        v = q.popleft()

        for nv in g[v]:
            if colors[nv] != -1:
                continue

            colors[nv] = not colors[v]
            q.append(nv)

    zero, one = [], []
    for idx, itm in enumerate(colors):
        if itm == 0:
            zero.append(idx+1)
        else:
            one.append(idx+1)

        if len(zero) == N//2:
            return zero

        if len(one) == N//2:
            return one

print(*main())


r"""Pipeline for loading VCF files to BigQuery.

Run locally:
python -m gcp_variant_transforms.vcf_to_bq \
  --input_pattern <path to VCF file(s)> \
  --output_table projectname:bigquerydataset.tablename

Run on Dataflow:
python -m gcp_variant_transforms.vcf_to_bq \
  --input_pattern gs://bucket/vcfs/vcffile.vcf \
  --output_table projectname:bigquerydataset.tablename \
  --project projectname \
  --staging_location gs://bucket/staging \
  --temp_location gs://bucket/temp \
  --job_name vcf-to-bq \
  --setup_file ./setup.py \
  --runner DataflowRunner
"""

from __future__ import absolute_import

import argparse  # pylint: disable=unused-import
import logging
import sys
import tempfile
from typing import List, Optional  # pylint: disable=unused-import

import apache_beam as beam
from apache_beam import pvalue  # pylint: disable=unused-import
from apache_beam.io import filesystems
from apache_beam.options import pipeline_options

from gcp_variant_transforms import pipeline_common
from gcp_variant_transforms.beam_io import vcfio
from gcp_variant_transforms.libs import metrics_util
from gcp_variant_transforms.libs import processed_variant
from gcp_variant_transforms.libs import vcf_header_parser
from gcp_variant_transforms.libs import variant_partition
from gcp_variant_transforms.libs.annotation.vep import vep_runner_util
from gcp_variant_transforms.libs.variant_merge import merge_with_non_variants_strategy
from gcp_variant_transforms.libs.variant_merge import move_to_calls_strategy
from gcp_variant_transforms.libs.variant_merge import variant_merge_strategy  # pylint: disable=unused-import
from gcp_variant_transforms.options import variant_transform_options
from gcp_variant_transforms.transforms import annotate_files
from gcp_variant_transforms.transforms import sample_info_to_bigquery
from gcp_variant_transforms.transforms import combine_call_names
from gcp_variant_transforms.transforms import densify_variants
from gcp_variant_transforms.transforms import extract_input_size
from gcp_variant_transforms.transforms import filter_variants
from gcp_variant_transforms.transforms import infer_headers
from gcp_variant_transforms.transforms import merge_headers
from gcp_variant_transforms.transforms import merge_variants
from gcp_variant_transforms.transforms import partition_variants
from gcp_variant_transforms.transforms import variant_to_avro
from gcp_variant_transforms.transforms import variant_to_bigquery
from gcp_variant_transforms.transforms import write_variants_to_shards

_COMMAND_LINE_OPTIONS = [
    variant_transform_options.VcfReadOptions,
    variant_transform_options.AvroWriteOptions,
    variant_transform_options.BigQueryWriteOptions,
    variant_transform_options.AnnotationOptions,
    variant_transform_options.FilterOptions,
    variant_transform_options.MergeOptions,
    variant_transform_options.PartitionOptions,
    variant_transform_options.ExperimentalOptions,
]

_ESTIMATE_SIZES_FILE_NAME = 'estimate-sizes'
_ESTIMATE_SIZES_JOB_NAME = 'estimate-input-size'
_MERGE_HEADERS_FILE_NAME = 'merged_headers.vcf'
_MERGE_HEADERS_JOB_NAME = 'merge-vcf-headers'
_ANNOTATE_FILES_JOB_NAME = 'annotate-files'
_SHARD_VCF_FILES_JOB_NAME = 'shard-files'
_SHARDS_FOLDER = 'shards'
_GCS_RECURSIVE_WILDCARD = '**'

def _read_variants(all_patterns,  # type: List[str]
                   pipeline,  # type: beam.Pipeline
                   known_args,  # type: argparse.Namespace
                   pipeline_mode  # type: int
                  ):
  # type: (...) -> pvalue.PCollection
  """Helper method for returning a PCollection of Variants from VCFs."""
  representative_header_lines = None
  if known_args.representative_header_file:
    representative_header_lines = vcf_header_parser.get_metadata_header_lines(
        known_args.representative_header_file)
  return pipeline_common.read_variants(
      pipeline,
      all_patterns,
      pipeline_mode,
      known_args.allow_malformed_records,
      representative_header_lines,
      vcfio.VcfParserType[known_args.vcf_parser])

def _get_variant_merge_strategy(known_args  # type: argparse.Namespace
                               ):
  # type: (...) -> Optional[variant_merge_strategy.VariantMergeStrategy]
  merge_options = variant_transform_options.MergeOptions
  if (not known_args.variant_merge_strategy or
      known_args.variant_merge_strategy == merge_options.NONE):
    return None
  elif known_args.variant_merge_strategy == merge_options.MOVE_TO_CALLS:
    return move_to_calls_strategy.MoveToCallsStrategy(
        known_args.info_keys_to_move_to_calls_regex,
        known_args.copy_quality_to_calls,
        known_args.copy_filter_to_calls)
  elif (known_args.variant_merge_strategy ==
        merge_options.MERGE_WITH_NON_VARIANTS):
    return merge_with_non_variants_strategy.MergeWithNonVariantsStrategy(
        known_args.info_keys_to_move_to_calls_regex,
        known_args.copy_quality_to_calls,
        known_args.copy_filter_to_calls)
  else:
    raise ValueError('Merge strategy is not supported.')

def _add_inferred_headers(all_patterns,  # type: List[str]
                          pipeline,  # type: beam.Pipeline
                          known_args,  # type: argparse.Namespace
                          merged_header,  # type: pvalue.PCollection
                          pipeline_mode  # type: int
                         ):
  # type: (...) -> pvalue.PCollection
  annotation_fields_to_infer = (known_args.annotation_fields if
                                known_args.infer_annotation_types else [])
  inferred_headers = (
      _read_variants(all_patterns,
                     pipeline,
                     known_args,
                     pipeline_mode)
      | 'FilterVariants' >> filter_variants.FilterVariants(
          reference_names=known_args.reference_names)
      | 'InferHeaderFields' >> infer_headers.InferHeaderFields(
          pvalue.AsSingleton(merged_header),
          known_args.allow_incompatible_records,
          known_args.infer_headers,
          annotation_fields_to_infer))
  merged_header = (
      (inferred_headers, merged_header)
      | 'FlattenHeaders' >> beam.Flatten()
      | 'MergeHeadersFromVcfAndVariants' >> merge_headers.MergeHeaders(
          known_args.split_alternate_allele_info_fields,
          known_args.allow_incompatible_records))
  return merged_header

def _shard_variants(known_args, pipeline_args, pipeline_mode):
  # type: (argparse.Namespace, List[str], int) -> List[str]
  """Reads the variants and writes them to VCF shards.

  Returns:
   The VCF shards directory.
  """
  options = pipeline_options.PipelineOptions(pipeline_args)
  google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions)
  shard_files_job_name = pipeline_common.generate_unique_name(
      _SHARD_VCF_FILES_JOB_NAME)
  _update_google_cloud_job_name(google_cloud_options, shard_files_job_name)
  vcf_shards_output_dir = filesystems.FileSystems.join(
      known_args.annotation_output_dir, _SHARDS_FOLDER)
  with beam.Pipeline(options=options) as p:
    variants = _read_variants(
        known_args.all_patterns, p, known_args, pipeline_mode)
    call_names = (variants
                  | 'CombineCallNames' >>
                  combine_call_names.CallNamesCombiner())
    _ = (variants
         | 'DensifyVariants' >> densify_variants.DensifyVariants(
             beam.pvalue.AsSingleton(call_names))
         | 'WriteToShards' >> write_variants_to_shards.WriteToShards(
             vcf_shards_output_dir,
             beam.pvalue.AsSingleton(call_names),
             known_args.number_of_variants_per_shard))

  return [vep_runner_util.format_dir_path(vcf_shards_output_dir) +
          _GCS_RECURSIVE_WILDCARD]

def _get_input_dimensions(known_args, pipeline_args):
  pipeline_mode = pipeline_common.get_pipeline_mode(
      known_args.all_patterns,
      known_args.optimize_for_large_inputs)
  beam_pipeline_options = pipeline_options.PipelineOptions(pipeline_args)
  google_cloud_options = beam_pipeline_options.view_as(
      pipeline_options.GoogleCloudOptions)

  estimate_sizes_job_name = pipeline_common.generate_unique_name(
      _ESTIMATE_SIZES_JOB_NAME)
  if google_cloud_options.job_name:
    google_cloud_options.job_name += '-' + estimate_sizes_job_name
  else:
    google_cloud_options.job_name = estimate_sizes_job_name
  temp_directory = google_cloud_options.temp_location or tempfile.mkdtemp()
  temp_estimated_input_size_file_name = '-'.join(
      [google_cloud_options.job_name,
       _ESTIMATE_SIZES_FILE_NAME])
  temp_estimated_input_size_file_path = filesystems.FileSystems.join(
      temp_directory, temp_estimated_input_size_file_name)
  with beam.Pipeline(options=beam_pipeline_options) as p:
    estimates = pipeline_common.get_estimates(
        p, pipeline_mode, known_args.all_patterns)

    files_size = (estimates
                  | 'GetFilesSize' >> extract_input_size.GetFilesSize())
    file_count = (estimates
                  | 'CountAllFiles' >> beam.combiners.Count.Globally())
    sample_map = (estimates
                  | 'ExtractSampleMap' >> extract_input_size.GetSampleMap())
    estimated_value_count = (sample_map
                             | extract_input_size.GetEstimatedValueCount())
    estimated_sample_count = (sample_map
                              | extract_input_size.GetEstimatedSampleCount())
    estimated_variant_count = (estimates
                               | 'GetEstimatedVariantCount'
                               >> extract_input_size.GetEstimatedVariantCount())
    _ = (estimated_variant_count
         | beam.ParDo(extract_input_size.print_estimates_to_file,
                      beam.pvalue.AsSingleton(estimated_sample_count),
                      beam.pvalue.AsSingleton(estimated_value_count),
                      beam.pvalue.AsSingleton(files_size),
                      beam.pvalue.AsSingleton(file_count),
                      temp_estimated_input_size_file_path))

  with filesystems.FileSystems.open(temp_estimated_input_size_file_path) as f:
    estimates = f.readlines()
  if len(estimates) != 5:
    raise ValueError('Exactly 5 estimates were expected in {}.'.format(
        temp_estimated_input_size_file_path))

  known_args.estimated_variant_count = int(estimates[0].strip())
  known_args.estimated_sample_count = int(estimates[1].strip())
  known_args.estimated_value_count = int(estimates[2].strip())
  known_args.files_size = int(estimates[3].strip())
  known_args.file_count = int(estimates[4].strip())

def _annotate_vcf_files(all_patterns, known_args, pipeline_args):
  # type: (List[str], argparse.Namespace, List[str]) -> str
  """Annotates the VCF files using VEP.

  Returns:
    The annotated VCF files directory.
  """
  options = pipeline_options.PipelineOptions(pipeline_args)
  google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions)
  annotate_files_job_name = pipeline_common.generate_unique_name(
      _ANNOTATE_FILES_JOB_NAME)
  _update_google_cloud_job_name(google_cloud_options, annotate_files_job_name)

  with beam.Pipeline(options=options) as p:
    _ = (p
         | beam.Create(all_patterns)
         | 'AnnotateShards' >> beam.ParDo(
             annotate_files.AnnotateFile(known_args, pipeline_args)))
  if known_args.annotation_fields:
    known_args.annotation_fields.append(known_args.vep_info_field)
  else:
    known_args.annotation_fields = [known_args.vep_info_field]
  # TODO(bashir2): The VEP runner by default runs VEP with --allele_number hence
  # we turn on this feature here. However, this might be inconsistent with other
  # annotation fields that are originally present in input files, if they do not
  # have ALLELE_NUM annotation. The fix is to make annotation ALT matching
  # smarter to fall back on other matching methods if ALLELE_NUM is not present.
  # When this is implemented, we may even consider removing use_allele_num flag
  # and always start by checking if ALLELE_NUM is present.
  known_args.use_allele_num = True
  return vep_runner_util.get_output_pattern(known_args.annotation_output_dir)

def _update_google_cloud_job_name(google_cloud_options, job_name):
  if google_cloud_options.job_name:
    google_cloud_options.job_name += '-' + job_name
  else:
    google_cloud_options.job_name = job_name

def _merge_headers(known_args, pipeline_args,
                   pipeline_mode, annotated_vcf_pattern=None):
  # type: (str, argparse.Namespace, List[str], int, str) -> None
  """Merges VCF headers using beam based on pipeline_mode."""
  if known_args.representative_header_file:
    return
  options = pipeline_options.PipelineOptions(pipeline_args)

  # Always run pipeline locally if data is small.
  if (pipeline_mode == pipeline_common.PipelineModes.SMALL and
      not known_args.infer_headers and not known_args.infer_annotation_types):
    options.view_as(pipeline_options.StandardOptions).runner = 'DirectRunner'

  google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions)
  merge_headers_job_name = pipeline_common.generate_unique_name(
      _MERGE_HEADERS_JOB_NAME)
  if google_cloud_options.job_name:
    google_cloud_options.job_name += '-' + merge_headers_job_name
  else:
    google_cloud_options.job_name = merge_headers_job_name

  temp_directory = google_cloud_options.temp_location or tempfile.mkdtemp()
  temp_merged_headers_file_name = '-'.join([google_cloud_options.job_name,
                                            _MERGE_HEADERS_FILE_NAME])
  temp_merged_headers_file_path = filesystems.FileSystems.join(
      temp_directory, temp_merged_headers_file_name)

  with beam.Pipeline(options=options) as p:
    headers = pipeline_common.read_headers(
        p, pipeline_mode, known_args.all_patterns)
    merged_header = pipeline_common.get_merged_headers(
        headers,
        known_args.split_alternate_allele_info_fields,
        known_args.allow_incompatible_records)
    if annotated_vcf_pattern:
      merged_header = pipeline_common.add_annotation_headers(
          p, known_args, pipeline_mode, merged_header,
          annotated_vcf_pattern)
    if known_args.infer_headers or known_args.infer_annotation_types:
      infer_headers_input_pattern = (
          [annotated_vcf_pattern] if
          annotated_vcf_pattern else known_args.all_patterns)
      merged_header = _add_inferred_headers(infer_headers_input_pattern, p,
                                            known_args, merged_header,
                                            pipeline_mode)

    pipeline_common.write_headers(merged_header, temp_merged_headers_file_path)
    known_args.representative_header_file = temp_merged_headers_file_path

def _validate_annotation_pipeline_args(known_args, pipeline_args):
  match_results = filesystems.FileSystems.match(['{}*'.format(
      vep_runner_util.format_dir_path(known_args.annotation_output_dir))])
  if match_results and match_results[0].metadata_list:
    raise ValueError('Output directory {} already exists.'.format(
        known_args.annotation_output_dir))

  flags_dict = pipeline_options.PipelineOptions(pipeline_args).get_all_options()
  expected_flags = ['max_num_workers', 'num_workers']
  for flag in expected_flags:
    if flag in flags_dict and flags_dict[flag] > 0:
      return
  raise ValueError('Could not find any of {} with a valid value among pipeline '
                   'flags {}'.format(expected_flags, flags_dict))

def _run_annotation_pipeline(known_args, pipeline_args):
  # type: (argparse.Namespace, List[str]) -> str
  annotated_vcf_pattern = None
  if known_args.run_annotation_pipeline:
    _validate_annotation_pipeline_args(known_args, pipeline_args)
    known_args.omit_empty_sample_calls = True

    files_to_be_annotated = known_args.all_patterns
    if known_args.shard_variants:
      pipeline_mode = pipeline_common.get_pipeline_mode(
          files_to_be_annotated,
          known_args.optimize_for_large_inputs)
      files_to_be_annotated = _shard_variants(known_args,
                                              pipeline_args,
                                              pipeline_mode)
    annotated_vcf_pattern = _annotate_vcf_files(files_to_be_annotated,
                                                known_args,
                                                pipeline_args)
  return annotated_vcf_pattern

def _create_sample_info_table(pipeline,  # type: beam.Pipeline
                              pipeline_mode,  # type: PipelineModes
                              known_args,  # type: argparse.Namespace
                             ):
  # type: (...) -> None
  headers = pipeline_common.read_headers(pipeline,
                                         pipeline_mode,
                                         known_args.all_patterns)
  _ = (headers | 'SampleInfoToBigQuery' >>
       sample_info_to_bigquery.SampleInfoToBigQuery(known_args.output_table,
                                                    known_args.append))

def run(argv=None):
  # type: (List[str]) -> None
  """Runs VCF to BigQuery pipeline."""
  logging.info('Command: %s', ' '.join(argv or sys.argv))
  known_args, pipeline_args = pipeline_common.parse_args(argv,
                                                         _COMMAND_LINE_OPTIONS)

  if known_args.auto_flags_experiment:
    _get_input_dimensions(known_args, pipeline_args)

  annotated_vcf_pattern = _run_annotation_pipeline(known_args, pipeline_args)

  all_patterns = (
      [annotated_vcf_pattern] if annotated_vcf_pattern
      else known_args.all_patterns)

  variant_merger = _get_variant_merge_strategy(known_args)

  pipeline_mode = pipeline_common.get_pipeline_mode(
      all_patterns,
      known_args.optimize_for_large_inputs)
  # Starts a pipeline to merge VCF headers in beam if the total files that
  # match the input pattern exceeds _SMALL_DATA_THRESHOLD
  _merge_headers(known_args, pipeline_args,
                 pipeline_mode, annotated_vcf_pattern)

  # Retrieve merged headers prior to launching the pipeline. This is needed
  # since the BigQuery schema cannot yet be dynamically created based on input.
  # See https://issues.apache.org/jira/browse/BEAM-2801.
  header_fields = vcf_header_parser.get_vcf_headers(
      known_args.representative_header_file)
  counter_factory = metrics_util.CounterFactory()
  processed_variant_factory = processed_variant.ProcessedVariantFactory(
      header_fields,
      known_args.split_alternate_allele_info_fields,
      known_args.allow_malformed_records,
      known_args.annotation_fields,
      known_args.use_allele_num,
      known_args.minimal_vep_alt_matching,
      known_args.infer_annotation_types,
      counter_factory)

  partitioner = None
  if ((known_args.optimize_for_large_inputs and variant_merger) or
      known_args.partition_config_path):
    partitioner = variant_partition.VariantPartition(
        known_args.partition_config_path)

  beam_pipeline_options = pipeline_options.PipelineOptions(pipeline_args)
  pipeline = beam.Pipeline(options=beam_pipeline_options)
  variants = _read_variants(all_patterns, pipeline, known_args, pipeline_mode)
  variants |= 'FilterVariants' >> filter_variants.FilterVariants(
      reference_names=known_args.reference_names)
  if partitioner:
    num_partitions = partitioner.get_num_partitions()
    partitioned_variants = variants | 'PartitionVariants' >> beam.Partition(
        partition_variants.PartitionVariants(partitioner), num_partitions)
    variants = []
    for i in range(num_partitions):
      if partitioner.should_keep_partition(i):
        variants.append(partitioned_variants[i])
      else:
        num_partitions -= 1
  else:
    # By default we don't partition the data, so we have only 1 partition.
    num_partitions = 1
    variants = [variants]

  for i in range(num_partitions):
    if variant_merger:
      variants[i] |= ('MergeVariants' + str(i) >>
                      merge_variants.MergeVariants(variant_merger))
    variants[i] |= (
        'ProcessVariants' + str(i) >>
        beam.Map(processed_variant_factory.create_processed_variant).\
            with_output_types(processed_variant.ProcessedVariant))
  if partitioner and partitioner.should_flatten():
    variants = [variants | 'FlattenPartitions' >> beam.Flatten()]
    num_partitions = 1

  if known_args.output_table:
    for i in range(num_partitions):
      table_suffix = ''
      if partitioner and partitioner.get_partition_name(i):
        table_suffix = '_' + partitioner.get_partition_name(i)
      table_name = known_args.output_table + table_suffix
      _ = (variants[i] | 'VariantToBigQuery' + table_suffix >>
           variant_to_bigquery.VariantToBigQuery(
               table_name,
               header_fields,
               variant_merger,
               processed_variant_factory,
               append=known_args.append,
               update_schema_on_append=known_args.update_schema_on_append,
               allow_incompatible_records=known_args.allow_incompatible_records,
               omit_empty_sample_calls=known_args.omit_empty_sample_calls,
               num_bigquery_write_shards=known_args.num_bigquery_write_shards,
               null_numeric_value_replacement=(
                   known_args.null_numeric_value_replacement)))
      if known_args.generate_sample_info_table:
        _create_sample_info_table(pipeline, pipeline_mode, known_args)

  if known_args.output_avro_path:
    # TODO(bashir2): Add an integration test that outputs to Avro files and
    # also imports to BigQuery. Then import those Avro outputs using the bq
    # tool and verify that the two tables are identical.
    _ = (
        variants | 'FlattenToOnePCollection' >> beam.Flatten()
        | 'VariantToAvro' >>
        variant_to_avro.VariantToAvroFiles(
            known_args.output_avro_path,
            header_fields,
            processed_variant_factory,
            variant_merger=variant_merger,
            allow_incompatible_records=known_args.allow_incompatible_records,
            omit_empty_sample_calls=known_args.omit_empty_sample_calls,
            null_numeric_value_replacement=(
                known_args.null_numeric_value_replacement))
    )

  result = pipeline.run()
  result.wait_until_finish()

  metrics_util.log_all_counters(result)

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  run()


# -*- encoding: utf-8 -*-
import os
from sys import exit

from microservice import create_app
from microservice.config import config_dict

# WARNING: Don't run with debug turned on in production!
DEBUG = (os.getenv('DEBUG', 'False') == 'True')

# The configuration
get_config_mode = 'Debug' if DEBUG else 'Production'

try:

    # Load the configuration using the default values
    app_config = config_dict[get_config_mode.capitalize()]

except KeyError:
    exit('Error: Invalid <config_mode>. Expected values [Debug, Production] ')

app = create_app(app_config)

if DEBUG:
    app.config['TEMPLATES_AUTO_RELOAD'] = True

if __name__ == "__main__":
    app.run()


import sys

input = sys.stdin.read

def cantore(str, n):
    if n == 0:
        print(str)
        return
    cantore(str + " " * len(str) + str, n - 1)

for i in input().split():
    cantore("-", int(i))


from collections import *
def unikati(s):
    t=[]
    for a in s:
        if a not in t:
            t.append(a)
    #print(t)
    return t

def avtor(tvit):
    a = tvit.split(":")
    b = a[0]
    return b

def vsi_avtorji(tviti):
    a=[]
    for n in tviti:
        a.append(avtor(n))
    a = unikati(a)
    return(a)

def izloci_besedo(beseda):
    t = beseda
    t = klic(t)
    t = t[::-1]
    t = klic(t)
    t = t[::-1]
    return t

def klic(t):
    for a in t:
        if a.isalnum() == False:
            t = t.replace(a, "")
        else:
            break
    return t

def se_zacne_z(tvit, c):
    k = tvit.split(" ")
    b=[]
    for a in k:
        #print(a)
        if c in a:
            b.append(izloci_besedo(a))
           # print(b)
    return b

def zberi_se_zacne_z(tviti, c):
    b = []
    for a in tviti:
        #print(a)
        if c in a:
            #print(a)
            b.extend(se_zacne_z(a, c))
           # print(b)
    b = unikati(b)
    #print(b)
    return b

def vse_afne(tviti):
    b = []
    for a in tviti:
        b.extend(se_zacne_z(a, "@"))
    b = unikati(b)
    return b

def vsi_hashtagi(tviti):
    b = []
    for a in tviti:
        b.extend(se_zacne_z(a, "#"))
    b = unikati(b)
    #print(b)
    return b

def vse_osebe(tviti):
     a = vsi_avtorji(tviti)
     a.extend(vse_afne(tviti))
     a = unikati(a)
     a.sort()
     return a

def custva(tviti, hashtagi):
    k  =[]
    for a in hashtagi:
        for b in tviti:
            if a in b:
                k.append(avtor(b))
    k = unikati(k)
    k.sort()
    return k

def se_poznata(tviti, oseba1, oseba2):
    for a in tviti:
        if avtor(a) == oseba1:
            if oseba2 in a and oseba2 in vse_osebe(tviti):
                k = avtor(a)
                print(oseba2, oseba1)
                return True
            else:
                return False

def besedilo(tvit):
    t = tvit
    for a in t:
        if a == " ":
            break
        t = t.lstrip(a)
    return t.lstrip(" ")

def zadnji_tvit(tviti):
    b = {}
    for a in tviti:
        b[avtor(a)] = besedilo(a)
    print(b)
    return b

def prvi_tvit(tviti):
    b = {}
    t = []
    for a in tviti:
        t.append(avtor(a))
        if t.count(avtor(a)) > 1:
            continue
        b[avtor(a)] = besedilo(a)
    return b

def prestej_tvite(tviti):
    b = {}
    t = []
    for a in tviti:
        t.append(avtor(a))
        b[avtor(a)] = t.count(avtor(a))
    #print(b)
    return b

def omembe(tviti):
    b = {}
    t = []
    for a in tviti:
        if avtor(a) in b:
            b[avtor(a)] += se_zacne_z(a, "@")
        else:
            b[avtor(a)] = se_zacne_z(a, "@")
    return b

def neomembe(ime, omembe):
    t = []
    for k in omembe.keys():
        if k not in omembe.get(ime) and ime != k:
            t.append(k)
    return t

import unittest

class TestObvezna(unittest.TestCase):
    maxDiff = 10000

    def test_1_besedilo(self):
        self.assertEqual(besedilo("sandra: Spet ta dež. #dougcajt"),
                         "Spet ta dež. #dougcajt")
        self.assertEqual(besedilo("ana: kdo so te: @berta, @cilka, @dani? #krneki"),
                         "kdo so te: @berta, @cilka, @dani? #krneki")

    def test_2_zadnji_tvit(self):
        self.assertDictEqual(
            zadnji_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"berta": "@sandra Delaj domačo za #programiranje1",
             "sandra": "@berta Ne maram #programiranje1 #krneki",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten",
             "cilka": "@benjamin @ana #split? po dvopičju, za začetek?"})

        self.assertDictEqual(
            zadnji_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "sandra: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "sandra: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten",
             "sandra": "@benjamin @ana #split? po dvopičju, za začetek?"})

        self.assertDictEqual(
            zadnji_tvit(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki"})

        self.assertEqual(zadnji_tvit([]), {})

    def test_3_prvi_tvit(self):
        self.assertDictEqual(
            prvi_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": "Spet ta dež. #dougcajt",
             "berta": "@sandra Delaj domačo za #programiranje1",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "cilka": "jst sm pa #luft",
             "benjamin": "pogrešam ano #zalosten"})

        self.assertDictEqual(
            prvi_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "sandra: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "sandra: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": "Spet ta dež. #dougcajt",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten"})

        self.assertDictEqual(
            prvi_tvit(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki"})

        self.assertEqual(prvi_tvit([]), {})

    def test_4_prestej_tvite(self):
        self.assertDictEqual(
            prestej_tvite([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": 2, "berta": 1, "ana": 1, "cilka": 2, "benjamin": 1})

        self.assertDictEqual(
            prestej_tvite([
                    "sandra: Spet ta dež. #dougcajt",
                    "sandra: @sandra Delaj domačo za #programiranje1",
                    "sandra: @berta Ne maram #programiranje1 #krneki",
                    "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                    "sandra: jst sm pa #luft",
                    "benjamin: pogrešam ano #zalosten",
                    "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": 5, "ana": 1, "benjamin": 1})

        self.assertDictEqual(
            prestej_tvite(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": 1})

        self.assertEqual(prestej_tvite([]), {})

    def test_5_omembe(self):
        self.assertDictEqual(
            omembe(["sandra: Spet ta dež. #dougcajt",
                    "berta: @sandra Delaj domačo za #programiranje1",
                    "sandra: @berta Ne maram #programiranje1 #krneki",
                    "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                    "cilka: jst sm pa #luft",
                    "benjamin: pogrešam ano #zalosten",
                    "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": ["berta", "benjamin", "ana"],
             "benjamin": [],
             "cilka": [],
             "berta": ["sandra"],
             "ana": ["berta", "cilka", "dani"]}
        )

    def test_6_neomembe(self):
        omembe = {"sandra": ["berta", "benjamin", "ana"],
                  "benjamin": [],
                  "cilka": [],
                  "berta": ["sandra"],
                  "ana": ["berta", "cilka", "dani", "benjamin", "sandra"]}

        self.assertEqual(neomembe("sandra", omembe), ["cilka"])
        self.assertEqual(neomembe("ana", omembe), [])
        self.assertEqual(set(neomembe("benjamin", omembe)), set(omembe) - {"benjamin"})

class TestDodatna(unittest.TestCase):
    def test_1_se_poznata(self):
        omembe = {"sandra": ["berta", "benjamin", "ana"],
                  "benjamin": [],
                  "cilka": [],
                  "berta": ["sandra"],
                  "ana": ["berta", "cilka", "dani"]}

        self.assertTrue(se_poznata("ana", "berta", omembe))
        self.assertTrue(se_poznata("berta", "ana", omembe))
        self.assertTrue(se_poznata("sandra", "benjamin", omembe))
        self.assertTrue(se_poznata("benjamin", "sandra", omembe))

        self.assertFalse(se_poznata("benjamin", "ana", omembe))
        self.assertFalse(se_poznata("ana", "benjamin", omembe))

        self.assertFalse(se_poznata("cilka", "dani", omembe))
        self.assertFalse(se_poznata("pavel", "peter", omembe))

    def test_2_hashtagi(self):
        self.assertDictEqual(
            hashtagi(["sandra: Spet ta dež. #dougcajt",
                      "berta: @sandra Delaj domačo za #programiranje1",
                      "sandra: @berta Ne maram #programiranje1 #krneki",
                      "ana: kdo so te @berta, @cilka, @dani? #krneki",
                      "cilka: jst sm pa #luft",
                      "benjamin: pogrešam ano #zalosten",
                      "ema: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {'dougcajt': ['sandra'],
             'krneki': ['ana', 'sandra'],
             'luft': ['cilka'],
             'programiranje1': ['berta', 'sandra'],
             'split': ['ema'],
             'zalosten': ['benjamin']})

if __name__ == "__main__":
    unittest.main()

code/batch-2/dn6 - spet tviti/M-17027-2271.py


# square barrier function
def square_barrier(x, l = 1, h=9, x0 = 4):
    a = x<x0
    b = x>x0+l
    return h*~(a+b)
#def square_barrier(x, l = 1, h=9, x0 = 4):
#    v_x = np.zeros_like(x)
#    for i in range(len(x)):
#        if  x[i]<x0:
#            v_x[i] = 0
#        elif x[i] <= x0+l:
#            v_x[i] = h
#        else:
#            v_x[i] = 0
#    return v_x

# tunnel function
def tunnel_findiff_propagate(x,psi_x,v_x,E):
    dx = x[1]-x[0]
    psi_new = np.copy(psi_x)
    # iterate over 1 to len(x)-1
    for i in range(1, len(x)-1):
        psi_new[i+1] = (2 + 2*(v_x[i] - E)*dx**2)*psi_new[i] - psi_new[i-1]
    # return time-propagated psi
    return psi_new
# initialize variables
dx = 0.01
x = np.arange(0, 10, dx)
energy = 10
psi_x = qw.plane_wave(x, energy)
barrier = square_barrier(x)
# calculate psi_tunnel and the pdf
psi_tunnel = tunnel_findiff_propagate(x, psi_x, barrier, energy)
pdf = qw.prob_density(psi_tunnel)
# plot
plt.plot(x,barrier,label='barrier')
plt.plot(x,psi_tunnel.real,label='real')
plt.plot(x,psi_tunnel.imag,label='imag')
plt.plot(x,pdf,label='pdf')
plt.xlabel('x')
plt.legend()
plt.show()


#Создать калькулятор

def calc(a, b, operation):
    result = "Операция не поддерживается"
    if operation == "+":
        result = a + b
    elif operation == "-":
        result = a - b
    elif operation == "*":
        result = a * b
    elif operation == "/":
        if b != 0:
            result = a / b
        else:
            result = "Делить на 0 нельзя"
    return result

if __name__ == "__main__":
# Чтобы предотвратить запуск кода при импорте модуля нужно писать такую конструкцию
    print(calc(30, 15, "+"))
    print(calc(30, 15, "-"))
    print(calc(20, 5, "*"))
    print(calc(25, 4, "/"))


from django.shortcuts import render, redirect
from .models import League, Team, Player
from django.db.models import Count
from . import team_maker

def index(request):
	context = {
		"baseball": League.objects.filter(sport="Baseball"),
		"women": League.objects.filter(name__contains="Womens'"),
		"hockey": League.objects.filter(sport__contains="Hockey"),
		"not_football": League.objects.exclude(sport="Football"),
		"conferences": League.objects.filter(name__contains="Conference"),
		"atlantic": League.objects.filter(name__contains="Atlantic"),
		"Dallas": Team.objects.filter(location="Dallas"),
		"Raptors": Team.objects.filter(team_name="Raptors"),
		"City": Team.objects.filter(location__contains="City"),
		"starts_with_T": Team.objects.filter(team_name__startswith="T"),
		"teamsAZ": Team.objects.order_by('location'),
		"teamsZA": Team.objects.order_by('-team_name'),
		"cooper": Player.objects.filter(last_name="Cooper"),
		"joshua": Player.objects.filter(first_name="Joshua"),
		"cooper_no_joshua": Player.objects.filter(last_name="Cooper").exclude(first_name="Joshua"),
		"alexander_or_wyatt": Player.objects.filter(first_name="Alexander") | Player.objects.filter(first_name="Wyatt"),
		"ASC": Team.objects.filter(league__name="Atlantic Soccer Conference"),
		"BPplayers": Player.objects.filter(curr_team__team_name="Penguins", curr_team__location="Boston"),
		# "players": Player.objects.filter(curr_team__league__name = 'International Collegiate Baseball Conference'),
		# "players":Player.objects.filter(curr_team__league__name='American Conference of Amateur Football', last_name='Lopez')
					# Player.objects.filter(curr_team__league__sport="Football"),
					# Team.objects.filter(curr_players__first_name="Sophia"),
					# League.objects.filter(teams__curr_players__first_name="Sophia"),
					# Player.objects.filter(last_name="Anderson").exclude(curr_team__location="Phoenix", curr_team__team_name="Rays"),

# Team.objects.filter(all_players__first_name = "Samuel", all_players__last_name="Evans")
# Player.objects.filter(all_teams__location="Manitoba", all_teams__team_name="Tiger-Cats"),
# Player.objects.filter(all_teams__location="Wichita").exclude(curr_team__location="Wichita")
# Team.objects.filter(all_players__first_name="Jacob", all_players__last_name="Gray").exclude(location="Oregon")
# Player.objects.filter(first_name="Joshua", all_teams__league__name="Atlantic Federation of Amateur Baseball Players")
# Team.objects.annotate(num_players=Count('all_players')).filter(num_players__gte=12),
# Player.objects.annotate(num_teams=Count('all_teams')).order_by('num_teams'),
		"leagues": League.objects.all(),
		"teams": Team.objects.all(),
		"players": Player.objects.all(),

	}
	return render(request, "leagues/index.html", context)

def make_data(request):
	team_maker.gen_leagues(10)
	team_maker.gen_teams(50)
	team_maker.gen_players(200)

	return redirect("index")


"""
Card: Atomic Positions

"""

class AtomicPositions:
    """
    ATOMIC_POSITIONS Card

    options:
    alat       : atomic positions are in cartesian coordinates, in
                 units of the lattice parameter (either celldm(1)
                 or A). If no option is specified, 'alat' is assumed;
                 not specifying units is DEPRECATED and will no
                 longer be allowed in the future

    bohr       : atomic positions are in cartesian coordinate,
                 in atomic units (i.e. Bohr radii)

    angstrom   : atomic positions are in cartesian coordinates,
                 in Angstrom

    crystal    : atomic positions are in crystal coordinates, i.e.
                 in relative coordinates of the primitive lattice
                 vectors as defined either in card CELL_PARAMETERS
                 or via the ibrav + celldm / a,b,c... variables

    crystal_sg : atomic positions are in crystal coordinates, i.e.
                 in relative coordinates of the primitive lattice.
                 This option differs from the previous one because
                 in this case only the symmetry inequivalent atoms
                 are given. The variable space_group must indicate
                 the space group number used to find the symmetry
                 equivalent atoms. The other variables that control
                 this option are uniqueb, origin_choice, and
                 rhombohedral.
    """
    options = ("alat", "bhor", "crystal", "crystal_sg", "angstrom")

    def __init__(self):
        self.name = "ATOMIC_POSITIONS"
        self.option = None
        self.atom_positions = []

    def add_atom_position(self, symbol, position, option="alat"):
        """
        Add atom position:
        symbol    (1-2) characters
        position  [x, y, z]
        """
        if len(symbol) > 2:
            error_str = "Chemical Symbol 1-2 Characters [{0}]".format(symbol)
            raise Exception(error_str)

        if not len(position) == 3:
            raise Exception("Must be vector len 3")

        if option not in AtomicPositions.options:
            error_str = "CELL_PARAMETERS {0} not valid option".format(self.option)
            raise Exception(error_str)

        self.option = option
        self.atom_positions.append([symbol, position])

    def validate(self):
        """
        Validate the class ATOMIC_POSITIONS is properly setup
        (to the best of my knowledge)
        """
        if self.option not in AtomicPositions.options:
            error_str = "ATOMIC_POSITIONS {0} not valid (should never happen)".format(self.option)
            raise Exception(error_str)

    def __str__(self):
        import pyqe.config as config

        atomicpositions_str = "{0} ({1})\n".format(self.name, self.option)
        for atom_position in self.atom_positions:
            symbol = atom_position[0]
            position_str = " ".join(map(str, atom_position[1]))
            atomicpositions_str += config.card_space + symbol + " " + position_str + "\n"
        return atomicpositions_str


"""
    EXTERNAL LIBRARIES
"""

import sys
import numpy as np
import random
import matplotlib.pyplot as plt
import math

"""
    INTERNAL UTIL LIBRARIES
"""

# Add parent directory to the sys path
sys.path.append('../')
# Import any python modules from parent directory
from utils.SingleLayerNetwork import SingleLayerNetwork
from utils.auxfunctions import plotModel

"""
    The perceptron learning algorithm is suitable for learning linearly
    separable binary functions of binary inputs and is guaranteed to
    find a solution if the classes are linearly separable.

    Unfortunately, if the classes are not linearly separable, the
    algorithm may not even converge and is unlikely to produce the best
    solution when it does.
"""

class PerceptronLearningNetwork(SingleLayerNetwork):

    def __init__(self, numInputs, numOutputs, randomize=False, bias=False):
        """
            Construct a single-layer neural network given the number of input
            nodes and the number of output nodes. This network will train
            using the perceptron learning algorithm. The activation function
            used in this network will be a linear threshold unit where
            y = -1 if u <= 0
            y = +1 if u > 0     where u is the output of the weighted sum of inputs

            Input, output, and target values are assumed to be +- 1
        """
        # Define activation function
        def ltu(x):
            if x <= 0:
                return -1
            return 1
        # Parameters
        self.bias = bias
        self.activationFunc = ltu
        # Set weights according to randomize parameter
        if bias:
            self.weights = np.zeros((numOutputs, numInputs+1))
        else:
            self.weights = np.zeros((numOutputs, numInputs))
        if randomize:
            for i in range(self.weights.shape[0]):
                for j in range(self.weights.shape[1]):
                    self.weights[i, j] = random.random() * 2.0 - 1.0

    def train(self, x, y, epochs=1, lr=0.1, verbose=True):
        """
            Train the network given a batch of inputs, x, and their corresponding
            target outputs, y. Run the perceptron learning algorithm on the training
            set for the number of times specified by the epochs parameter.
        """
        numTrainingPoints = len(x)
        for e in range(epochs):
            # Set accuracy at beginning of epoch to 0s
            accuracy = 0
            # Compute the output for all training points
            allOutputs = self.evaluate(x)
            for i in range(numTrainingPoints):
                # Grab the inputs for the specific training point
                trainingPointInputs = x[i]
                # Grab the output for the specific training point
                trainingPointOutput = allOutputs[i]
                # Get the target outputs for the specific training point
                targets = y[i]
                # Compare each output 1 by 1
                for outputIndex in range(len(trainingPointOutput)):
                    # Grab specific output and corresponding target value
                    targetVal = targets[outputIndex]
                    outputVal = trainingPointOutput[outputIndex]
                    # If the outputs match, increment accuracy
                    if targetVal == outputVal:
                        accuracy += 1
                        continue
                    # Else, update the weights
                    else:
                        # For each input weight, compute its delta change, and then apply the change
                        for inputWeightIndex in range(len(self.weights[outputIndex])):
                            # If the inputWeightIndex is in the range of values for inputs, use the input at that index
                            if inputWeightIndex < len(trainingPointInputs):
                                trainingPointInput = trainingPointInputs[inputWeightIndex]
                            # Else, that value is the bias, and the input should be constant 1.0
                            else:
                                trainingPointInput = 1.0
                            # Compute delta w and apply the change
                            deltaW = 2.0 * lr * targetVal * trainingPointInput
                            self.weights[outputIndex, inputWeightIndex] += deltaW
            # Compute accuracy
            accuracy /= numTrainingPoints
            # If verbose == True, print accuracy for each training epoch
            if verbose:
                print('Epoch ' + str(e+1) + ' / ' + str(epochs) + ' Accuracy: ' + str(accuracy))
            # Return final accuracy
        return accuracy

# Test the network's learning capabilities
if __name__ == '__main__':
    """"
        Test the network on the AND and XOR Boolean functions. Show training
        progress in graphs.
    """
    # Params
    EPOCHS = 10
    NUM_GRAPHS = 10

    NUM_EPOCHS_PER_GRAPH = math.ceil(EPOCHS / NUM_GRAPHS)
    # Create AND training data
    and_train_x = np.array([
        [-1, -1],
        [-1, 1],
        [1, -1],
        [1, 1]
    ])
    and_train_y = np.array([
        [-1],
        [-1],
        [-1],
        [1]
    ])
    # Create XOR training data
    xor_train_x = np.array([
        [-1, -1],
        [-1, 1],
        [1, -1],
        [1, 1]
    ])
    xor_train_y = np.array([
        [-1],
        [1],
        [1],
        [-1]
    ])
    # Create networks
    and_pln = PerceptronLearningNetwork(2, 1, randomize=True, bias=True)
    xor_pln = PerceptronLearningNetwork(2, 1, randomize=True, bias=True)

    # Create the suplots
    fig, axes = plt.subplots(2, NUM_GRAPHS)
    fig.suptitle('Perceptron Learning Algorithm Training on AND and XOR Boolean Functions',
                 fontsize=18)

    # Label the subplots
    for x in range(2):
        for y in range(1, NUM_GRAPHS+1):
            if x == 0:
                axes[x][y-1].set_title('XOR Model at\n' + str(y * int(NUM_EPOCHS_PER_GRAPH)) + ' Epochs')
            else:
                axes[x][y-1].set_title('AND Model at\n' + str(y * int(NUM_EPOCHS_PER_GRAPH)) + ' Epochs')

    # Train each model on their respective datasets and show progress in the form
    # of decision boundaries for every N epochs
    for i in range(NUM_GRAPHS):
        # Train each model for N more epochs
        xor_pln.train(xor_train_x, xor_train_y, epochs=NUM_EPOCHS_PER_GRAPH, lr=0.05, verbose=False)
        and_pln.train(and_train_x, and_train_y, epochs=NUM_EPOCHS_PER_GRAPH, lr=0.05, verbose=False)

        # Plot the model
        plotModel(xor_pln, axes[0, i], [-1.2, 1.2, -1.2, 1.2], [-1.0, 1.0])
        axes[0, i].set_xlim(-1.2, 1.2)
        axes[0, i].set_ylim(-1.2, 1.2)
        axes[0, i].set_aspect('equal', adjustable='box')

        plotModel(and_pln, axes[1, i], [-1.2, 1.2, -1.2, 1.2], [-1.0, 1.0])
        axes[1, i].set_xlim(-1.2, 1.2)
        axes[1, i].set_ylim(-1.2, 1.2)
        axes[1, i].set_aspect('equal', adjustable='box')

        # Plot the actual data for each model
        axes[0, i].scatter([-1, 1], [1, -1], c='blue', s=150)
        axes[0, i].scatter([-1, 1], [-1, 1], c='red', s=150)

        axes[1, i].scatter([1], [1], c='blue', s=150)
        axes[1, i].scatter([-1, -1, 1], [-1, 1, -1], c='red', s=150)

    # Plot the graph
    figManager = plt.get_current_fig_manager()
    figManager.window.showMaximized()
    plt.show()

    """
        14 of the 16 Boolean functions are linearly separable.
        Let's show all of them and how Single-Layer Networks perform when
        using the Perceptron Learning Algorithm.
    """
    # Params
    EPOCHS_PER_MODEL = 20

    # Define class to hold info about each Boolean function
    class BooleanFunction:
        def __init__(self, true_x, false_x, name):
            self.true_x = true_x
            self.false_x = false_x
            self.name = name

        def getTrainingData(self):
            training_x = []
            training_y = []
            for pair in self.true_x:
                training_x.append(pair)
                training_y.append([1])
            for pair in self.false_x:
                training_x.append(pair)
                training_y.append([-1])
            return np.array(training_x), np.array(training_y)

    # Define each of the 16 boolean functions
    functions = []
    functions.append(
        BooleanFunction(
            [],
            [[-1, -1], [-1, 1], [1, -1], [1,1]],
            'FALSE'
        )
    )
    functions.append(
        BooleanFunction(
            [[1, 1]],
            [[-1, -1], [-1, 1], [1, -1]],
            'AND'
        )
    )
    functions.append(
        BooleanFunction(
            [[1, -1]],
            [[-1, -1], [-1, 1], [1, 1]],
            'A AND NOT B'
        )
    )
    functions.append(
        BooleanFunction(
            [[1, -1], [1, 1]],
            [[-1, -1], [-1, 1]],
            'A'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, 1]],
            [[-1, -1], [1, -1], [1, 1]],
            'NOT A AND B'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, 1], [1, 1]],
            [[-1, -1], [1, -1]],
            'B'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, 1], [1, -1]],
            [[-1, -1], [1, 1]],
            'XOR'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, 1], [1, -1], [1, 1]],
            [[-1, -1]],
            'OR'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1]],
            [[-1, 1], [1, -1], [1, 1]],
            'NOR'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [1, 1]],
            [[-1, 1], [1, -1]],
            'XNOR'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [1, -1]],
            [[-1, 1], [1, 1]],
            'NOT B'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [1, -1], [1, 1]],
            [[-1, 1]],
            'A OR NOT B'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [-1, 1]],
            [[1, -1], [1, 1]],
            'NOT A'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [-1, 1], [1, 1]],
            [[1, -1]],
            'NOT A OR B'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [-1, 1], [1, -1]],
            [[1, 1]],
            'NAND'
        )
    )
    functions.append(
        BooleanFunction(
            [[-1, -1], [-1, 1], [1, -1], [1, 1]],
            [],
            'TRUE'
        )
    )

    # Create the pyplot
    fig, axes = plt.subplots(2, 8)
    fig.suptitle('14 of 16 Boolean functions are linearly separable.\n' +
                'These graphs display decision boundaries formed by training\n' +
                'Single-Layer Networks using Perceptron Learning Algorithm.',
                fontsize=14)

    # Print out a warning to user that this may take a while, but progress will be output below
    print('\n\nWARNING: This may take a while. Progress will be output below:\n\n')

    # Create models for each of the functions, and plot the trained models
    f, x, y = 0, 0, 0
    for function in functions:
        # Create Single Layer Network
        model = PerceptronLearningNetwork(2, 1, randomize=True, bias=True)

        # Train the model on its dataset
        training_x, training_y = function.getTrainingData()
        model.train(training_x, training_y, epochs=EPOCHS_PER_MODEL, lr=0.5, verbose=False)

        # Print progress
        print('PROGRESS: ' + str(f+1) + ' / 16')

        # Plot the trained model in the appropriate subplot
        plotModel(model, axes[x, y], [-1.2, 1.2, -1.2, 1.2], valRange=[-1.0, 1.0])
        axes[x, y].set_xlim(-1.2, 1.2)
        axes[x, y].set_ylim(-1.2, 1.2)
        axes[x, y].set_aspect('equal', adjustable='box')
        axes[x, y].set_title(function.name)

        # Plot the points in the dataset
        for pair in function.true_x:
            axes[x, y].scatter(pair[0], pair[1], color='blue', s=150)
        for pair in function.false_x:
            axes[x, y].scatter(pair[0], pair[1], color='red', s=150)

        # Increment the trackers
        f += 1
        x += 1
        if x >= 2:
            x = 0
            y += 1

    # Plot the graph
    figManager = plt.get_current_fig_manager()
    figManager.window.showMaximized()
    plt.show()

3. Single-Layer Networks/3.4 Learning Rules for Single-Layer Networks/PerceptronLearningAlgorithm.py


a = str(input('Enter chars: ')).split(' ')
d = dict()
r = list()
n = 0
for i in a :
    if i in d :
        d[i] += 1
        n = d[i]
        r.append(i + '_' + str(n))
    else :
        d[i] = 1
        r.append(i)
print(' '.join(r))


from PyQt5.QtWidgets import QGraphicsRectItem, QGraphicsScene
from PyQt5.QtGui import QColor

class BlockDiagram(QGraphicsScene):
    def __init__(self, blocks, block_labels, title):
        super(BlockDiagram, self).__init__()
        self.blocks = blocks
        self.block_labels = block_labels
        self.title = title

        self.scene = QGraphicsScene()
        self.scene.setSceneRect(0, 0, 750, 700)

    def add_tree_items(self, block_type): # switch colour depending on type (expeneses / income)
        for it in self.blocks: # loop through dict list
            # Construct a square object
            rect = QGraphicsRectItem(it["x"], it["y"], it["dx"], it["dy"])

            if block_type == "income":
                rect.setBrush(QColor.fromRgb(97, 247, 255))

            elif block_type == "expenses":
                rect.setBrush(QColor.fromRgb(255, 105, 97))

            self.scene.addItem(rect)

        return self.scene


from dcore._dispatcher import mpi
from .worker_base import SumkDFTWorkerBase, setup_sk

class SumkDFTWorkerSpaghettis(SumkDFTWorkerBase):
    """For computing Spaghettis"""
    def __init__(self, model_hdf5_file, input_file, output_file) -> None:
        super().__init__(model_hdf5_file, input_file, output_file)

    def run(self):
        from dcore.sumkdft_post import SumkDFTDCorePost
        sk = SumkDFTDCorePost(hdf_file=self.model_hdf5_file, use_dft_blocks=False, h_field=0.0,
                              bands_data=self.params['bands_data'])
        setup_sk(sk, 'w', self.params)
        results = {}
        results['akw'] = sk.spaghettis(broadening=self.params['broadening'],
            plot_range=None, ishell=None, save_to_file=None)

        if mpi.is_master_node():
            self.save_result(results)


import logging
import sys
from constants import *
from common import c_word_w, c_nof_complex, ceil_pow2, ceil_log2
from base_object import BaseObject
from numpy import mod

logger = logging.getLogger('main.periph.field')

class Field(BaseObject):
    """ A field defines data at certain address or an array of addresses
    """
    def __init__(self, name, settings=None):
        super().__init__()

        self.name(name)

        # self._valid_keys = ['width', 'bit_offset', 'access_mode', 'side_effect', 'address_offset', 'number_of_fields',
                            # 'reset_value', 'software_value', 'radix', 'field_description', 'field_name', 'default', 'user_width']
        self._valid_dict = {'width':{'max':32, 'min':1}, 'bit_offset':{'max':UNASSIGNED_BIT,'min':0}, 'access_mode':{}, 'interface':{}, 'side_effect':{},'address_offset': {'max':16384,'min':0, 'word_aligned':True},
                            'number_of_fields':{'max':262144,'min':'1'},'reset_value':{'max':131071},'software_value':{},'radix':{},'field_description':{},'field_name':{},'user_width':{'max':2048,'min':32}}
        self._args.update({'width'            : DEFAULT_WIDTH,
                           'bit_offset'       : DEFAULT_BIT_OFFSET,
                           'access_mode'      : DEFAULT_ACCESS_MODE,
                           'side_effect'      : DEFAULT_SIDE_EFFECT,
                           'address_offset'   : DEFAULT_ADDRESS_OFFSET,
                           'number_of_fields' : DEFAULT_NUMBER_OF_FIELDS,
                           'reset_value'      : RESET_VALUE,
                           'software_value'   : DEFAULT_SOFTWARE_VALUE,
                           'radix'            : DEFAULT_RADIX,
                           'field_description': DEFAULT_DESCRIPTION,
                           'interface'        : DEFAULT_INTERFACE,
                           'group_name'       : None})

        if settings is not None:
            # print(name)
            # print(settings)
            for key, val in settings.items():
                if key in self._valid_dict.keys(): #self._valid_keys:

                    if key == 'access_mode' and val.upper() not in VALID_ACCESS_MODES:
                        logger.error("Field.__init__(), Not a valid acces_mode '%s'", val)
                        self.success = False
                    elif key == 'side_effect' and val.upper() not in VALID_SIDE_EFFECTS:
                        logger.error("Field.__init__(), Not a valid side_effect '%s'", val)
                        self.success = False
                    else:
                        self.set_kv(key, val)
                else:
                    logger.error("Field.__init__(), Not a valid key '%s'", key)
                    self.success = False

    def __lt__(self, other):
        return self.address_offset() < other.address_offset()

    def number_of_fields(self, val=None):
        """ set/get number of fields """
        if val is not None:
            self.set_kv('number_of_fields', val)
            return
        return self._as_int('number_of_fields')

    def group_name(self, val=None):
        """ set/get group name """
        if val is not None:
            self.set_kv('group_name', val)
            return
        return self._as_str('group_name')

    def width(self, val=None):
        """ set/get width of field
        val: if not None set width of field
        return: actual width of field """
        if val is not None:
            return self.set_kv('width', val)
        _val = self._as_int('width')

        if not self.is_valid('width'):
            return None

        return self._as_int('width')

    def bit_offset(self, val=None):
        """ set/get bit_offset of field
        val: if not None set bit_offset of field
        return: actual bit_offset of field """
        if val is not None:
            return self.set_kv('bit_offset', val)
        if not self.is_valid('bit_offset'):
            return None
        return self._as_int('bit_offset')

    def access_mode(self, val=None):
        """ set/get access_mode of field
        val: if not None and a valid mode set access_mode of field
        return: actual access_mode of field """
        if val is not None:
            if val.upper() in VALID_ACCESS_MODES:
                return self.set_kv('access_mode', val.upper())
            else:
                logger.error("unknown access_mode '%s'", val)
                self.success = False
                return False
        return self._as_str('access_mode').upper()

    def side_effect(self, val=None):
        """ set/get side_effect of field
        val: if not None and a valid side_effect set side_effect of field
        return: actual side_effect of field """
        if val is not None:
            if val.upper() != 'NONE':
                vals = val.split(',')
                for _val in vals:
                    _val = _val.strip()
                    if _val.upper() not in VALID_SIDE_EFFECTS:
                        logger.error("unknown side_effect '%s'", _val)
                        self.success = False
                        return False
                return self.set_kv('side_effect', val.upper())
        return self._as_str('side_effect').upper()

    def address_offset(self, val=None):
        """ set/get address offset of field
        val: if not None set address offset of field
        return: actual address offset of field """
        if val is not None:
            return self.set_kv('address_offset', val)
        if not self.is_valid('address_offset'):
            return None
        return self._as_int('address_offset')

    def reset_value(self, val=None):
        """ set/get default hardware reset value of field
        val: if not None set default value of field
        return: active hardware reset value of field """
        if val is not None:
            return self.set_kv('reset_value', val)
        if not self.is_valid('reset_value'):
            return None
        return self._as_int('reset_value')

    def software_value(self, val=None):
        """ set/get software reset value of field
        val: if not None set default value of field
        return: active software reset value of field """
        if val is not None:
            return self.set_kv('software_value', val)
        if not self.is_valid('software_value'):
            return None
        return self._as_int('software_value')

    def radix(self, val=None):
        """ set/get radix value of field
        val: if not None set default value of field
        return: active radix value of field """
        if val is not None:
            if val.upper() in VALID_RADIXS:
                return self.set_kv('radix', val.upper())
            else:
                logger.error("unknown radix '%s'", val)
                self.success = False
                return False
        return self._as_int('radix')

    def field_description(self, val=None):
        """ set/get description of field
        val: if not None set description of field
        return: description of field """
        if val is not None:
            return self.set_kv('field_description', val)
        return self._as_str('field_description')

    def user_width(self, val=None):
        """ set/get width of RAM MM bus side interface  """
        if val is not None:
            self.set_kv('user_width', val)
            return
        return self._as_int('user_width', default=32)

    def interface(self, val=None):
        """ interface is used for rams to select between simple addr/data and full AXI4 """
        if val is not None:
            self.set_kv('interface', val)
            return
        return self._as_str('interface')

    def base_address(self, val = None):
        if val is not None:
            if mod(val, WIDTH_IN_BYTES):  # don't need check here if tool calcs are correct
                logger.error("Base address for field {} is not word aligned".format(field.name()))
            self.set_kv('base_addr', val)
            return
        return self._as_int('base_addr', default=0)

    def is_valid(self, yaml_key):
        """ Check value falls within min max range for keys that are ints """
        min = self._valid_dict[yaml_key].get('min', None)
        max = self._valid_dict[yaml_key].get('max', None)
        check_alignment = self._valid_dict[yaml_key].get('word_aligned', False)

        if yaml_key in ['software_value','reset_value']:
            min =  0
            max = int(1<<self._args.get('width', 32))-1

        _val = self._as_int(yaml_key)
        if not isinstance(_val, int):
            return True # may not have been evaluated from parameter yet, skip

        if check_alignment:
            if mod(_val, WIDTH_IN_BYTES):
                logger.error("Address offset for field {} is not word aligned".format(self.name()))
                sys.exit()

        if min is not None:
            if _val < min:
                logger.error("Field '{}': Value {} for '{}' key is outside of supported range, min is {}. Value reset to None".format(self.name(), _val, yaml_key, min))
                return False
        if max is not None:
            if _val > max:
                logger.error("Field '{}': Value {} for '{}' key is outside of supported range, max is {}. Value reset to None".format(self.name(), _val, yaml_key, max))
                return False
        return True

    # TODO: calc size in bytes
    # def get_byte_size(self):

    #def address_length(self, val=None):
    #    """ set/get address length of field
    #    val: if not None set address length of field
    #    return: active address_length of field """
    #    if val is not None:
    #        return self.set_kv('address_length', val)
    #    return self._as_int('address_length')


# This was one of my first interactions with tensorflow.
# You can find quite similar implementation in the official docs of Tensorflow docs.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("../MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])

# weights and biases for the first layer
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# predicteed value of y
y = tf.nn.softmax(tf.matmul(x, W) + b)

# actual value of y
y_ = tf.placeholder(tf.float32, [None, 10])

# Determining the loss of our model by using cross entropy
cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y) )

# Training our model with backprop and gradient descent optimizer
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# Initialize our variables
init = tf.global_variables_initializer()

# Calculating how many correct predictions
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

# converting bool array to float and calculating accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Start our session
with tf.Session() as sess:
	sess.run(init)

	for i in range(1000):
		batch_xs, batch_ys = mnist.train.next_batch(100)
		sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
		if i % 100 == 0:
			print("Batch Number {}: Accuracy {}".format(i, 100*sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})))

	print("Final Accuracy : ", end="")
	print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


from fastapi import APIRouter, Depends
from starlette import status

from app.db.base import customers_collection, favourite_books_collection
from app.models.customers import CustomerModel
from app.utils.utils import get_current_active_user, get_error_response

router = APIRouter(
    prefix="/customer",
    tags=["Customer"],
    responses={404: {
        "description": "Not found"
    }},
)

@router.get('/customer-list')
async def customer_list(user: object = Depends(get_current_active_user)):
    find_query = {
        "is_deleted": False
    }
    if user is None:
        return get_error_response("Unauthorized",
                                  status.HTTP_401_UNAUTHORIZED)
    customers_list = list(customers_collection.find(find_query))
    customers = [CustomerModel(**x).customer_list_response() for x in customers_list]
    response = {
        "customers": customers
    }
    return response

@router.get('/customers-with-favorite-books')
async def get_customers_with_favourite_books_count(user: object = Depends(get_current_active_user)):
    find_query = {
        "is_deleted": False
    }
    customers_list = list(customers_collection.find(find_query))

    favourite_books = list(favourite_books_collection.find())
    customers_response_list = []
    for customer in customers_list:
        favourite_book = next((a.get("favourite_books_list") for a in favourite_books
                               if a.get('customer_id') == customer.get('_id')), None)
        customer_response = CustomerModel(**customer).customer_list_response()
        customer_response['favourite_book_count'] = 0
        if favourite_book is not None:
            customer_response['favourite_book_count'] = len(favourite_book.split(','))
        customers_response_list.append(customer_response)
    response = {
        "customer_response": customers_response_list
    }
    return response


"""Traffic Evader config"""

WIDTH = 960
HEIGHT = 540
FPS = 60
INITIAL_SPEED = 3
LANE_SWITCH_SPEED = 1

LEVELS = {
    "easy": {
        "lanes": 5,
        "lane_width": 90,
        "player": {
            "init_x": WIDTH // 2 - 40,
            "init_lane": 3
        }
    },
    "normal": {
        "lanes": 4,
        "lane_width": 112,
        "player": {
            "init_x": WIDTH // 2 - 95,
            "init_lane": 2
        }
    },
    "hard": {
        "lanes": 3,
        "lane_width": 150,
        "player": {
            "init_x": WIDTH // 2 - 40,
            "init_lane": 2
        }
    }
}

CARS_OBSTACLES = {
    "low": [
        "chrysler-pt-cruiser-gt.png",
        "fiat-multipla.png",
        "lada-1200-vaz-2101.png",
        "peugeot-307.png",
        "pontiac-aztek.png",
        "renault-kadjar.png",
        "toyota-prius.png",
    ],
    "medium": [
        "aston-martin-vantage.png",
        "bmw-1-series.png",
        "bmw-m3.png",
        "chevrolet-camaro.png",
        "mercedes-amg-gt-r.png",
    ],
    "high": [
        "rolls-royce-spectre.png",
        "bugatti-chiron.png",
        "ferrari-daytona-sp3.png",
        "lamborghini-aventador-svj.png",
        "lexus-lfa.png",
        "porsche-911-gt3-rs.png"
    ]
}


# Using While Loop
n = input("") #input() function takes input as string type

n = int(n) # convert it to integer type
fact = 1
i = 1
while i <= n :
    fact = fact * i
    i += 1
print(fact)

#Using For Loop
n = int(input())

fact = 1
for i in range(1,n+1):
    fact = fact * i
print(fact)

#Using Lambda Function
n = int(input())
def shortfact(x):
    return 1 if x <= 1 else x*shortfact(x-1)
print(shortfact(n))

#Using reduce
from functools import reduce

def fun(acc, item):
    return acc*item

num = int(input())
print(reduce(fun,range(1, num+1), 1))

#Reduce how work

#The reduce function is used to perform a specific operation on a sequence of values.
#  In this case, it will be used to multiply all the numbers from 1 to num together to calculate the factorial.

#A custom function fun is defined, which will be used as the operation to apply to the values in the sequence.
#  This function takes two arguments, acc (short for "accumulator") and item. It returns the product of acc and item, which effectively accumulates the product of all the items in the sequence.

#The reduce function is called as follows:

print(reduce(fun, range(1, num + 1), 1))
#reduce takes three arguments:
#The first argument is the function (fun) to apply cumulatively to the items in the sequence.
#The second argument is the sequence itself, which is generated using range(1, num + 1). This creates a sequence of numbers from 1 to num.
#The third argument is the initial value for the accumulator, which is set to 1. This is the starting point for the multiplication.
#The reduce function then performs the following operations:

#Initially, acc is set to 1 (the initial value), and item is set to the first element of the sequence (1).
#It applies the fun function to these values, so acc becomes 1 * 1 = 1.
#Then, acc is set to 1 (the result of the previous step) and item is set to the next element in the sequence (2).
#This process continues, accumulating the product of the numbers from 1 to num through the fun function.
#The result is printed using print, which will be the factorial of the input num.