import logging
import datetime
import pytz
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from ssd.dashboard.models import Event
from ssd.dashboard.forms import SearchForm, GSearchForm

# Get an instance of the ssd logger
logger = logging.getLogger(__name__)

def graph(request):
    """Event Search View (Graph)

    Show events for a specific date, when clicked through from the summary graph

    """

    logger.debug('%s view being executed.' % 'search.gsearch')

    form = GSearchForm(request.GET)
    logger.debug('Form submit (GET): %s, with result: %s' % ('GSearchForm',form))

    if form.is_valid():
        # Obtain the cleaned data (only validate the dates)
        date = form.cleaned_data['date']
        type = form.cleaned_data['type']
        page = form.cleaned_data['page']

        # Combine the dates and times into datetime objects
        start = datetime.datetime.combine(date, datetime.datetime.strptime('00:00:00','%H:%M:%S').time())
        end = datetime.datetime.combine(date, datetime.datetime.strptime('23:59:59','%H:%M:%S').time())

        # Set the timezone
        tz = pytz.timezone(request.timezone)
        start = tz.localize(start)
        end = tz.localize(end)

        results_all = Event.objects.filter(type__type=type,start__range=[start,end]
                                          ).values('id','type__type','start','description','status__status'
                                          ).order_by('-start')

        # Create a paginator and paginate the list w/ 10 messages per page
        paginator = Paginator(results_all, 10)

        # Paginate them
        try:
            results = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, or is not given deliver first page.
            results = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            results = paginator.page(paginator.num_pages)

        # Put together the query params
        query_params = 'date=%s&type=%s' % (date,type)

        # Print the page
        return render_to_response(
           'search/graph.html',
           {
              'title':'System Status Dashboard | Graph Search',
              'results':results,
              'type':type,
              'date':date,
              'query_params':query_params
           },
           context_instance=RequestContext(request)
        )

    # Invalid form
    else:
        messages.add_message(request, messages.ERROR, 'Invalid graph search query')
        return HttpResponseRedirect('/')

def events(request):
    """Event List View

    Show a listing of all events

    """

    logger.debug('%s view being executed.' % 'search.events')

    form = SearchForm(request.GET)
    logger.debug('Form submit (GET): %s, with result: %s' % ('SearchForm',form))

    # Check the params
    if form.is_valid():

        page = form.cleaned_data['page']
        start = form.cleaned_data['start']
        end = form.cleaned_data['end']
        text = form.cleaned_data['text']
        type = form.cleaned_data['type']

        # Build the filter for the search query
        filter = {}

        # Start/End
        if start and end:
            # Combine the dates and times into datetime objects
            start_tmp = datetime.datetime.combine(start, datetime.datetime.strptime('00:00:00','%H:%M:%S').time())
            end_tmp = datetime.datetime.combine(end, datetime.datetime.strptime('23:59:59','%H:%M:%S').time())

            # Set the timezone
            tz = pytz.timezone(request.timezone)
            start_tmp = tz.localize(start_tmp)
            end_tmp = tz.localize(end_tmp)

            filter['start__range'] = [start_tmp,end_tmp]

        # Type
        if type:
            filter['type__type'] = '%s' % type

        # Text
        if text:
            filter['description__contains'] = '%s' % text

        # Obtain filtered incidents
        if filter:
            events_all = Event.objects.filter(**filter).values('id','status__status','type__type','start','end','description').order_by('-id')

        # Obtain all incidents
        else:
            events_all = Event.objects.values('id','status__status','type__type','start','end','description').order_by('-id')

        # Create a paginator and paginate the list w/ 10 messages per page
        paginator = Paginator(events_all, 10)

        # Paginate them
        try:
            events = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, or is not given deliver first page.
            events = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            events = paginator.page(paginator.num_pages)

        # Put together the query params
        query_params = None
        if start and end:
            query_params = 'start=%s&end=%s' % (start,end)

        if text:
            if query_params:
                query_params += '&text=%s' % text
            else:
                query_params = 'text=%s' % text

        if type:
            if query_params:
                query_params += '&type=%s' % type
            else:
                query_params = 'type=%s' % type

        # Print the page
        return render_to_response(
           'search/events.html',
           {
              'title':'System Status Dashboard | Events Search',
              'events':events,
              'page':page,
              'start':start,
              'end':end,
              'text':text,
              'type':type,
              'query_params':query_params
           },
           context_instance=RequestContext(request)
        )

    # Invalid form
    else:

        # Print the page
        return render_to_response(
           'search/events.html',
           {
              'title':'System Status Dashboard | Events Search',
              'form':form,
           },
           context_instance=RequestContext(request)
        )


import numpy as np
import pytest
import nibabel as nb
from nitransforms.linear import Affine
from sdcflows.utils.tools import brain_masker, deoblique_and_zooms

def test_epi_mask(tmpdir, testdata_dir):
    """Check mask algorithm."""
    tmpdir.chdir()
    mask = brain_masker(testdata_dir / "epi.nii.gz")[-1]
    assert abs(np.asanyarray(nb.load(mask).dataobj).sum() - 166476) < 10

@pytest.mark.parametrize("padding", [0, 1, 4])
@pytest.mark.parametrize("factor", [1, 4, 0.8])
@pytest.mark.parametrize("centered", [True, False])
@pytest.mark.parametrize(
    "rotate",
    [
        np.eye(4),
        # Rotate 90 degrees around x-axis
        np.array([[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1]]),
        # Rotate 30 degrees around x-axis
        nb.affines.from_matvec(
            nb.eulerangles.euler2mat(0, 0, 30 * np.pi / 180),
            (0, 0, 0),
        ),
        # Rotate 48 degrees around y-axis and translation
        nb.affines.from_matvec(
            nb.eulerangles.euler2mat(0, 48 * np.pi / 180, 0),
            (2.0, 1.2, 0.7),
        ),
    ],
)
def test_deoblique_and_zooms(tmpdir, padding, factor, centered, rotate, debug=False):
    """Check deoblique and denser."""
    tmpdir.chdir()

    # Generate an example reference image
    ref_shape = (80, 128, 160) if factor < 1 else (20, 32, 40)
    ref_data = np.zeros(ref_shape, dtype=np.float32)
    ref_data[1:-2, 10:-11, 1:-2] = 1
    ref_affine = np.diag([2.0, 1.25, 1.0, 1.0])
    ref_zooms = nb.affines.voxel_sizes(ref_affine)
    if centered:
        ref_affine[:3, 3] -= nb.affines.apply_affine(
            ref_affine,
            0.5 * (np.array(ref_data.shape) - 1),
        )
    ref_img = nb.Nifti1Image(ref_data, ref_affine)
    ref_img.header.set_qform(ref_affine, 1)
    ref_img.header.set_sform(ref_affine, 0)

    # Generate an example oblique image
    mov_affine = rotate @ ref_affine
    mov_img = nb.Nifti1Image(ref_data, mov_affine)
    mov_img.header.set_qform(mov_affine, 1)
    mov_img.header.set_sform(mov_affine, 0)

    # Call function with default parameters
    out_img = deoblique_and_zooms(ref_img, mov_img, padding=padding, factor=factor)

    # Check output shape and zooms
    assert np.allclose(out_img.header.get_zooms()[:3], ref_zooms / factor)

    # Check idempotency with a lot of tolerance
    ref_resampled = Affine(reference=out_img).apply(ref_img, order=0)
    ref_back = Affine(reference=ref_img).apply(ref_resampled, order=0)
    resampled = Affine(reference=out_img).apply(mov_img, order=2)
    if debug:
        ref_img.to_filename("reference.nii.gz")
        ref_back.to_filename("reference_back.nii.gz")
        ref_resampled.to_filename("reference_resampled.nii.gz")
        mov_img.to_filename("moving.nii.gz")
        resampled.to_filename("resampled.nii.gz")

    # Allow up to 3% pixels wrong after up(down)sampling and walk back.
    assert (
        np.abs(np.clip(ref_back.get_fdata(), 0, 1) - ref_data).sum()
        < ref_data.size * 0.03
    )

    vox_vol_out = np.prod(out_img.header.get_zooms())
    vox_vol_mov = np.prod(mov_img.header.get_zooms())
    vol_factor = vox_vol_out / vox_vol_mov

    ref_volume = ref_data.sum()
    res_volume = np.clip(resampled.get_fdata(), 0, 1).sum() * vol_factor
    # Tolerate up to 2% variation of the volume of the moving image
    assert abs(1 - res_volume / ref_volume) < 0.02


from load_data import load_data

def data_analysis():
    data = load_data()
    print(data)
    data_types = data.dtypes
    #checking the null values
    data_null_values = data.isnull().sum()
    print(data_null_values)
    print(data_types)
    return data
data_analysis()


from functools import reduce

import sympy
from jax import Array
from typing import Callable

import itertools
import jax
import jax.numpy as jnp

import original.slimplectic_GGL
from .ggl import ggl, dereduce
from sympy import Symbol, Float, Expr, S

from .discretise_integral import discretise_integral

from .helpers import jax_enable_x64

jax_enable_x64()

t_sym = Symbol('t')
ddt = Float(1)
q1 = Symbol('q')
qdot_1 = Symbol('qdot_1')

def compute_qidot_values(qi_vec, r):
    _, ws, dij = dereduce(ggl(r), dt=1)

    jax_value = jnp.dot(
        ws,
        jax.numpy.matmul(dij, qi_vec)
    )

    expr, table = original.slimplectic_GGL.GGL_Gen_Ld(
        tsymbol=t_sym,
        q_list=[q1],
        qprime_list=[qdot_1],
        ddt=ddt,
        r=r,
        L=qdot_1
    )

    sympy_value = float(expr.subs([
        (table[0][i], qi_vec[i])
        for i in range(len(table[0]))
    ]))

    return sympy_value, jax_value

def test_qidot_derivative_calculations():
    """
    Tests that the qi_dot values calculated by sympy and jax are the same for different values of r.

    This test uses 20 random vectors to ensure that the test is not passing by chance so may not be repeatable.
    """
    for (i, r) in itertools.product(range(20), range(10)):
        random_vec = jax.random.normal(
            key=jax.random.PRNGKey(i),
            shape=(r + 2,)
        )

        sympy_value, jax_value = compute_qidot_values(random_vec, r)

        assert jnp.allclose(
            jax_value,
            sympy_value
        )

def sympy_discretise_integral(
        r: int,
        dt: float,
        dof: int,
        expr_builder: Callable[[list[Symbol], list[Symbol], Symbol], Expr],
):
    q_list = [Symbol(f'q{i}') for i in range(dof)]
    qprime_list = [Symbol(f'qdot{i}') for i in range(dof)]
    t_symbol = Symbol('t')

    expr, table = original.slimplectic_GGL.GGL_Gen_Ld(
        tsymbol=t_symbol,
        q_list=q_list,
        qprime_list=qprime_list,
        r=r,
        ddt=Float(dt),
        L=expr_builder(q_list, qprime_list, t_symbol)
    )

    def fn(q_vec: Array, _t: float = 0):
        # TODO: Test time dependence.
        assert q_vec.shape == (dof, r + 2)

        subs_list = []
        for i in range(len(table)):
            for j in range(len(table[0])):
                subs_list.append([table[i][j], q_vec.tolist()[i][j]])

        return float(expr.subs(subs_list))

    return fn

def test_discretise_integral():
    dt = 0.1

    for (random_key, dof, r) in itertools.product(range(5), range(5), range(5)):
        random_qi = jax.random.normal(
            key=jax.random.PRNGKey(0),
            shape=(dof, r + 2)
        )

        sympy_result = sympy_discretise_integral(
            r=r,
            dt=dt,
            dof=dof,

            # |q|^2 + |q_prime|^2
            expr_builder=lambda q_list, qprime_list, t_symbol: (
                    reduce(lambda sum, c: sum + c ** 2, q_list, S.Zero) +
                    reduce(lambda sum, c: sum + c ** 2, qprime_list, S.Zero)
            )
        )(random_qi)

        jax_result = discretise_integral(
            r=r,
            dt=dt,
            fn=lambda q_vec, q_dot_vec, t: jnp.dot(q_vec, q_vec) + jnp.dot(q_dot_vec, q_dot_vec)
        )[0](
            random_qi.transpose(),
            t0=0
        )

        assert jnp.allclose(sympy_result, jax_result)


from unittest.mock import MagicMock, patch

import pytest
import source_bing_ads
from airbyte_cdk.models import SyncMode
from airbyte_cdk.utils import AirbyteTracedException
from bingads.service_info import SERVICE_INFO_DICT_V13
from source_bing_ads.base_streams import Accounts, AdGroups, Ads, Campaigns
from source_bing_ads.source import SourceBingAds

@patch.object(source_bing_ads.source, "Client")
def test_streams_config_based(mocked_client, config):
    streams = SourceBingAds().streams(config)
    assert len(streams) == 60

@patch.object(source_bing_ads.source, "Client")
def test_source_check_connection_ok(mocked_client, config, logger_mock):
    with patch.object(Accounts, "read_records", return_value=iter([{"Id": 180519267}, {"Id": 180278106}])):
        assert SourceBingAds().check_connection(logger_mock, config=config) == (True, None)

@patch.object(source_bing_ads.source, "Client")
def test_source_check_connection_failed_user_do_not_have_accounts(mocked_client, config, logger_mock):
    with patch.object(Accounts, "read_records", return_value=[]):
        connected, reason = SourceBingAds().check_connection(logger_mock, config=config)
        assert connected is False
        assert (
            reason.message == "Config validation error: You don't have accounts assigned to this user. Please verify your developer token."
        )

def test_source_check_connection_failed_invalid_creds(config, logger_mock):
    with patch.object(Accounts, "read_records", return_value=[]):
        connected, reason = SourceBingAds().check_connection(logger_mock, config=config)
        assert connected is False
        assert (
            reason.internal_message
            == "Failed to get OAuth access token by refresh token. The user could not be authenticated as the grant is expired. The user must sign in again."
        )

@patch.object(source_bing_ads.source, "Client")
def test_validate_custom_reposts(mocked_client, config_with_custom_reports, logger_mock):
    reporting_service_mock = MagicMock()
    reporting_service_mock._get_service_info_dict.return_value = SERVICE_INFO_DICT_V13
    mocked_client.get_service.return_value = reporting_service_mock
    mocked_client.environment = "production"
    res = SourceBingAds().validate_custom_reposts(config=config_with_custom_reports, client=mocked_client)
    assert res is None

@patch.object(source_bing_ads.source, "Client")
def test_validate_custom_reposts_failed_invalid_report_columns(mocked_client, config_with_custom_reports, logger_mock):
    reporting_service_mock = MagicMock()
    reporting_service_mock._get_service_info_dict.return_value = SERVICE_INFO_DICT_V13
    mocked_client.get_service.return_value = reporting_service_mock
    mocked_client.environment = "production"
    config_with_custom_reports["custom_reports"][0]["report_columns"] = ["TimePeriod", "NonExistingColumn", "ConversionRate"]

    with pytest.raises(AirbyteTracedException) as e:
        SourceBingAds().validate_custom_reposts(config=config_with_custom_reports, client=mocked_client)
    assert e.value.internal_message == (
        "my test custom report: Reporting Columns are invalid. "
        "Columns that you provided don't belong to Reporting Data Object Columns:"
        " ['TimePeriod', 'NonExistingColumn', 'ConversionRate']. "
        "Please ensure it is correct in Bing Ads Docs."
    )
    assert (
        "Config validation error: my test custom report: Reporting Columns are "
        "invalid. Columns that you provided don't belong to Reporting Data Object "
        "Columns: ['TimePeriod', 'NonExistingColumn', 'ConversionRate']. Please "
        "ensure it is correct in Bing Ads Docs."
    ) in e.value.message

@patch.object(source_bing_ads.source, "Client")
def test_get_custom_reports(mocked_client, config_with_custom_reports):
    custom_reports = SourceBingAds().get_custom_reports(config_with_custom_reports, mocked_client)
    assert isinstance(custom_reports, list)
    assert custom_reports[0].report_name == "DSAAutoTargetPerformanceReport"
    assert custom_reports[0].report_aggregation == "Weekly"
    assert "AccountId" in custom_reports[0].custom_report_columns

def test_clear_reporting_object_name():
    reporting_object = SourceBingAds()._clear_reporting_object_name("DSAAutoTargetPerformanceReportRequest")
    assert reporting_object == "DSAAutoTargetPerformanceReport"
    reporting_object = SourceBingAds()._clear_reporting_object_name("DSAAutoTargetPerformanceReport")
    assert reporting_object == "DSAAutoTargetPerformanceReport"

@patch.object(source_bing_ads.source, "Client")
def test_campaigns_request_params(mocked_client, config):

    campaigns = Campaigns(mocked_client, config)

    request_params = campaigns.request_params(stream_slice={"account_id": "account_id"})
    assert request_params == {
        "AccountId": "account_id",
        "CampaignType": "Audience DynamicSearchAds Search Shopping",
        "ReturnAdditionalFields": "AdScheduleUseSearcherTimeZone BidStrategyId CpvCpmBiddingScheme DynamicDescriptionSetting DynamicFeedSetting MaxConversionValueBiddingScheme MultimediaAdsBidAdjustment TargetImpressionShareBiddingScheme TargetSetting VerifiedTrackingSetting",
    }

@patch.object(source_bing_ads.source, "Client")
def test_campaigns_stream_slices(mocked_client, config):

    campaigns = Campaigns(mocked_client, config)
    accounts_read_records = iter([{"Id": 180519267, "ParentCustomerId": 100}, {"Id": 180278106, "ParentCustomerId": 200}])
    with patch.object(Accounts, "read_records", return_value=accounts_read_records):
        slices = campaigns.stream_slices()
        assert list(slices) == [
            {"account_id": 180519267, "customer_id": 100},
            {"account_id": 180278106, "customer_id": 200},
        ]

@patch.object(source_bing_ads.source, "Client")
def test_adgroups_stream_slices(mocked_client, config):

    adgroups = AdGroups(mocked_client, config)
    accounts_read_records = iter([{"Id": 180519267, "ParentCustomerId": 100}, {"Id": 180278106, "ParentCustomerId": 200}])
    campaigns_read_records = [iter([{"Id": 11}, {"Id": 22}]), iter([{"Id": 55}, {"Id": 66}])]
    with patch.object(Accounts, "read_records", return_value=accounts_read_records):
        with patch.object(Campaigns, "read_records", side_effect=campaigns_read_records):
            slices = adgroups.stream_slices()
            assert list(slices) == [
                {"campaign_id": 11, "account_id": 180519267, "customer_id": 100},
                {"campaign_id": 22, "account_id": 180519267, "customer_id": 100},
                {"campaign_id": 55, "account_id": 180278106, "customer_id": 200},
                {"campaign_id": 66, "account_id": 180278106, "customer_id": 200},
            ]

@patch.object(source_bing_ads.source, "Client")
def test_ads_request_params(mocked_client, config):

    ads = Ads(mocked_client, config)

    request_params = ads.request_params(stream_slice={"ad_group_id": "ad_group_id"})
    assert request_params == {
        "AdGroupId": "ad_group_id",
        "AdTypes": {
            "AdType": ["Text", "Image", "Product", "AppInstall", "ExpandedText", "DynamicSearch", "ResponsiveAd", "ResponsiveSearch"]
        },
        "ReturnAdditionalFields": "ImpressionTrackingUrls Videos LongHeadlines",
    }

@patch.object(source_bing_ads.source, "Client")
def test_ads_stream_slices(mocked_client, config):

    ads = Ads(mocked_client, config)

    with patch.object(
        AdGroups,
        "stream_slices",
        return_value=iter([{"account_id": 180519267, "customer_id": 100}, {"account_id": 180278106, "customer_id": 200}]),
    ):
        with patch.object(AdGroups, "read_records", side_effect=[iter([{"Id": 11}, {"Id": 22}]), iter([{"Id": 55}, {"Id": 66}])]):
            slices = ads.stream_slices()
            assert list(slices) == [
                {"ad_group_id": 11, "account_id": 180519267, "customer_id": 100},
                {"ad_group_id": 22, "account_id": 180519267, "customer_id": 100},
                {"ad_group_id": 55, "account_id": 180278106, "customer_id": 200},
                {"ad_group_id": 66, "account_id": 180278106, "customer_id": 200},
            ]

@pytest.mark.parametrize(
    ("stream", "stream_slice"),
    (
        (Accounts, {}),
        (AdGroups, {"campaign_id": "campaign_id"}),
        (Ads, {"ad_group_id": "ad_group_id"}),
        (Campaigns, {"account_id": "account_id"}),
    ),
)
@patch.object(source_bing_ads.source, "Client")
def test_streams_full_refresh(mocked_client, config, stream, stream_slice):
    stream_instance = stream(mocked_client, config)
    _ = list(stream_instance.read_records(SyncMode.full_refresh, stream_slice))
    mocked_client.request.assert_called_once()

@patch.object(source_bing_ads.source, "Client")
def test_transform(mocked_client, config):
    record = {"AdFormatPreference": "All", "DevicePreference": 0, "EditorialStatus": "ActiveLimited", "FinalAppUrls": None}
    transformed_record = Ads(mocked_client, config).transform(
        record=record, stream_slice={"ad_group_id": 90909090, "account_id": 909090, "customer_id": 9090909}
    )
    assert transformed_record == {
        "AccountId": 909090,
        "AdFormatPreference": "All",
        "AdGroupId": 90909090,
        "CustomerId": 9090909,
        "DevicePreference": 0,
        "EditorialStatus": "ActiveLimited",
        "FinalAppUrls": None,
    }


#!/usr/bin/python3
"""Printing a square"""

class Square:
    """Private instance attribute: size"""
    def __init__(self, size=0):
        """Function constructor"""
        if isinstance(size, int) is False:
            raise TypeError("size must be an integer")
        if size < 0:
            raise ValueError("size must be >= 0")
        self.__size = size

    def area(self):
        """Public instance method that returns the current square area"""
        return self.__size * self.__size

    @property
    def size(self):
        """Public instance method Get that returns the current value of size"""
        return self.__size

    @size.setter
    def size(self, value):
        """Public instance method set that validate an change the current
        value of size
        """
        if isinstance(value, int) is False:
            raise TypeError("size must be an integer")
        if value < 0:
            raise ValueError("size must be >= 0")
        self.__size = value

    def my_print(self):
        """Public instance method that prints in stdout the square with the
        character #
        """
        character = '#'
        if self.__size == 0:
            print()
        else:
            for row in range(self.__size):
                for column in range(self.__size):
                    print(character, end='')
                print()


#!/usr/bin/env python3

from flask import Blueprint,request,render_template,redirect,session
from src.models.model import User
import os,time

UPLOAD_FOLDER = '/Users/jacoblucas/insta'

controller = Blueprint('private',__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

tm = time.time()

@controller.route('/upload',methods=['GET','POST'])
def post():
	if request.method == 'GET':
		return render_template('test_post.html')
	elif request.method == 'POST':
		if session:
			username = session['username']
			caption = request.form['caption']

			target = os.path.join(APP_ROOT, '../static')

			for file in request.files.getlist('file'):
				filename = file.filename
				print(filename)
				destination = '/'.join([target, filename])
				file.save(destination)

				if User(username).post(tm,filename,caption):
					return redirect('/')

@controller.route('/repost',methods=['POST'])
def repost():
	if request.method == 'GET':
		pass
	elif request.method == 'POST':
		if session:
			username = session['username']
			post_id = request.form['post_id']
			if User(username).repost(post_id,tm):
				return redirect('/')
		else:
			return redirect('/login')

@controller.route('/logout')
def logout():
	session.pop('username')
	return redirect('/')


from CandidateApp.models import CandidatePost
from django.shortcuts import redirect,render
from django.contrib import messages

def StaffCandCampaign(request):
    if request.session['Staffloginidpk']:
        if request.method=='POST':
            if 'candidatePostSubmit' in request.POST:
                ID=request.POST['candidatePostid']
                request.session['StaffCandidatePostView12']=ID
                return redirect("StaffCandidatePostView")
        obj=CandidatePost.objects.all()
        if obj:
            obj=obj.values()
            obj=  [obj[i:i+3] for i in range(0,len(obj),3)]
        else:
            messages.info(request,"Sorry But There Was No Post")
            return redirect("StaffDashboard")

        return render(request,'Staff/StaffCandCampaign.html',{'header_nav':'Post','obj':obj})
    else:
        return redirect("home_page")

def StaffCandidatePostView(request):
    if request.session['Staffloginidpk']:
        id=request.session['StaffCandidatePostView12']
        obj=CandidatePost.objects.filter(pk=id)
        if obj:
            obj=obj.values()
            obj=obj[0]
            return render(request,'Staff/StaffCandidatePostView.html',{'header_nav':'PostView','obj':obj})
        else:
            return redirect("StudentCandCampaign")
    else:
        return redirect("home_page")


import sys
input = lambda: sys.stdin.readline().rstrip()

for aa in range(int(input())):
    n=int(input())
    # n,m=map(int,input().split())
    li=list(map(int,input().split()))
    li.sort()
    z=0
    for i in range(1,n-1):
        for j in range(i):
          for k in range(i+1,n):
            if(li[i]-li[j]==li[k]-li[i]):
                z=1
                break
          if(z==1):
             break
        if(z==1):
            break
    if(z==1):
        print("No")
    else:
        print("Yes")


from cuproj import Transformer as cuTransformer

from cupy.testing import assert_allclose

if __name__ == '__main__':
    # Sydney opera house latitude and longitude
    lat = -33.8587
    lon = 151.2140

    # Transform to UTM using cuproj
    cu_transformer = cuTransformer.from_crs("epsg:4326", "EPSG:32756")
    cuproj_x, cuproj_y = cu_transformer.transform(lat, lon)

    assert_allclose(cuproj_x, 334783.9544807102)
    assert_allclose(cuproj_y, 6252075.961741454)


import pandas as pd
import numpy as np
import torch
import tqdm
from sklearn import preprocessing

def read2logits(name):
    output_list = []
    df = pd.read_csv(name)
    df['output'] = df['output'].apply(lambda x: x.split('[')[1].split(']')[0])
    df_output = df['output'].values.tolist()
    for i in tqdm.tqdm(range(23639)):
        output = df_output[i].split(',')
        output_list.append(torch.tensor([float(x) for x in output]).reshape(1, -1))

    output_list = torch.cat(output_list, dim=0)
    return output_list

efficinet_b7_logits = read2logits(
    '/home/mithil/PycharmProjects/Cultivar_FGVC9/submissions/final/tf_efficientnet_b7_ns_800_cutmix_newSet (is(800-_640) 7xTTa pseudo_label)__w_out.csv')
print(efficinet_b7_logits.shape)
efficinet_l_logits = read2logits(
    '/home/mithil/PycharmProjects/Cultivar_FGVC9/submissions/final/tresnet_m_640_cutmix_newSet (640_7TTa_pseudo_label)__w_out.csv')
filenames = pd.read_csv(
    '/home/mithil/PycharmProjects/Cultivar_FGVC9/submissions/final/tf_efficientnetv2_l_in21ft1k_800_cutmix_h_1(is800-_640 TTa pseudo_label)__w_out.csv')
cultivar = filenames['cultivar'].values.tolist()

probablity = efficinet_l_logits * 0.4 + efficinet_b7_logits * 0.6
probablity = torch.argmax(probablity, dim=1)
probablity = probablity.numpy()
label_to_str = {}
for i, j in zip(cultivar, probablity):
    if j not in label_to_str:
        label_to_str.update({j: i})

print(len(label_to_str))
probablity = list(map(lambda x: label_to_str[x], probablity))
print(probablity[:10])

submissions = pd.DataFrame.from_dict({'filename': filenames['filename'].values.tolist(), 'cultivar': probablity})
submissions.to_csv('/home/mithil/PycharmProjects/Cultivar_FGVC9/submissions/final/ensemble_tresnet_efficitnet.csv', index=False)


from oslo_config import cfg

rating_group = cfg.OptGroup(name='rating_plugin',
                            title='Rating Service Options')

RatingGroup = [
    cfg.StrOpt('service_name',
               default='rating',
               help="Service name of the Rating service."),
    cfg.StrOpt('user_name',
               default='cloudkitty',
               help="User name for the Rating service."),
    cfg.StrOpt('endpoint_type',
               default='publicURL',
               choices=['public', 'admin', 'internal',
                        'publicURL', 'adminURL', 'internalURL'],
               help="The endpoint type to use for the rating service."),
]


from django.test import TestCase
from . import logic
from django.contrib.auth.models import AnonymousUser
from .models import Book, DiscountGroup, Category
from api.v1.tests import factories
from django.contrib.auth import get_user_model

User = get_user_model()

# Create your tests here.
class LogicTestCase(TestCase):
    def setUp(self):
        factories.UserFactory.create()
        factories.UserFactory.create(is_staff=True)
        factories.AuthorFactory.create_batch(2)
        factories.CategoryFactory.create_batch(3)
        factories.BookFactory.create_batch(5)

    def test_in_bookmarks_anonymous(self):
        book = Book.objects.order_by('?').first()
        self.assertFalse(logic.in_bookmarks(book, AnonymousUser()))

    def test_in_bookmarks_logged_in(self):
        book = Book.objects.order_by('?').first()
        user = User.objects.order_by('?').first()
        relation = factories.UserBookRelationFactory.create(user=user, book=book)
        self.assertEqual(relation.in_bookmarks, logic.in_bookmarks(book, user))

    def test_in_bookmarks_no_user(self):
        book = Book.objects.order_by('?').first()
        self.assertFalse(logic.in_bookmarks(book, None))

    def test_book_price_recalculation(self):
        book = factories.BookFactory.create(discount=10, price_original=1000)
        book = Book.objects.get(id=book.id)
        self.assertEqual(900, book.price)
        book.discount = 20
        book.save()
        book = Book.objects.get(id=book.id)
        self.assertEqual(800, book.price)
        discount_group = DiscountGroup.objects.create(name="DG1", discount=20)
        book.discount_group = discount_group
        book.save()
        book = Book.objects.get(id=book.id)
        self.assertEqual(600, book.price)
        discount_group.discount = 30
        discount_group.save()
        book = Book.objects.get(id=book.id)
        self.assertEqual(500, book.price)
        book.discount = 0
        book.save()
        book = Book.objects.get(id=book.id)
        self.assertEqual(700, book.price)

    def test_category_book_stats(self):
        category = factories.CategoryFactory.create()
        factories.BookFactory.create(price_original=20, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=40, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=60, discount=0, categories=(category,))
        category = Category.objects.get(id=category.id)
        self.assertEqual(3, category.book_count)
        self.assertEqual(40, category.book_average_price)

    def test_category_book_stats_with_none(self):
        category = factories.CategoryFactory.create()
        factories.BookFactory.create(price_original=None, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=100, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=50, discount=0, categories=(category,))
        category = Category.objects.get(id=category.id)
        self.assertEqual(3, category.book_count)
        self.assertEqual(75, category.book_average_price)

    def test_category_book_stats_with_zero(self):
        category = factories.CategoryFactory.create()
        factories.BookFactory.create(price_original=0, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=100, discount=0, categories=(category,))
        factories.BookFactory.create(price_original=50, discount=0, categories=(category,))
        category = Category.objects.get(id=category.id)
        self.assertEqual(3, category.book_count)
        self.assertEqual(50, category.book_average_price)


# -*- coding: utf-8 -*-
"""
Created on Thu Jun  6 13:10:07 2019

@author: eduar
"""

import os
import numpy as np
import glob
import pylab as py
from scipy import stats

which='Data_Boot_Corr_Amplitude_Result_'
which2='SybA'
n_iterations=1000

current_dir = os.getcwd()
listsubdirs=[]

total = np.empty(shape=(n_iterations,1))
for item in os.listdir(current_dir):
    if os.path.isdir(os.path.join(current_dir, item)):
        if item == "__pycache__":
            continue
        else:
            listsubdirs+=[item]

for item in range(len(listsubdirs)):
    print("Working on folder:" + listsubdirs[item])
    os.chdir(listsubdirs[item])

    with open("unitswindow.txt", "r") as datafile:
        s=datafile.read().split()[0::3]
    for i in range(len(s)):
        os.chdir(".\\Files\\Unit_"+s[i]+"\\Results")
        annot_files_list = glob.glob('*.txt')
        for name in annot_files_list:
            if which in name and which2 in name:
                print(name)
                read = np.loadtxt(name)[:,1][1:].reshape(-1,1)
                print(read[:5])
                total = np.column_stack((total,read))
        os.chdir("..\\..\\..")
    os.chdir(current_dir)
bol=total[:,1:]<0.05
print("Total of <0.05: " + str(np.sum(np.size(np.where(bol==True)))) + " out of " + str(bol.size))
print("In first row: " + str(np.sum(np.size(np.where(bol[0,:]==True)))) + " out of " + str(bol[0,:].size))
np.savetxt("boot"+which+which2+".csv", total[:,1:], delimiter=',', fmt='%s')

cases=np.array([])
for row in range(len(bol)):
    cases=np.append(cases,np.sum(np.size(np.where(bol[row,:]==True))))

py.hist(cases, bins=np.arange(min(cases), max(cases)+2, 1), density=True)
xt = np.arange(min(cases)-2, max(cases)+2, 1)
xmin, xmax = min(xt), max(xt)
lnspc = np.linspace(xmin, xmax, len(cases))
m, s = stats.norm.fit(cases) # get mean and standard deviation
pdf_g = stats.norm.pdf(lnspc, m, s) # now get theoretical values in our interval
py.plot(lnspc, pdf_g, label="Norm", color="black", linestyle="dashed") # plot it
py.xlabel("Significant values per case")


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

from Catalog import Catalog
from datetime import date,datetime,timedelta

class User:
    def __init__(self, name, location, age, aadhar_id):
        self.name = name
        self.location = location
        self.age = age
        self.aadhar_id = aadhar_id
        #self.catalog = Catalog()  #creating  a catalog object

class Member(User):
    def __init__(self,name, location, age, aadhar_id,student_id):
        super().__init__(name, location, age, aadhar_id)
        self.student_id = student_id
        self.issueLimit = 3
        self.bookIssued = []

    def __repr__(self):
        return self.name + ' ' + self.location + ' ' + str(self.student_id)

    #assume name is unique
    def issueBook(self,catalog,name,barcode,days=10):
        transaction = []  #store the current transaction details
        self.days = days
        book = catalog.searchByName(name) # search in the books objects  # if requested book present
        try:
            #check count of booItem in inventory and   check the member issue limit
            if catalog.inventory.get(name) > 0 and self.issueLimit > 0:
                for bookitem in book.book_item: # search for bookItem of requested barcode
                    if bookitem.barcodeNo == barcode:  # if requested barcode present
                        book.book_item.remove(bookitem) #remove bookItem of that barcode
                        book.total_count-= 1  #decrease total count of bookItems
                        catalog.inventory[name]-= 1  #decrease the count of that book in inventory
                        self.issueLimit-= 1  # reduce the book issue limit of member
                        print('you can issue {} more books'.format(self.issueLimit))
                        returndays = self.returnDays(days) #will return total days from issue date to return date
                        transaction.extend([(datetime.now()),book.name,bookitem.isbn,bookitem.rack,barcode,returndays])  #make a transaction
                        self.bookIssued.append(transaction) #associate the details of transaction with member
                        return transaction
        except:
            print("bookItem of book {} not present".format(book.name))
            return

        print("book of name {} not present in inventory".format(name))

    # issue book return inforamation
    def returnDays(self,days):
        currenttime  = datetime.now()
        returntime   = currenttime + timedelta(days)
        info = returntime - currenttime
        info = int(str(info).split(" ")[0])
        return info #total days from issue date to return date

    #show the whole collection of book and bookItem
    def showInventory(self,catalog):
        return catalog.inventory

    #assume name is unique
    def returnBook(self,catalog,name,rinfo,issuedays,returndays):
        #print(name,issuedays,returndays)
        fineAmt = 0
        bkitem = [bitem for bitem in self.bookIssued if rinfo[-2] in bitem]
        if bkitem:  #check the book is that whick is issued
            #[(datetime.now()),book.name,bookitem.isbn,bookitem.rack,barcode,returndays]
            book = catalog.searchByName(name)
            #book = [bk for bk in catalog.books if bk.name == rinfo[1]][0]
            catalog.addBookItem(book,rinfo[2],rinfo[3],rinfo[4])
            catalog.inventory[book.name]+= 1  #increase the count of that book in inventory
            self.issueLimit+= 1  # update the book issue limit of member
            self.bookIssued.remove(rinfo)  # remove that transaction from member account
            fineAmt = self.payFine(returndays-issuedays)
            print("Return successful")
            print("please pay the fine of {} to librarian".format(fineAmt))
        else:
            print("please bring associated with this library")

    #for paying fine
    def payFine(self,noOfDays):
        fineAmt = 0
        if noOfDays <= 10:  # now we are checking only for 10 days
            return 0
        else:
            fineAmt = (noOfDays-10) * 2 # if greater than 10 days count from 11th day
            return fineAmt

    #for searching all the available book present in catalog by name
    def searchCatalogByName(self,catalog,name):
        result = catalog.searchByName(name) #if book of required name found
        if result:
            print("book of name {} is present".format(name))
            return True
        else:
            print("book of name {} is not present".format(name))
            return False

    #for searching all the available book present in catalog by author
    def searchCatalogByAuthor(self,catalog,author):
        result = catalog.searchByAuthor(author)
        if result:  #if book of required author found
            print("all the books by author {} is/are {}".format(author,result))
        else:
            print("book of author {} not present now".format(author))

class Librarian(User):

    def __init__(self,name, location, age, aadhar_id,emp_id):
        super().__init__(name, location, age, aadhar_id)
        self.emp_id = emp_id

    #string representation of the object
    def __repr__(self):
        return self.name +' '+ self.location +' '+ self.emp_id

    # to add the book in the catalog by the librarian
    def addBook(self,catalog,name,author,publish_date,pages):
        #only librarian can add the book to catalog
        # returning the book object and storing in self.book for later use
        self.book = catalog.addBook(name,author,publish_date,pages)  # returning the book object
        return self.book         # returning book object

    # to display No. of different Books
    def displayDifferentBooks(self,catalog):
        catalog.displayDifferentBooks()

    # to add the bookItem of perticular book
    def addBookItem(self,catalog,book,isbn,rack,barcode):
        #we are calling the already defined function of catalog class
        #only librarian can add the bookItem to catalog
        catalog.addBookItem(self.book,isbn,rack,barcode)

    #display all the book item with different book
    def displayAllBookItems(self,catalog):
        catalog.displayAllBookItems()

    #for removing the book so its bookItem will also deleted
    def removeBook(self,catalog,name):
        self.bookItemslen = 0
        bookobj = catalog.searchByName(name)
        catalog.books.remove(bookobj)  #remove book object from list of books
        catalog.different_book_count-=1  # reduce the different book count
        bookobj.book_item.clear() #clearing the bookItem list of perticular list
        self.bookItemslen = len(bookobj.book_item) #determining total bookitems of book
        bookobj.total_count-=self.bookItemslen #reducing total book count
        catalog.inventory.pop(bookobj.name)

    #to remove the bookItem based on the barcodeNo from inventory
    def removeBookItem(self,catalog,name,barcodeNo):
        books = catalog.searchByName(name)
        for bookItem in books.book_item:
            if bookItem.barcodeNo == barcodeNo:
                books.book_item.remove(bookItem)
                catalog.inventory[books.name]-= 1
                books.total_count-= 1

Project 1- LMS/Library Mgmt System/User.py


import sys,re
import argparse

def break_into_contigs(seq_name, seq):
    ctg_seqs = re.sub('[nN]+','\n',seq).split('\n')
    if len(ctg_seqs) == 1:
        print(f'>{seq_name}')
        print(ctg_seqs[0])
    else:
        for j, ctg_seq in enumerate(ctg_seqs):
            print(f'>{seq_name}_{j}')
            print(ctg_seq)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--inputFasta')
    args = parser.parse_args()

    seq_name = None
    with open(args.inputFasta, "r") as f:
        for line in f:
            if line.strip()[0] == ">":
                if seq_name != None:
                    break_into_contigs(seq_name, seq)
                seq_name = line.strip()[1:]
                seq = ""
                continue
            seq += line.strip()
    break_into_contigs(seq_name, seq)

if __name__ == "__main__":
    main()


from typing import List
from django.db import models
from django.db.models.lookups import PostgresOperatorLookup
from django.http import response
from django.shortcuts import redirect, render

from .forms import DonorDarahForm
from .models import DonorForm, NamaLayanan

def donorPage(request):
    namaLayanan = NamaLayanan.objects.all()
    response = {'namaLayanan' : namaLayanan}
    return render(request, 'donorpage.html', response)

def layananPage(request) :
    namaLayanan = NamaLayanan.objects.all()
    response = {'namaLayanan' : namaLayanan}
    return render(request, 'layananpage.html', response)

def formPage(request) :
    context ={}
    form = DonorDarahForm(request.POST or None, request.FILES or None)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            return redirect('outputform/')
    context['form']= form
    return render(request, "form.html", context)

def hasilFormPage(request) :
    allRelawan = DonorForm.objects.all()
    result = DonorForm
    for relawan in allRelawan :
        if relawan.FullName == 'Salsabila Zahra Chinanti' :
            result = relawan

    response = {'result' : result}
    return render(request, 'outputform.html', response)


"""
CRIE UM PROGRAMA QUE LEIA VÁRIOS NÚMEROS INTEIROS
PELO TECLADO. O PROGRAMA SÓ VAI PARAR QUANDO O USUÁRIO
DIGITAR O VALOR 999, QUE É A CONDIÇÃO DE PARADA.

NO FINAL, MOSTRE QUANTOS NÚMEROS FORAM DIGITADOS
E QUAL FOI A SOMA ENTRE ELES.
"""

print('{} \n '
      '\t\t\t\t\t\t\t\t CONSIDERE A SOMA'
      '\n {}'.format('-=-' * 30, '-=-' * 30))

soma = count = 0
while True:
      num = int(input('Escreva um valor (Escreva 999 para parar): '))
      if num != 999:
            count += 1
            soma += num
      else:
            break
print(f'\nA soma dos {count} valores foi {soma}!')


import numpy as np
from .sph_source import SPHSource
from ..sph_kernels import _WendlandC2Kernel, find_fwhm
from os.path import join, normpath, sep
import astropy.units as U

class EAGLESource(SPHSource):
    """
    Class abstracting HI sources designed to work with publicly available
    EAGLE snapshot + group data.

    For file access, see http://icc.dur.ac.uk/Eagle/database.php.

    Parameters
    ----------
    snapPath : str
        Directory containing snapshot files. The directory structure unpacked
        from the publicly available tarballs is expected; removing/renaming
        files or directories below this will cause errors.

    snapBase : str
        Filename of snapshot files, omitting portion '.X.hdf5'.

    fof : int
        FOF group number of the target object. Note that all particles in the
        FOF group to which the subhalo belongs are used to construct the data
        cube. This avoids strange "holes" at the locations of other subhaloes
        in the same group, and gives a more realistic treatment of foreground
        and background emission local to the source. In the EAGLE database,
        this is the 'GroupNumber'.

    sub : int
        Subfind subhalo number of the target object. For centrals the subhalo
        number is 0, for satellites >0. In the EAGLE database, this is then
        'SubGroupNumber'.

    db_user : str
        Database username.

    db_key : str, optional
        Database password, or omit for a prompt at runtime. (Default: None.)

    subBoxSize : Quantity, with dimensions of length
        Box half-side length of a region to load around the object of interest,
        in physical (not comoving, no little h) units. Using larger values
        will include more foreground/background, which may be desirable, but
        will also slow down execution and impair the automatic routine used
        to find a disc plane.

    distance : Quantity, with dimensions of length, optional
        Source distance, also used to set the velocity offset via Hubble's law.
        (Default: 3 Mpc.)

    vpeculiar : Quantity, with dimensions of velocity, optional
        Source peculiar velocity, added to the velocity from Hubble's law.
        (Default: 0 km/s.)

    rotation : dict, optional
        Must have a single key, which must be one of `axis_angle`, `rotmat` or
        `L_coords`. Note that the 'y-z' plane will be the one eventually placed in the
        plane of the "sky". The corresponding value must be:

        - `axis_angle` : 2-tuple, first element one of 'x', 'y', 'z' for the \
        axis to rotate about, second element a Quantity with \
        dimensions of angle, indicating the angle to rotate through.
        - `rotmat` : A (3, 3) numpy.array specifying a rotation.
        - `L_coords` : A 2-tuple containing an inclination and an azimuthal \
        angle (both Quantity instances with dimensions of \
        angle). The routine will first attempt to identify a preferred plane \
        based on the angular momenta of the central 1/3 of particles in the \
        source. This plane will then be rotated to lie in the plane of the \
        "sky" ('y-z'), rotated by the azimuthal angle about its angular \
        momentum pole (rotation about 'x'), and inclined (rotation about \
        'y'). A 3-tuple may be provided instead, in which case the third \
        value specifies the position angle on the sky (rotation about 'x'). \
        The default position angle is 270 degrees.

        (Default: identity rotation matrix.)

    ra : Quantity, with dimensions of angle, optional
        Right ascension for the source centroid. (Default: 0 deg.)

    dec : Quantity, with dimensions of angle, optional
        Declination for the source centroid. (Default: 0 deg.)

    print_query : bool, optional
        If True, the SQL query submitted to the EAGLE database is printed.
        (Default: False.)
    """

    def __init__(
        self,
        snapPath=None,
        snapBase=None,
        fof=None,
        sub=None,
        db_user=None,
        db_key=None,
        subBoxSize=50.0 * U.kpc,
        distance=3.0 * U.Mpc,
        vpeculiar=0 * U.km / U.s,
        rotation={"rotmat": np.eye(3)},
        ra=0.0 * U.deg,
        dec=0.0 * U.deg,
        print_query=False,
    ):
        if snapPath is None:
            raise ValueError("Provide snapPath argument to EAGLESource.")
        if snapBase is None:
            raise ValueError("Provide snapBase argument to EAGLESource.")
        if fof is None:
            raise ValueError("Provide fof argument to EAGLESource.")
        if sub is None:
            raise ValueError("Provide sub argument to EAGLESource.")
        if db_user is None:
            raise ValueError("Provide EAGLE database username.")

        # optional dependencies for this source class
        from eagleSqlTools import connect, execute_query
        from pyread_eagle import EagleSnapshot
        from Hdecompose.atomic_frac import atomic_frac
        import h5py

        snapNum = int(snapBase.split("_")[1])
        volCode = normpath(snapPath).split(sep)[-2]
        query = (
            "SELECT "
            "  sh.redshift as redshift, "
            "  sh.CentreOfPotential_x as x, "
            "  sh.CentreOfPotential_y as y, "
            "  sh.CentreOfPotential_z as z, "
            "  sh.Velocity_x as vx, "
            "  sh.Velocity_y as vy, "
            "  sh.Velocity_z as vz "
            "FROM "
            "  {:s}_SubHalo as sh ".format(volCode) + "WHERE "
            "  sh.Snapnum = {:d} ".format(snapNum)
            + "  and sh.GroupNumber = {:d} ".format(fof)
            + "  and sh.SubGroupNumber = {:d}".format(sub)
        )
        if print_query:
            print("-----EAGLE-DB-QUERY-----")
            print(query)
            print("-------QUERY-ENDS-------")
        if db_key is None:
            print("EAGLE database")
        q = execute_query(connect(db_user, db_key), query)
        redshift = q["redshift"]
        a = np.power(1 + redshift, -1)
        cop = np.array([q[coord] for coord in "xyz"]) * a * U.Mpc
        vcent = np.array([q["v" + coord] for coord in "xyz"]) * U.km / U.s

        snapFile = join(snapPath, snapBase + ".0.hdf5")

        with h5py.File(snapFile, "r") as f:
            h = f["RuntimePars"].attrs["HubbleParam"]
            subBoxSize = (subBoxSize * h / a).to(U.Mpc).value
            centre = (cop * h / a).to(U.Mpc).value
            eagle_data = EagleSnapshot(snapFile)
            region = np.vstack((centre - subBoxSize, centre + subBoxSize)).T.flatten()
            eagle_data.select_region(*region)
            lbox = f["/Header"].attrs["BoxSize"] * U.Mpc / h
            fH = f["/RuntimePars"].attrs["InitAbundance_Hydrogen"]
            fHe = f["/RuntimePars"].attrs["InitAbundance_Helium"]
            proton_mass = f["/Constants"].attrs["PROTONMASS"] * U.g
            mu = 1 / (fH + 0.25 * fHe)
            gamma = f["/RuntimePars"].attrs["EOS_Jeans_GammaEffective"]
            T0 = f["/RuntimePars"].attrs["EOS_Jeans_TempNorm_K"] * U.K

            def fetch(att, ptype=0):
                # gas is type 0, only need gas properties
                tmp = eagle_data.read_dataset(ptype, att)
                dset = f["/PartType{:d}/{:s}".format(ptype, att)]
                aexp = dset.attrs.get("aexp-scale-exponent")
                hexp = dset.attrs.get("h-scale-exponent")
                return tmp[()] * np.power(a, aexp) * np.power(h, hexp)

            code_to_g = f["/Units"].attrs["UnitMass_in_g"] * U.g
            code_to_cm = f["/Units"].attrs["UnitLength_in_cm"] * U.cm
            code_to_cm_s = f["/Units"].attrs["UnitVelocity_in_cm_per_s"] * U.cm / U.s
            ng_g = fetch("GroupNumber")
            particles = dict(
                xyz_g=(fetch("Coordinates") * code_to_cm).to(U.kpc),
                vxyz_g=(fetch("Velocity") * code_to_cm_s).to(U.km / U.s),
                T_g=fetch("Temperature") * U.K,
                hsm_g=(fetch("SmoothingLength") * code_to_cm).to(U.kpc)
                * find_fwhm(_WendlandC2Kernel().kernel),
            )
            rho_g = fetch("Density") * U.g * U.cm**-3
            SFR_g = fetch("StarFormationRate")
            Habundance_g = fetch("ElementAbundance/Hydrogen")

        particles["mHI_g"] = (
            atomic_frac(
                redshift,
                rho_g * Habundance_g / (mu * proton_mass),
                particles["T_g"],
                rho_g,
                Habundance_g,
                onlyA1=True,
                EAGLE_corrections=True,
                SFR=SFR_g,
                mu=mu,
                gamma=gamma,
                fH=fH,
                T0=T0,
            )
            * code_to_g
        ).to(U.Msun)

        mask = ng_g == fof
        for k, v in particles.items():
            particles[k] = v[mask]

        particles["xyz_g"] -= cop
        particles["xyz_g"][particles["xyz_g"] > lbox / 2.0] -= lbox.to(U.kpc)
        particles["xyz_g"][particles["xyz_g"] < -lbox / 2.0] += lbox.to(U.kpc)
        particles["vxyz_g"] -= vcent

        super().__init__(
            distance=distance,
            vpeculiar=vpeculiar,
            rotation=rotation,
            ra=ra,
            dec=dec,
            h=h,
            **particles,
        )
        return


from typing import List, Dict, Any, Union

def list_targets(
    parameters: Dict[str, Any], case_split: bool = False
) -> Union[List[str], Dict[str, Any]]:
    """ Return all target column names.

    Args:
        parameters: parameters defined in parameters*.yml files.
        case_split: should per-use-case dictionary be returned, default False.
    Returns:
        Target column names.
    """

    targets_parameters = parameters["targets"]

    if case_split:
        target_colnames = {}
    else:
        target_colnames = []

    for use_case_name in targets_parameters:
        use_case_targets_parameters = targets_parameters[use_case_name]
        for specific_target in use_case_targets_parameters:
            target_colname = use_case_targets_parameters[specific_target]["colname"]
            if case_split:
                if use_case_name not in target_colnames:
                    target_colnames[use_case_name] = []
                target_colnames[use_case_name].append(target_colname)
            else:
                target_colnames.append(target_colname)

    return target_colnames


import numpy as np
import firstGameFirstPolicyFunctions as mf
import matplotlib.pyplot as plt
import matplotlib.cm as cm
rewardMatrix = np.array([[5, 0], [10, 1]]) ## Reward Matrix
epsilon = 0.2 ## epsilon
firstPlayerPolicy = mf.policyInitializer()
secondPlayerPolicy = mf.policyInitializer()
policyTrackPlayer1 = list()
policyTrackPlayer2 = list()
for i in range(1000):
  learningRate = 0.5/(i+1)
  policyTrackPlayer1.append(firstPlayerPolicy[0])
  policyTrackPlayer2.append(secondPlayerPolicy[0])
  firstPlayerAction = mf.actionTaker(firstPlayerPolicy, epsilon)
  secondPlayerAction = mf.actionTaker(secondPlayerPolicy, epsilon)
  firstPlayerPolicy, secondPlayerPolicy = mf.policyImprover(firstPlayerPolicy, secondPlayerPolicy, firstPlayerAction, secondPlayerAction, learningRate, rewardMatrix)

colors = cm.rainbow(np.linspace(0, 1, len(policyTrackPlayer1)))
plt.scatter(policyTrackPlayer1, policyTrackPlayer2, s=5, color=colors)
plt.scatter(firstPlayerPolicy[0], secondPlayerPolicy[0], s=50, color=(1, 0, 0))
plt.title('Prisoner\'s Dilemma')
plt.xlabel('Player 1 cooperation')
plt.ylabel('Player 2 cooperation')
plt.show()


'''
Среди чисел, принадлежащих отрезку [150000; 200000],
найти имеющие ровно 48 различных натуральных делителей,
не считая 1 и самого числа.
Для каждого найденного числа вывести самый большой делитель,
в порядке возрастания делителей
'''

START, END = 150000, 200000

def find_divs(n):
    divs = set()
    m = 2
    while m * m <= n:
        if n % m == 0:
            divs.update({m, n//m})
        m += 1
    return divs

result = []
for number in range(START, END+1):
    divs = find_divs(number)
    if len(divs) == 48:
        result.append(max(divs))
print(sorted(result))


"""
Module defining variable calculators managing the exact calculation process
of variables on objects.
"""
from __future__ import annotations

import typing as t
from collections import abc
from itertools import repeat

from more_itertools import peekable
from toolz import curry

from lXtractor.core.exceptions import FailedCalculation
from lXtractor.util import apply
from lXtractor.variables.base import (
    AbstractCalculator,
    ERT,
    OT,
    VT,
    MappingT,
    AbstractVariable,
)

M: t.TypeAlias = MappingT | abc.Iterable[MappingT | None] | None
METHODS = ("joblib", "multiprocess")

# TODO: docs

@curry
def _try_calculate(
    inp: tuple[OT, VT, MappingT | None],
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
) -> ERT:
    o, v, m = inp
    if valid_exceptions is not None:
        try:
            return True, v.calculate(o, m)
        except tuple(valid_exceptions) as e:
            return False, str(e)
    return True, v.calculate(o, m)

@curry
def _calc_on_object(
    inp: tuple[OT, abc.Iterable[VT], MappingT | None],
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
) -> list[ERT]:
    o, vs, m = inp
    return [_try_calculate((o, v, m), valid_exceptions) for v in vs]

def calculate(
    o: abc.Iterable[OT],
    v: abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
    m: MappingT | abc.Iterable[MappingT | None] | None,
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
    num_proc: int,
    verbose: bool = False,
    **kwargs,
) -> abc.Generator[abc.Iterator[ERT], None, None]:
    # Unpack o to know the size
    o = list(o)

    # Check variables type
    v = peekable(v)
    fst = v.peek(None)
    if isinstance(fst, AbstractVariable):
        v = repeat(list(v), len(o))

    if m is None:
        m = repeat(None, len(o))
    elif isinstance(m, abc.Mapping):
        m = repeat(m, len(o))

    inputs = zip(o, v, m, strict=True)
    fn = _calc_on_object(valid_exceptions=valid_exceptions)
    yield from apply(fn, inputs, verbose, "Calculating variables", num_proc, **kwargs)

class GenericCalculator(AbstractCalculator):
    """
    Parallel calculator, calculating variables in parallel. Duh.
    """

    __slots__ = ("num_proc", "valid_exceptions", "apply_kwargs", "verbose")

    def __init__(
        self,
        num_proc: int = 1,
        valid_exceptions: abc.Sequence[t.Type[Exception]] = (FailedCalculation,),
        apply_kwargs: dict | None = None,
        verbose: bool = False,
    ):
        self.num_proc = num_proc
        self.valid_exceptions = valid_exceptions
        self.apply_kwargs = apply_kwargs or {}
        self.verbose = verbose

    @t.overload
    def __call__(self, o: OT, v: VT, m: MappingT | None) -> ERT:
        ...

    @t.overload
    def __call__(
        self,
        o: abc.Iterable[OT],
        v: abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
        m: abc.Iterable[MappingT | None] | None,
    ) -> abc.Iterable[abc.Iterable[ERT]]:
        ...

    def __call__(
        self,
        o: OT | abc.Iterable[OT],
        v: VT | abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
        m: MappingT | abc.Iterable[MappingT | None] | None,
    ) -> ERT | abc.Iterable[abc.Iterable[ERT]]:
        if isinstance(v, abc.Iterable):
            return calculate(
                o,
                v,
                m,
                self.valid_exceptions,
                self.num_proc,
                self.verbose,
                **self.apply_kwargs,
            )
        assert (
            isinstance(m, abc.Mapping) or m is None
        ), "Mapping must be a single object"

        return _try_calculate((o, v, m), self.valid_exceptions)

    def map(
        self, o: OT, v: abc.Iterable[VT], m: MappingT | None
    ) -> abc.Generator[ERT, None, None]:
        v = list(v)
        inputs = zip(
            repeat(o, len(v)),
            v,
            repeat(m, len(v)),
            strict=True,
        )
        fn = _try_calculate(valid_exceptions=self.valid_exceptions)
        yield from apply(
            fn, inputs, self.verbose, "Calculating variables", self.num_proc
        )

    def vmap(
        self,
        o: abc.Iterable[OT],
        v: VT,
        m: abc.Iterable[MappingT | None] | MappingT | None,
    ) -> abc.Generator[ERT, None, None]:
        o = list(o)
        if m is None or isinstance(m, abc.Mapping):
            m = repeat(m, len(o))
        inputs = zip(o, repeat(v, len(o)), m)
        fn = _try_calculate(valid_exceptions=self.valid_exceptions)
        yield from apply(
            fn, inputs, self.verbose, "Calculating variables", self.num_proc
        )

if __name__ == "__main__":
    raise RuntimeError


import sqlite3

from create_tables import DATABASE_URI

__author__ = 'myidispg'

class Education:

    def __init__(self, _id, course, from_date, till_date, institution, board_university):
        self._id = _id
        self.course = course
        self.from_date = from_date
        self.till_date = till_date
        self.institution = institution
        self.board_university = board_university

    def insert_data(self):
        """
        If a row with the user id already exists, then it updates the row, otherwise inserts the data
        :return: Nothing to return
        """
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query_find_by_id = "SELECT * FROM education WHERE _id=? and course=?"
        result = cursor.execute(query_find_by_id, (self._id, self.course,))
        rows = result.fetchone()

        if rows is not None:
            query = "UPDATE education " \
                    "SET from_date=?, till_date=?, institution = ?, board_university = ? " \
                    "WHERE _id = ? and course = ?"
            cursor.execute(query, (self.from_date, self.till_date,
                                   self.institution, self.board_university, self._id, self.course,))

        else:
            query = "INSERT INTO education values(?,?,?,?,?,?)"
            cursor.execute(query, (self._id, self.course, self.from_date, self.till_date, self.institution,
                                   self.board_university,))

        connection.commit()
        connection.close()

    @classmethod
    def get_by_id(cls, _id):
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query = 'SELECT * FROM education WHERE _id=?'
        result = cursor.execute(query, (_id,))

        row = result.fetchone()

        education = cls(row[0], row[1], row[2], row[3], row[4])
        connection.close()

        return education

    @staticmethod
    def get_all():
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query = "SELECT * from education"
        result = cursor.execute(query)

        rows = result.fetchall()

        list = []

        for row in rows:
            dictionary = {
                'id': row[0],
                'course': row[1],
                'from_date': row[2],
                'till_date': row[3],
                'institution': row[4],
                'board': row[5]
            }
            list.append(dictionary)

        connection.close()
        return list


from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.views.generic import ListView, DetailView, View
from .models import Order, CartItem
from gallery.models import painting

@login_required(login_url='/login/')
def OrderSummary(request):
    cart_items,created = CartItem.objects.get_or_create(
        user=request.user, ordered=False)
    context = {'cart_items': cart_items}
    print(cart_items)
    return render(request, 'cart.html', context)

@login_required(login_url='/login/')
def add_to_cart(request, pk):
    item = get_object_or_404(painting, pk=pk)
    ordered_item, created = Order.objects.get_or_create(
        item=item,
        user=request.user,
        ordered=False
    )

    user_cartitem = CartItem.objects.filter(
        user=request.user, ordered=False)

    if user_cartitem.exists():
        cart_item = user_cartitem[0]

        if cart_item.item.filter(item__pk=item.pk).exists():
            ordered_item.quantity += 1
            ordered_item.save()
            messages.success(request, "Added Quantity Item")
            return redirect("cart:order-summary")
        else:
            cart_item.item.add(ordered_item)
            messages.success(request, "Added Item to your cart")
            return redirect("cart:order-summary")

    else:
        ordered_date = timezone.now()
        cart_item = CartItem.objects.create(
            user=request.user, order_date=ordered_date)
        cart_item.item.add(ordered_item)
        messages.success(request, "Added Item to your cart")
        return redirect("cart:order-summary", pk=pk)

@login_required(login_url='/login/')
def remove_from_cart(request, pk):
    item = get_object_or_404(painting,pk=pk)
    user_cartitems = CartItem.objects.filter(user=request.user,
                                             ordered=False
                                             )
    if user_cartitems.exists():
        cart_items = user_cartitems[0]

        if cart_items.item.filter(item__pk=item.pk).exists():
            order_item = Order.objects.filter(user=request.user,
                                              item=item,
                                              ordered=False)[0]
            order_item.delete()
            messages.success(request, "Item \"" +
                             order_item.item.Title+"\" removed from your cart")
            return redirect("cart:order-summary")
        else:
            messages.success(request, "This Item not in your cart")
            return redirect("cart:order-summary")
    else:
        messages.success(request, "You do not have an Order")
        return redirect("cart:order-summary")

@login_required(login_url='/login/')
def remove_single_item_from_cart(request, pk):
    item = get_object_or_404(painting,pk=pk)
    user_cartitems = CartItem.objects.filter(user=request.user,
                                             ordered=False
                                             )
    if user_cartitems.exists():
        cart_items = user_cartitems[0]

        if cart_items.item.filter(item__pk=item.pk).exists():
            order_item = Order.objects.filter(user=request.user,
                                              item=item,
                                              ordered=False)[0]
            if order_item.quantity > 1:
                order_item.quantity -= 1
                order_item.save()
            else:
                order_item.delete()
            messages.success(request, "Cart Updated")
            return redirect("cart:order-summary")

        else:
            messages.success(request, "This Item is not in your cart")
            return redirect("cart:order-summary")
    else:
        messages.success(request, "You do not have an Order")
        return redirect("cart:order-summary")

@login_required(login_url='/login/')
def PlaceOrder(request):
    cart_items = CartItem.objects.get(user=request.user, ordered=False)
    # order = Order.objects.filter(user=request.user, ordered=False)

    order_items = cart_items.item.all()
    order_items.update(ordered=True)
    for item in order_items:
        item.save()

    cart_items.ordered = True
    cart_items.save()
    messages.success(request, "Your Order has been placed")
    return redirect("/")


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging
import time
from six import wraps, get_method_function, get_method_self

from .exceptions import DoNotReadThisWidget

null_logger = logging.getLogger('widgetastic_null')
null_logger.addHandler(logging.NullHandler())

class PrependParentsAdapter(logging.LoggerAdapter):
    """This class ensures the path to the widget is represented in the log records."""
    def process(self, msg, kwargs):
        return '[{}]: {}'.format(self.extra['widget_path'], msg), kwargs

def create_widget_logger(widget_path, logger=None):
    """Create a logger that prepends the ``widget_path`` to the log records."""
    return PrependParentsAdapter(
        logger or null_logger,
        {'widget_path': widget_path})

def logged(log_args=False, log_result=False):
    def g(f):
        @wraps(f)
        def wrapped(self, *args, **kwargs):
            start_time = time.time()
            if log_args:
                signature = '{}{!r}{!r}'.format(f.__name__, args, kwargs)
            else:
                signature = f.__name__
            self.logger.debug('%s started', signature)
            try:
                result = f(self, *args, **kwargs)
            except DoNotReadThisWidget:
                elapsed_time = (time.time() - start_time) * 1000.0
                self.logger.info(
                    '%s not read on widget\'s request (elapsed %.0f ms)', signature, elapsed_time)
                raise
            else:
                elapsed_time = (time.time() - start_time) * 1000.0
                if log_result:
                    self.logger.info('%s -> %r (elapsed %.0f ms)', signature, result, elapsed_time)
                else:
                    self.logger.info('%s (elapsed %.0f ms)', signature, elapsed_time)
                return result

        wrapped.original_function = f
        return wrapped

    return g

def call_unlogged(method, *args, **kwargs):
    """Calls the original method without logging when ``logged`` is applied.

    In case you pass in an ordinary method that was not decorated, it will work as usual.

    Args:
        method: The method object from the object.
        *args: Args to pass to the method.
        **kwargs: Keyword arguments to pass to the method.

    Returns:
        Whatever that method returns.
    """
    try:
        f = method.original_function
    except AttributeError:
        f = get_method_function(method)

    return f(get_method_self(method), *args, **kwargs)


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(N):
    # write your code in Python 3.6
    br = str(bin(N))[2:]
    res = 0
    cur = 0
    for i in range(1, len(br)-1):
        if br[i] == "0":
            if br[i-1] == "1" or cur != 0:
                cur += 1
            if br[i+1] == "1":
                res = max(res, cur)
                cur = 0
    return res

#MinDistinct


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 17 11:15:57 2018

@author: kazuki.onodera
"""

import gc, os
from tqdm import tqdm
import pandas as pd
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from multiprocessing import cpu_count, Pool
#from glob import glob
import count
import utils, utils_cat
utils.start(__file__)
#==============================================================================

SEED = 71

HEADS = list(range(500, 2500, 100))

param = {
         'objective': 'binary',
         'metric': 'auc',
         'learning_rate': 0.01,
         'max_depth': 6,
         'num_leaves': 63,
         'max_bin': 255,

         'min_child_weight': 10,
         'min_data_in_leaf': 150,
         'reg_lambda': 0.5,  # L2 regularization term on weights.
         'reg_alpha': 0.5,  # L1 regularization term on weights.

         'colsample_bytree': 0.9,
         'subsample': 0.9,
#         'nthread': 32,
         'nthread': cpu_count(),
         'bagging_freq': 1,
         'verbose':-1,
         'seed': SEED
         }

# =============================================================================
# load
# =============================================================================
imp = pd.read_csv('LOG/imp_801_imp_lgb.py.csv')
imp['split'] /= imp['split'].max()
imp['gain'] /= imp['gain'].max()
imp['total'] = imp['split'] + imp['gain']
imp.sort_values('total', ascending=False, inplace=True)

for HEAD in HEADS:
    imp_ = imp[~imp.feature.str.startswith('Mxw_META_FEATURE_')]
    use_files = (imp_.head(HEAD).feature + '.f').tolist()

    files = utils.get_use_files(use_files, True)

    X = pd.concat([
                    pd.read_feather(f) for f in tqdm(files, mininterval=60)
                   ], axis=1)
    y = utils.read_pickles('../data/label').TARGET

    if X.columns.duplicated().sum()>0:
        raise Exception(f'duplicated!: { X.columns[X.columns.duplicated()] }')
    print('no dup :) ')
    print(f'X.shape {X.shape}')

    gc.collect()

    CAT = list( set(X.columns)&set(utils_cat.ALL))

    # =============================================================================
    # cv
    # =============================================================================
    dtrain = lgb.Dataset(X, y, categorical_feature=CAT )
    gc.collect()

    ret = lgb.cv(param, dtrain, 9999, nfold=5,
                 early_stopping_rounds=100, verbose_eval=50,
                 seed=SEED)

    result = f"CV auc-mean({HEAD}): {ret['auc-mean'][-1]}"
    print(result)

    utils.send_line(result)

# =============================================================================
# train
# =============================================================================
#dtrain = lgb.Dataset(X, y, categorical_feature=CAT )
##model = lgb.train(param, dtrain, len(ret['auc-mean']))
#model = lgb.train(param, dtrain, 1000)
#imp = ex.getImp(model).sort_values(['gain', 'feature'], ascending=[False, True])
#
#
#imp.to_csv(f'LOG/imp_{__file__}.csv', index=False)
#
#"""
#imp = pd.read_csv('LOG/imp_909_cv.py.csv')
#"""

#def multi_touch(arg):
#    os.system(f'touch "../feature_unused/{arg}.f"')
#
#
#col = imp[imp['split']==0]['feature'].tolist()
#pool = Pool(cpu_count())
#pool.map(multi_touch, col)
#pool.close()

#==============================================================================
utils.end(__file__)
#utils.stop_instance()


command = "even"
lis = [1, 2, 1, 2, 8, 4, 5, 3, 10, 4, 5]
t = ""
listove = []
# index = lis.index(max(lis))
# index = max((x, i) for i, x in enumerate(lis))
# index = len(lis) - lis[::-1].index(max(lis)) - 1
# index = [i if i == 8 else 0 for i in lis]
# index = [ i if i % 2 == 0 and command == "even" else for i in lis]
# index = [lis[i] for i in range(t)]
# print(lis[::-1])
# a = "import 5"
# b = a.split()
# index = [i if i == len(lis) - lis[::-1].index(max(lis)) - 1 else 0 for i in lis]
# if set(listove) == {0}:
#     print("Yes")
# print(index)
# a = len(lis) - lis[::-1].index(min(lis)) - 1
# b = [i for i in lis if i % 2 == 0]
# print(b)
# c = len(lis) - lis[::-1].index(max(b)) - 1
# print(lis[::-1].index(max(b)))
# print(c)
# if not listove:
# lis[0] += 3
# lis.pop(3)
# for i in lis:
#     listove.append(str(i))
#     "|".join(listove)
# print(lis)
# print("|".join(listove))
# houses = [int(i) for i in input().split("@")]

a = 4
b = 3.4
if a > b:
    print(lis)


from django.urls import path

from .views import (
    AuthorListView,
    AuthorDetailView,
    BookListView,
    BookDetailView,
    AuthorCreateView,
    BookCreateView,
    AuthorUpdateView,
    AuthorDeleteView,
    BookUpdateView,
    BookDeleteView,
    GenreListView,
    GenreCreateView,
    GenreUpdateView,
    GenreDeleteView,
)

urlpatterns = [
    path("books/", BookListView.as_view(), name="books-list"),
    path("book/add/", BookCreateView.as_view(), name="book-create"),
    path("book/update/<int:pk>", BookUpdateView.as_view(), name="book-update"),
    path("book/delete/<int:pk>", BookDeleteView.as_view(), name="book-delete"),
    path("book/<int:pk>", BookDetailView.as_view(), name="book-detail"),
    path("authors/", AuthorListView.as_view(), name="authors-list"),
    path("author/<int:pk>", AuthorDetailView.as_view(), name="author-detail"),
    path("author/add/", AuthorCreateView.as_view(), name="author-create"),
    path("author/update/<int:pk>", AuthorUpdateView.as_view(), name="author-update"),
    path("author/delete/<int:pk>", AuthorDeleteView.as_view(), name="author-delete"),
    path("genres/", GenreListView.as_view(), name="genres-list"),
    path("genre/add/", GenreCreateView.as_view(), name="genre-create"),
    path("genre/update/<int:pk>", GenreUpdateView.as_view(), name="genre-update"),
    path("genre/delete/<int:pk>", GenreDeleteView.as_view(), name="genre-delete"),
]


import zipfile
import os
import random
import shutil

train_percent = 0.8

# Archive unpack
unzip_dir = 'VOC_PCB'

if not os.path.exists(unzip_dir):
    path_to = '../VOC_PCB.zip'
    with zipfile.ZipFile(path_to, 'r') as zip_ref:
        zip_ref.extractall()

# Data group
new_dir = 'Dataset_for_YOLO'

if not os.path.exists(new_dir):
    os.mkdir(new_dir)
    os.mkdir(os.path.join(new_dir, 'train'))
    os.mkdir(os.path.join(new_dir, 'val'))
    os.mkdir(os.path.join(new_dir, 'train', 'images'))
    os.mkdir(os.path.join(new_dir, 'train', 'labels'))
    os.mkdir(os.path.join(new_dir, 'val', 'images'))
    os.mkdir(os.path.join(new_dir, 'val', 'labels'))

photo_dir = unzip_dir + '/JPEGImages'
annotation_dir = '../Labels'

for filename in os.listdir(photo_dir):
    rand_num = random.random()

    if rand_num < train_percent:
        target_dir = os.path.join(new_dir, 'train', 'images')
        annotation_target_dir = os.path.join(new_dir, 'train', 'labels')
    else:
        target_dir = os.path.join(new_dir, 'val', 'images')
        annotation_target_dir = os.path.join(new_dir, 'val', 'labels')

    os.makedirs(target_dir, exist_ok=True)
    source_path = os.path.join(photo_dir, filename)

    if os.path.exists(source_path):
        target_path = os.path.join(target_dir, filename)
        shutil.move(source_path, target_path)

        annotation_file = os.path.splitext(filename)[0] + '.txt'
        annotation_source_path = os.path.join(annotation_dir, annotation_file)
        annotation_target_path = os.path.join(annotation_target_dir, annotation_file)

        if os.path.exists(annotation_source_path):
            shutil.move(annotation_source_path, annotation_target_path)
        else:
            print(f"Annotation file not found: {annotation_source_path}")
    else:
        print(f"File is not real: {source_path}")


from copy import deepcopy
from qiskit.execute import execute
from qiskit.providers.basicaer import BasicAer

from qiskit.test import QiskitTestCase

from qiskit.circuit import ClassicalRegister, QuantumRegister, QuantumCircuit

def random_circuit(Data):
    qr = QuantumRegister(3, 'q')
    cr = ClassicalRegister(3, 'c')
    circuit = QuantumCircuit(qr, cr)
    circuit.h(qr[1])
    circuit.cx(qr[1], qr[2])
    circuit.measure(qr, cr)
    return circuit

class FuzzOptmizationLevels(QiskitTestCase):

    def __init__(self, Data):
        self.circuit = random_circuit(Data)
        self.seed_simulator = int.from_bytes(Data.read(1), byteorder='little')
        self.random_bool = self.seed_simulator < 42

    def assertEqualCounts(self, *counts):
        average = {}
        for value in set(counts[0]).intersection(*counts[1:]):
            average[value] = sum([count[value] for count in counts])/len(counts)

        for count in counts:
            for value in count.keys():
                self.assertEqual(count[value], average[value])

    def optmization_levels(self):
        backend = BasicAer.get_backend('qasm_simulator')

        circuit = self.circuit
        seed_simulator = self.seed_simulator
        seed_transpiler = seed_simulator

        counts_0 = execute(deepcopy(circuit),
                           backend, optimization_level=0,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler).result().get_counts()
        counts_1 = execute(deepcopy(circuit),
                           backend, optimization_level=1,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()
        counts_2 = execute(deepcopy(circuit),
                           backend, optimization_level=2,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()

        if self.random_bool:
            counts_3 = execute(deepcopy(circuit),
                           backend, optimization_level=3,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()
        else:
            counts_3 = deepcopy(counts_2)

        self.assertEqualCounts(counts_0, counts_1, counts_2, counts_3)

def optmization_levels(Data):
    test = FuzzOptmizationLevels(Data)
    test.optmization_levels()

if __name__ == '__main__':
    import io
    data = io.BytesIO(b"abcdef")
    optmization_levels(data)


import numpy as np

n = 2000000

# Make a list from 2 to n
up2n = np.array([i for i in range(n+1)])
up2n[1] = 0
p = 2

# Use a sieve to get only primes
while p < n:
    if up2n[p] != 0 and p*p < n:
        for i in range(p*p, n+1//p + 1, p):
            up2n[i] = 0
    p += 1

print(np.sum(up2n[up2n != 0]))


import enum
from typing import Optional, List
import can, os
import time

class Command(enum.IntEnum):

    START_Start = 0x01
    STOP_Stop = 0x02

    POS_GetActualPosition = 0x40
    TPOS_GetTargetPosition = 0x4B

    GAC_GetAcceleration = 0x15
    GDEC_GetDecceleration = 0x1B
    GSP_GetMaximumSpeed = 0x36
    GCC_GetContinousCurrent = 0x18
    GPC_GetPeakCurrent = 0x30

    AC_SetCommandAcceleration = 0x65
    DEC_SetCommandDeceleration = 0x6d
    SP_SetMaximumSpeed = 0x8f
    LCC_LoadContinousCurrentLimit = 0x80
    LPC_LoadPeakCurrentLimit = 0x81

    RESET_ResetDrive = 0x59
    RN_ResetNode = 0x44

    EEPSAV_SaveParameters = 0x0d
    DI_DisableDrive = 0x08
    EN_EnableDrive = 0x0F
    M_InitiateMotion = 0x3C
    LA_LoadAbsolutePosition = 0xB4
    LR_LoadRelativePosition = 0xB6
    TEM_GetTemperature = 0x47

    HO_DefineHomePosition = 0xB8
    GOHOSEQ_GoHomeSequence = 0x2F

class Result(enum.IntEnum):
    Success = 1
    EEPROMWritinDone = -2
    Overtemperature = -4
    InvalidParameter = -5
    UnknownCommand = -7
    CommandNotAvailable = -8
    FlashDefect = -13

class StatusWord(enum.IntFlag):
    ReadyToSwitchOn = 0x0001
    SwitchedOn = 0x0002
    OperationEnabled = 0x0004
    Fault = 0x0008

    VoltageEnabled = 0x0010
    QuickStop = 0x0020
    SwitchOnDisabled = 0x0030
    Warning = 0x0080

    __reserved0 = 0x0100,
    Remote = 0x0200,
    TargetReached = 0x0400,
    InternalLimitActive = 0x0800,

    SetpointAcknowledge = 0x1000
    HommingAttained = 0x1000
    Speed = 0x1000

    HomingError = 0x2000
    HardNotifty = 0x4000
    __reserved1 = 0x8000

def Initialize() -> can.interface.Bus:
    os.system("sudo ifconfig can0 down")
    os.system("sudo ip link set can0 type can bitrate 20000")
    os.system("sudo ip link set can0 type can restart-ms 100")
    os.system("sudo ifconfig can0 up")

    can0 = can.interface.Bus(channel = 'can0', bustype='socketcan_ctypes')
    return can0

def SendCommandToServomotor(bus: can.interface.Bus, nodeAddress: int, command: Command, data: List[int], responseTimeout: Optional[float] = None) -> Optional[int]:
    assert isinstance(data, list)

    # Przygotuj komunikat dla serwosilnika
    payload = [0] * 5
    payload[0] = command & 0xFF

    data = data or []
    for i in range(0, len(data)):
        payload[i + 1] = data[i] & 0xFF

    #print(f"Sendin {command}...")
    try:
        msg = can.Message(arbitration_id = 0x300 + nodeAddress, data = payload, extended_id = False)
        bus.send(msg)
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

    if responseTimeout is None:
        return None # nie czekamy na odpowiedź sterownika

    try:
        msg = bus.recv(responseTimeout)
        if msg is None:
            return None # timeout
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

    return msg.data

def Flush(bus: can.interface.Bus, nodeAddress: int):
    try:
        while True:
            msg = bus.recv(0.0)
            if msg is None:
                return
    except can.CanError as ce:
        print("CanError: ", ce)
    pass

def WaitForStatusWord(bus: can.interface.Bus, nodeAddress: int, responseTimeout: float) -> Optional[int]:
    try:
        while True:
            msg = bus.recv(responseTimeout)
            if msg is None:
                return # timeout
            if msg.arbitration_id != 0x180 + nodeAddress:
                continue

            assert msg.dlc == 2 # ten komunikat musi mieć dwa bajty

            statusword = int.from_bytes(msg.data, byteorder='little', signed=False)
            return statusword
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

def ReadStatusWord(bus: can.interface.Bus, nodeAddress: int, responseTimeout: float) -> Optional[int]:

    # Przygotuj komunikat dla serwosilnika
    try:
        msg = can.Message(arbitration_id = 0x180 + nodeAddress, data = [], extended_id = False)
        bus.send(msg)
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

    if responseTimeout is None:
        return None # nie czekamy na odpowiedź sterownika

    return WaitForStatusWord(bus, nodeAddress, responseTimeout)

def FindHomePosition(bus: can.interface.Bus, nodeAddress: int, responseTimeout: Optional[float] = 20):
    timestep = 0.2

    Flush(bus, nodeAddress)
    print("Szukanie bazy: ", end="")
    SendCommandToServomotor(bus, nodeAddress, Command.GOHOSEQ_GoHomeSequence, [])
    timer = responseTimeout
    Flush(bus, nodeAddress)

    while True:
        print(f"o", end="")
        time.sleep(timestep)

        if timer is not None:
            timer -= timestep
            if timer <= 0:
                print("!")
                return False

        sw = ReadStatusWord(bus, nodeAddress, 1)
        if sw is None:
            timer -= 1
            continue

        if not (sw & StatusWord.TargetReached):
            break

    while True:
        if timer is not None:
            timer -= timestep
            if timer <= 0:
                print("!")
                return False

        sw = ReadStatusWord(bus, nodeAddress, 1)
        if sw is None:
            timer -= 1
        print(f".", end="")
        time.sleep(timestep)

        if (sw & StatusWord.TargetReached):
            break

    print("Ok.")
    return True

def GoToPosition(bus: can.interface.Bus, nodeAddress: int, targetPosition: int):
    payload = list(int.to_bytes(targetPosition, length=4, byteorder='little',signed=True))
    Flush(bus, nodeAddress)
    SendCommandToServomotor(bus, nodeAddress, Command.LA_LoadAbsolutePosition, payload)
    SendCommandToServomotor(bus, nodeAddress, Command.M_InitiateMotion, [])

def WaitForTargetPosition(bus: can.interface.Bus, nodeAddress: int, responseTimeout: Optional[float] = 10):
    timestep = 0.2
    timer = responseTimeout

    while True:
        sw = ReadStatusWord(bus, nodeAddress, 5)
        print(f"o", end="")
        time.sleep(timestep)

        if timer is not None:
            timer -= timestep
            if timer <= 0:
                return False
        if not (sw & StatusWord.TargetReached):
            break

    while True:
        sw = ReadStatusWord(bus, nodeAddress, 5)
        print(f".", end="")
        time.sleep(timestep)

        if timer is not None:
            timer -= timestep
            if timer <= 0:
                print("!")
                return False
        if (sw & StatusWord.TargetReached):
            break
    print("|")

def SendNodeStartCommand(bus: can.interface.Bus, nodeAddress: int):
    # Przygotuj komunikat dla serwosilnika
    try:
        payload = [Command.START_Start, nodeAddress & 0xFF]
        msg = can.Message(arbitration_id = 0x000, data = payload, extended_id = False)
        bus.send(msg)
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

def GetCurrentPosition(bus: can.interface.Bus, nodeAddress: int):

    try:
        pos_payload = [Command.POS_GetActualPosition, 0, 0, 0, 0]
        msg = can.Message(arbitration_id = 0x300 + nodeAddress, data = pos_payload, extended_id = False)
        bus.send(msg)

        Flush(bus, nodeAddress)

        msg = can.Message(arbitration_id = 0x280 + nodeAddress, is_remote_frame = True, extended_id = False)
        bus.send(msg)
    except can.CanError as ce:
        print("CanError: ", ce)
        return None

    timeout = 1
    while True:
        try:
            msg = bus.recv(timeout)
        except can.CanError as ce:
            print("CanError: ", ce)
            return None

        if msg is None:
            return None # timeout
        if msg.arbitration_id != 0x280 + nodeAddress:
            continue # to nie do mnie
        if msg.dlc <= 1 + 4:
            continue # zbyt krótka odpowiedz
        if msg.data[0] != Command.POS_GetActualPosition:
            continue # To nie jest odpowiedz na POS_GetActualPosition

        # Tak!
        position = int.from_bytes(msg.data[1:5], byteorder='little', signed=True)
        return position

    pass

if __name__ == "__main__":
    pass


'''
Ejercicios de Listas y Tuplas

Ejercicio 1
Escribir un programa que almacene las asignaturas de un
curso (por ejemplo Matemáticas, Física, Química, Historia y
Lengua) en una lista y la muestre por pantalla.
'''
print("--- Ejercicio 1 ---")

asignaturas = ["Matematicas","Fisica","Quimica", "Historia", "Lengua"]

print(asignaturas)

'''
Ejercicio 2
Escribir un programa que almacene las asignaturas de un
curso (por ejemplo Matemáticas, Física, Química, Historia y
Lengua) en una lista y la muestre por pantalla el mensaje Yo
estudio <asignatura>, donde <asignatura> es cada una de
las asignaturas de la lista.
'''
print("--- Ejercicio 2 ---")

asignaturas = ["Matematicas","Fisica","Quimica", "Historia", "Lengua"]

for i in range(len(asignaturas)):
    if i == 0:
        print("Yo estudio ", end="")
    elif i == len(asignaturas)-1:
        print(f"y {asignaturas[i]}.")
    elif i == len(asignaturas)-2:
        print(f"{asignaturas[i]} ", end="")
    else:
        print(f"{asignaturas[i]}, ", end="")

'''
Ejercicio 3
Escribir un programa que almacene las asignaturas de un
curso (por ejemplo Matemáticas, Física, Química, Historia y
Lengua) en una lista, pregunte al usuario la nota que ha
sacado en cada asignatura, y después las muestre por pantalla
con el mensaje En <asignatura> has sacado <nota> donde
<asignatura> es cada una des las asignaturas de la lista y
<nota> cada una de las correspondientes notas introducidas
por el usuario.
'''
print("--- Ejercicio 3 ---")

asignaturas = ["Matematicas","Fisica","Quimica", "Historia", "Lengua"]
notas = []

for i in asignaturas:
    notas.append(int(input(f"Que nota se saco en la asignatura {i}")))

for i in range(len(asignaturas)):
    print(f"En {asignaturas[i]} has sacado {notas[i]}")

'''
Ejercicio 4
Escribir un programa que pregunte al usuario los números
ganadores de la lotería primitiva, los almacene en una lista y
los muestre por pantalla ordenados de menor a mayor.
'''
print("--- Ejercicio 4 ---")
num_lot = []
i=1
while i <= 8:
    num = input(f"Ingrese el numero que salio en la loteria en la posicion {i}")
    if not num.isnumeric():
        print("Debe ingresar un numero")
        continue
    num = int(num)
    if num > 49 or num < 0 :
        print("El numero debe estar entre 00 y 49")
    else:
        num_lot.append(num)
        i +=1
print(sorted(num_lot))

'''
Ejercicio 5
Escribir un programa que almacene en una lista los números
del 1 al 10 y los muestre por pantalla en orden inverso
separados por comas.
'''
print("--- Ejercicio 5 ---")
nums = list(range(1,11))
x = 1
for i in (list(reversed(nums))):
    if x == len(nums):
        print(i, end=". ")
    else:
        print(i, end=", ")
    x += 1

'''
Ejercicio 6
Escribir un programa que almacene las asignaturas de un
curso (por ejemplo Matemáticas, Física, Química, Historia y
Lengua) en una lista, pregunte al usuario la nota que ha
sacado en cada asignatura y elimine de la lista las asignaturas
aprobadas. Al final el programa debe mostrar por pantalla las
asignaturas que el usuario tiene que repetir.
'''
print("--- Ejercicio 6 ---")

asignaturas = ["Matematicas","Fisica","Quimica", "Historia", "Lengua"]
asignaturas_aprobadas = []
notas = []

for i in asignaturas:
    nota = int(input(f"Que nota se saco en la asignatura {i}"))
    if nota < 5:
        notas.append(nota)
        asignaturas_aprobadas.append(i)

for i in range(len(asignaturas_aprobadas)):
    print(f"En {asignaturas_aprobadas[i]} has sacado {notas[i]}")

'''
Ejercicio 7
Escribir un programa que almacene el abecedario en una lista,
elimine de la lista las letras que ocupen posiciones múltiplos de
3, y muestre por pantalla la lista resultante.
'''
print("--- Ejercicio 7 ---")

import string

abc = list(string.ascii_lowercase)
lista = []
count = 1
for letra in abc:
    if count % 3 == 0:
        lista.append(letra)
    count += 1
for l in lista:
    abc.remove(l)
print(abc)

'''
Ejercicio 8
Escribir un programa que pida al usuario una palabra y
muestre por pantalla si es un palíndromo.
'''
print("--- Ejercicio 8 ---")

palabra = input('Ingrese una palabra: ')
reverse = palabra[::-1]
if palabra == reverse:
    print(f'La palabra "{palabra}" es palindroma!')
else:
    print(f'La palabra "{palabra}" no es palindroma!')

'''
Ejercicio 9
Escribir un programa que pida al usuario una palabra y
muestre por pantalla el número de veces que contiene cada
vocal.
'''
print("--- Ejercicio 9 ---")

palabra = input('Ingrese una palabra: ')
vocales = ['a','e','i','o','u']
print(f'La palabra "{palabra}" contiene las siguientes vocales:')
for v in vocales:
    count = palabra.count(v)
    print(f'"{v}": {count}')

'''
Ejercicio 10
Escribir un programa que almacene en una lista los
siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por
pantalla el menor y el mayor de los precios.
'''
print("--- Ejercicio 10 ---")

prices = [50, 75, 46, 22, 80, 65, 8]
min = max = prices[0]
for price in prices:
    if price < min:
        min = price
    elif price > max:
        max = price
print("El mínimo es " + str(min))
print("El máximo es " + str(max))

'''
Ejercicio 11
Escribir un programa que almacene los vectores (1,2,3) y (-
1,0,2) en dos listas y muestre por pantalla su producto
escalar.
'''
print("--- Ejercicio 11 ---")

a = (1, 2, 3)
b = (-1, 0, 2)
product = 0
for i in range(len(a)):
    product += a[i]*b[i]
print("El producto de los vectores" + str(a) + " y " + str(b) + " es " + str(product))

'''
Ejercicio 12
Escribir un programa que almacene las
en una lista y muestre por pantalla su producto.
Nota: Para representar matrices mediante listas usar listas
anidadas, representando cada vector fila en una lista.
'''
print("--- Ejercicio 12 ---")

a = ((1, 2, 3),(4, 5, 6))
b = ((-1, 0),(0, 1),(1,1))
result = [[0,0],[0,0]]
for i in range(len(a)):
    for j in range(len(b[0])):
        for k in range(len(b)):
            result[i][j] += a[i][k] * b[k][j]
for i in range(len(result)):
    result[i] = tuple(result[i])
result = tuple(result)
for i in range(len(result)):
    print(result[i])

'''
Ejercicio 13
Escribir un programa que pregunte por una muestra de
números, separados por comas, los guarde en una lista y
muestre por pantalla su media y desviación típica.
'''
print("--- Ejercicio 13 ---")

sample = input("Introduce una muestra de números separados por comas: ")
sample = sample.split(',')
n = len(sample)
for i in range(n):
    sample[i] = int(sample[i])
sample = tuple(sample)
sum = 0
sumsq = 0
for i in sample:
    sum += i
    sumsq += i**2
mean = sum/n
stdev = (sumsq/n-mean**2)**(1/2)
print('La media es', mean, ', y la desviación típica es', stdev)

Python/Ejercicios/Ejercicios de listas y tuplas/listas y tuplas.py