import numpy as np
from tensorflow import keras
import tensorflow as tf

class NormalSampling(keras.layers.Layer):
  """Implements reparametrization trick (based on VAE Keras example)."""

  def __init__(self, **kwargs):
    super(NormalSampling, self).__init__(**kwargs)

  def call(self, inputs):
    z_mean, z_log_var = inputs
    epsilon = tf.keras.backend.random_normal(shape=tf.shape(z_mean))
    return z_mean + tf.exp(0.5 * z_log_var) * epsilon

class Sunken(keras.Model):
  """Semi sUpervised NetworK ENsemble.

  Implements the ensemble of semi-supervised trained networks
  with some shared weights.
  """

  def __init__(self, shared_model_input, shared_model_output, ensemble_count, alpha=1.0, **kwargs):
    super(Sunken, self).__init__(**kwargs)

    self.x = shared_model_output
    self.z_mean = keras.layers.Dense(ensemble_count, name="z_mean")(self.x)
    self.z_log_var = keras.layers.Dense(ensemble_count, name="z_log_var")(self.x)
    self.z = NormalSampling(name="z")([self.z_mean, self.z_log_var])

    self.total_loss_tracker = keras.metrics.Mean(name="total_loss")
    self.supervised_loss_tracker = keras.metrics.Mean(name="supervised_loss")
    self.unsupervised_loss_tracker = keras.metrics.Mean(name="unsupervised_loss")

    self.ensemble = keras.Model(
        shared_model_input,
        [self.z, self.z_mean, self.z_log_var])

    self.alpha = alpha

  def summary(self, *args, **kwargs):
    self.ensemble.summary(*args, **kwargs)

  def get_layer(self, *args, **kwargs):
    return self.ensemble.get_layer(*args, **kwargs)

  def call(self, inputs):
    z, z_mean, z_log_var = self.ensemble(inputs)
    return z_mean

  def predict(self, inputs):
    z, z_mean, z_log_var = self.ensemble.predict(inputs)
    return z_mean

  def score_layer(self):
    return keras.layers.Concatenate()([self.z_mean, self.z_log_var])

  @property
  def metrics(self):
    return [
        self.total_loss_tracker,
        self.supervised_loss_tracker,
        self.unsupervised_loss_tracker,
    ]

  def train_step(self, data):
    x, y = data
    with tf.GradientTape() as tape:
      z, z_mean, z_log_var = self.ensemble(x, training=True)

      supervised_loss = tf.square(y) * (tf.exp(-y*z + self.alpha) + tf.exp(z_log_var))
      unsupervised_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
      total_loss = supervised_loss + unsupervised_loss

    grads = tape.gradient(total_loss, self.ensemble.trainable_weights)
    self.optimizer.apply_gradients(zip(grads, self.ensemble.trainable_weights))

    self.total_loss_tracker.update_state(total_loss)
    self.supervised_loss_tracker.update_state(supervised_loss)
    self.unsupervised_loss_tracker.update_state(unsupervised_loss)

    return {
      "total_loss": self.total_loss_tracker.result(),
      "supervised_loss": self.supervised_loss_tracker.result(),
      "unsupervised_loss": self.unsupervised_loss_tracker.result(),
    }

def prepare_sunken_multiple_output(rng, expected, ensemble_count, output_count, labeled_count):
  def binarize(y, v):
    x = np.zeros(y.shape)
    x[np.where(y != 0)[0], 0] = -1
    x[np.where(y == v)[0], 0] = 1 # order here matters, since we want to overwrite negative ones
    return x

  def sample():
    y = np.zeros((expected.shape[0], 1))
    lab = rng.choice(np.where(expected != 0)[0], labeled_count)
    y[lab, 0] = expected[lab]
    return np.concatenate([ binarize(y, i + 1) for i in range(output_count) ], axis=1)

  return np.concatenate(
      [ sample() for _ in range(ensemble_count) ],
      axis=1)


import itertools
from datetime import date
from typing import Dict
from typing import Iterator
from typing import List
from typing import Tuple

from dateutil.relativedelta import relativedelta

from homecomp import const
from homecomp.models import BudgetItem
from homecomp.models import MonthlyExpense
from homecomp.models import NetworthMixin

def format_currency(value) -> str:
    currency = '${:,.2f}'.format(abs(value))
    if value < 0:
        currency = f'({currency})'
    return currency

def iter_months(start: date = None) -> Iterator[str]:
    start = start or date.today()

    while True:
        yield start.strftime('%b, %Y')
        start += relativedelta(months=1)

def get_networth_items(budget_items: List[BudgetItem]) -> Dict[str, BudgetItem]:
    """Return only budget items which have value"""
    return {
        budget_item.name: budget_item
        for budget_item in budget_items
        if isinstance(budget_item, NetworthMixin)
    }

def get_asset_table(budget_items: List[BudgetItem], periods: int) -> Tuple:
    networth_items = get_networth_items(budget_items)
    months = iter_months()

    headers = ['Time']
    headers += list(networth_items.keys())
    headers += ['Total']

    rows = []
    for period in range(const.INIT_PERIOD, periods + 1):
        row = {'Time': next(months)}
        row.update({
            key: format_currency(networth_item.get_period_value(period))
            for key, networth_item in networth_items.items()
        })
        row['Total'] = format_currency(sum(
            networth_item.get_period_value(period)
            for networth_item in networth_items.values()
        ))

        rows.append(row)

    return headers, rows

def get_asset_delta(budget_items: List[BudgetItem]) -> str:
    networth_items = get_networth_items(budget_items)

    final_value = sum(item.value for item in networth_items.values())
    init_value = sum(item.values[const.INIT_PERIOD] for item in networth_items.values())

    gains = final_value - init_value
    return format_currency(gains)

def get_average_cost(expenses: List[MonthlyExpense]) -> str:
    """
    Return the average montly cost of expenses over lifetime.

    This will not take into account appreciation of any assets. This value will
    deviate from most home buying vs. renting calculators because those calculators do
    use home appreciation to offset costs. The asset delta should be used when
    comparing against other calculators.
    """
    return format_currency(
        -sum(expense.costs for expense in expenses) / len(expenses)
    )

def _traverse_expense(expense: MonthlyExpense, column: str = '') -> Dict:
    """
    Build an expense row by traversing expense tree.

    Flip all of the expense totals so that expenses are displayed as positives.
    """
    if not expense.components:
        return {column: format_currency(-expense.total)}

    column = f'{column}.' if column else ''
    row = {}

    for component in expense.components:
        row.update(_traverse_expense(component, f'{column}{component.name}'))

    row[f'{column}Total'] = format_currency(-expense.total)
    return row

def get_expense_table(expenses: List[MonthlyExpense]):
    months = iter_months(date.today() + relativedelta(months=1))

    rows = [
        {
            'Time': next(months),
            **_traverse_expense(expense)
        }
        for expense in expenses
    ]

    headers = list(rows[0].keys())

    if any(set(row.keys()) != set(headers) for row in rows[1:]):
        raise ValueError('Allxpenses are not available across all periods')

    return headers, rows

def get_header_spans(headers: List[str]):
    """
    Split list of composite headers into simple headers with colspan values.

    If table headers are composite values (e.x. Home.Mortage) then return a list of
    header rows that group each header value under common parent headers. For the following
    header grouping:

    |      |           Home              |       |
    | Time | Mortage | ... | Maintenance | Total |

    The output would be:

    [
        [('', 1), ('Home', 3), ('', 1)],
        [('Time', 1), ('Mortgage', 1), ('...', 1), ('Maintenance', 1), ('Total', 1)]
    ]
    """
    header_rows = []
    split_headers = [
        header.split('.')
        for header in headers
    ]
    max_split = max([len(header) for header in split_headers])

    for idx in range(-1, -max_split - 1, -1):
        header_row = []

        for header in split_headers:
            try:
                header_row.append(header[idx])
            except IndexError:
                header_row.append('')

        # group headers together into spans
        header_row = [
            (key, len(list(group)))
            for key, group in itertools.groupby(header_row)
        ]

        header_rows = [header_row] + header_rows

    return header_rows


def extractMike777ac(item):
	"""
	# Mike777ac

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not postfix and ':' in item['title']:
		postfix = item['title'].split(':')[-1]
	if ('Hardcore OPness' in item['tags'] or 'HCOP' in item['tags']) and (chp or vol):
		return buildReleaseMessageWithType(item, 'Hardcore OP-ness', vol, chp, frag=frag, postfix=postfix, tl_type='oel')


from django.test import Client, TestCase
from ..models import Post, Group, User
from django.urls import reverse
from django.core.cache import cache

class PostsCacheTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.group = Group.objects.create(
            title='Группа тестовых групп',
            slug='test-slug-slug',
            description='Давайте опишем'
        )
        cls.post1 = Post.objects.create(
            author=User.objects.create_user(username='Masha'),
            text='Новый тест',
            group=cls.group,
        )

    def setUp(self):
        cache.clear()
        self.guest_client = Client()

    def test_cache(self):
        """Проверяем, что посты на главной странице кешируютсяю."""
        response0 = self.guest_client.get(reverse('posts:main_view')).content
        self.post1.delete()
        response1 = self.guest_client.get(reverse('posts:main_view')).content
        self.assertEqual(response0, response1)
        cache.clear()
        response2 = self.guest_client.get(reverse('posts:main_view')).content
        self.assertNotEqual(response1, response2)


import torch
import torch.nn as nn
import deepspeed
import torch.nn.functional as F

# Define the model
class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        # Shared layers
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
        self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding=1)

        # Classification head
        self.fc1 = nn.Linear(128 * 16 * 16, 64)
        self.dropout = nn.Dropout(0.5)
        self.fc2 = nn.Linear(64, 1)
        self.sigmoid = nn.Sigmoid()

        # Segmentation head
        self.conv_trans1 = nn.ConvTranspose2d(128, 64, kernel_size=3, padding=1)
        self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
        self.conv_trans2 = nn.ConvTranspose2d(64, 32, kernel_size=3, padding=1)
        self.conv_trans3 = nn.ConvTranspose2d(32, 16, kernel_size=3, padding=1)
        self.conv_trans4 = nn.ConvTranspose2d(16, 16, kernel_size=3, padding=1)
        self.conv_trans5 = nn.ConvTranspose2d(16, 1, kernel_size=1)

    def forward(self, x):
        #(N,H,W,C)->(N,C,H,W)
        x = torch.permute(x,(0,3,1,2))
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.pool(F.relu(self.conv3(x)))
        x = self.pool(F.relu(self.conv4(x)))
        # Classification head
        x_class = x.reshape(-1, 128 * 16 * 16)
        x_class = F.relu(self.fc1(x_class))
        x_class = self.dropout(x_class)
        x_class = self.sigmoid(self.fc2(x_class))

        # Segmentation head
        x_seg = F.relu(self.conv_trans1(x))
        x_seg = self.upsample(x_seg)
        x_seg = F.relu(self.conv_trans2(x_seg))
        x_seg = self.upsample(x_seg)
        x_seg = F.relu(self.conv_trans3(x_seg))
        x_seg = self.upsample(x_seg)
        x_seg = F.relu(self.conv_trans4(x_seg))
        x_seg = self.upsample(x_seg)
        x_seg = self.sigmoid(self.conv_trans5(x_seg))

        return x_class, torch.permute(x_seg, (0,2,3,1))


import sys
from typing import List, NewType, Union

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# Magic values.
SEPARATOR = "separator"

class AutoHideMenuBar(QMenuBar):
    """A menu bar that hides itself automatically when out of focus."""
    def __init__(self) -> None:
        super().__init__()
        self.hide()

    def focusOutEvent(self, event: QFocusEvent) -> bool:
        """Hide the menu bar unless the focus went to a menu."""
        if event.reason() != Qt.PopupFocusReason:
            self.hide()
        return super().focusOutEvent(event)

    def keyPressEvent(self, event: QKeyEvent) -> None:
        """Show the menu bar and grab focus when Alt is pressed. Close it on Alt or Escape."""
        if event.key() == Qt.Key_Alt:
            if self.isVisible():
                self.hide()
                self.clearFocus()
                return None
            else:
                self.show()
                self.setFocus()
                return None
        if event.key() == Qt.Key_Escape:
            self.hide()
            self.clearFocus()
            return None
        return super().keyPressEvent(event)

class Main(QMainWindow):
    """The application main window."""
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.setupUI()

    def setupUI(self) -> None:
        self.setWindowTitle("Autohide")
        self.resize(600, 400)
        self.centralWidget = QLabel("Press Alt to show the menu bar.")
        # Ensure that something (anything) else than the menu bar can grab the focus.
        self.centralWidget.setFocusPolicy(Qt.StrongFocus)
        self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setCentralWidget(self.centralWidget)

        appActions = self.__createAppActions()
        _addActions(self, appActions)

        menubar = AutoHideMenuBar()
        self.setMenuBar(menubar)

        appMenu = QMenu("&Application", menubar)
        _addActions(appMenu, appActions)
        menubar.addMenu(appMenu)

        helpMenu = QMenu("&Help", menubar)
        helpMenu.addSection("For illustration only")
        menubar.addMenu(helpMenu)
        _addActions(helpMenu, appActions)

    def __createAppActions(self) -> None:
        quitAction = QAction("&Quit", self)
        quitAction.setIcon(QIcon.fromTheme("application-exit"))
        quitAction.setShortcut(QKeySequence.Quit)
        quitAction.triggered.connect(self.close)
        return [
                quitAction,
        ]

    def keyPressEvent(self, event: QKeyEvent) -> None:
        """Ensure the menu bar receives the event that will open it initially."""
        if event.key() == Qt.Key_Alt:
            self.menuBar().keyPressEvent(event)
        return super().keyPressEvent(event)

def _addActions(parent: QMenu, actions: List[Union[QAction, str]]) -> None:
    """Add actions to a menu or toolbar, add separator if action is None."""
    for action in actions:
        if action is SEPARATOR:
            action = QAction(parent)
            action.setSeparator(True)
        parent.addAction(action)

app = QApplication(sys.argv)

# Periodically listen for Unix signals (e.g. SIGINT)
timer = QTimer()
timer.start(500)
timer.timeout.connect(lambda: None)

window = Main()
window.show()
sys.exit(app.exec())


### Payroll Processor
### by Andrew Kramer
#

"""

This program asks the user to enter an employee's name, pay rate, and hours worked in a week. It then calculates their pay, including potential overtime pay, and displays it.

After data for three employee's is entered/processed/displayed, it displays the total sum of all three employee's pay.

"""
### PSEUDOCODE
"""

- Import payrollModule module as payroll for pay calculation functions.

Define the main function:

- Establish accumulator variable.
- Establish for loop with a range of 3 to allow entry and processing of data for 3 employees.

- Within the for loop, call the pay function within the payroll module to process the data and receive the calculated value back from the function.

- Print each data result for each employee
- Print the sum of all employees' pay.

"""

# Import payrollModule module as payroll.

import payrollModule as payroll

# Define the main function of the program.

def main():

    # Establish accumulator variable to add each employee's pay
    # to calculate the total payroll for the week.

    total_payroll = 0.00

    # Establish for range to allow entry for the data of the 3 employees.

    for employees in range(3):

        # Ask the user to enter the employee's name and assign it to the name variable.

        name = input('Enter employee name: ')

        # Ask the user to enter the employee's hourly pay rate and assign it to the hourly_rate variable.

        hourly_rate = float(input(f'Enter hourly rate for {name}: '))

        # Ask the user to enter the employee's quantity of hours for the week and assign it to the week_hours variable.

        week_hours = int(input(f'Enter hours for {name} this week: '))

        # Call the pay function within the payroll module to calculate the pay
        # by passing it the hourly_rate and week_hours arguments and then
        # assigning the returned value to the emp_pay variable.

        emp_pay = payroll.pay(hourly_rate, week_hours)

        # Print the calculated pay for the employee.

        print(f'Pay for {name} is ${emp_pay:.2f}')

        # Use the accumulator variable to keep a running total.

        total_payroll = total_payroll + emp_pay

    # Print the running total for the week.

    print(f'Total payroll for the week is ${total_payroll:,.2f}')

# Call the main function ONLY if the file is being run as
# a standalone program.

if __name__ == '__main__':

    main()


import random
import fontstyle as fnt
import os

os.system('cls')

def RPS():

  number_of_turns = 10
  options = ['Rock', 'Paper', 'Scissors']

  upoint = 0
  cpoint = 0
  turns = 1
  while (turns <= number_of_turns):
    try:
      user = int(
        input(
          fnt.apply("Enter 1 for Rock || 2 for Paper || 3 for Scissors: ",
                    "blue/bold")))
    except (TypeError, ValueError):
      continue

    computer = random.choice(options)

    if computer == 'Rock':

      if user == 1:
        print(fnt.apply("None of you got a point.", "cyan/bold"))

      elif user == 2:
        print(fnt.apply("You got a point!", 'green/bold'))
        upoint += 1

      elif user == 3:
        print(fnt.apply("Compouter got a point!", "red/bold"))
        cpoint += 1

    elif computer == 'Paper':
      if user == 2:
        print(fnt.apply("None of you got a point.", "cyan/bold"))

      elif user == 3:
        print(fnt.apply("You got a point!", 'green/bold'))
        upoint += 1
        print(fnt.apply(f'Computer: {cpoint} || User: {upoint}',
                        'yellow/bold'))
      elif user == 1:
        print(fnt.apply("Compouter got a point!", "red/bold"))
        cpoint += 1

    else:
      if user == 3:
        print(fnt.apply("None of you got a point.", "cyan/bold"))

      elif user == 1:
        print(fnt.apply("You got a point!", 'green/bold'))
        upoint += 1

      elif user == 2:
        print(fnt.apply("Compouter got a point!", 'red/bold'))
        cpoint += 1

    print(fnt.apply(f'Computer: {cpoint} || User: {upoint}', 'yellow/bold'))
    print(fnt.apply(f'Turn {number_of_turns - turns}', 'white/bold'))
    turns += 1

RPS()


import datetime as dt
from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models

from api_yamdb.settings import ROLE_TYPE
from api.validators import validate_username_pattern
from reviews.base_models import BaseModel

class CustomUser(AbstractUser):
    """Кастомная модель пользователей"""
    username = models.CharField(
        max_length=150,
        unique=True,
        blank=False,
        validators=[
            validate_username_pattern,
        ],
    )
    role = models.CharField(
        verbose_name='Роль',
        max_length=10,
        blank=False,
        choices=ROLE_TYPE,
        default=ROLE_TYPE[0][1],
    )
    email = models.EmailField(
        max_length=254,
        unique=True,
        blank=False,
    )
    first_name = models.CharField(
        verbose_name='Имя',
        max_length=150,
        blank=True,
    )
    last_name = models.CharField(
        verbose_name='Фамилия',
        max_length=150,
        blank=True,
    )
    bio = models.TextField(
        verbose_name='Биография',
        blank=True,
    )

    @property
    def is_admin(self):
        return self.role == ROLE_TYPE[2][1] or self.is_superuser

    @property
    def is_moderator(self):
        return self.role == ROLE_TYPE[1][1] or self.is_superuser

class Genre(BaseModel):
    """Модель жанров."""
    slug = models.SlugField(max_length=50, unique=True)

    def __str__(self) -> str:
        return f'{self.name}, {self.slug}'

class Category(BaseModel):
    """Модель категорий."""
    slug = models.SlugField(max_length=50, unique=True)

    def __str__(self) -> str:
        d = {'name': self.name, 'slug': self.slug}
        return f'{d}'

class Title(BaseModel):
    """Модель произведений и её привязка к жанрам и категориям."""
    year = models.IntegerField(
        verbose_name='Год выхода',
        validators=[MaxValueValidator(dt.date.today().year)],
        db_index=True,
    )
    description = models.TextField(
        verbose_name='Описание',
        null=True,
        blank=True
    )
    genre = models.ManyToManyField(
        Genre,
        related_name='titles',
        verbose_name='Жанр',
    )
    category = models.ForeignKey(
        Category,
        blank=True,
        null=True,
        related_name='titles',
        on_delete=models.SET_NULL,
        verbose_name='Категория',
    )

class Review(models.Model):
    """Модель отзывов на произведения, а так же их рейтинг"""
    author = models.ForeignKey(
        CustomUser,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='Автор',
    )
    text = models.TextField(
        null=False,
        verbose_name='Текст отзыва',
    )
    pub_date = models.DateTimeField(
        'Дата публикации',
        auto_now_add=True,
    )
    title = models.ForeignKey(
        Title,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='Произведение',
    )
    score = models.IntegerField(
        verbose_name='Рейтинг',
        validators=[
            MinValueValidator(1, 'Разрешены значения от 1 до 10'),
            MaxValueValidator(10, 'Разрешены значения от 1 до 10'),
        ]
    )

    def __str__(self):
        return self.text

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['title', 'author'],
                name='unique_title_author'
            )
        ]
        verbose_name = 'Отзыв'
        verbose_name_plural = 'Отзывы'
        ordering = ['-pub_date']

class Comment(models.Model):
    """Модель комментариев к отзыву произведений."""
    author = models.ForeignKey(
        CustomUser,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='Автор'
    )
    text = models.TextField(verbose_name='Текст комментария',)
    pub_date = models.DateTimeField(
        'Дата публикации',
        auto_now_add=True,
    )
    review = models.ForeignKey(
        Review,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='Отзыв',
    )

    class Meta:
        ordering = ['-pub_date']


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from collections import namedtuple

#group2
gaussian = (3.34, 2.68, 4.32)

label = ('(a) baseline', '(b)', '(c)', '(d)')

fig, ax = plt.subplots()

index = np.arange(4)
index1 = np.arange(1)
index2 = np.arange(3)+1
bar_width = 0.25
plt.ylim(0, 5)
plt.axhline(y=1, color='grey', linewidth=0.5,linestyle='--')

minorLocator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minorLocator)
plt.tick_params(which='minor', length=4)
plt.tick_params(which='major', bottom=False,top=False)

rGCuda = ax.bar(index1-1.15*bar_width, 2.76, bar_width,
                alpha=0.8, color='black') #, hatch='//')
rGOpencl = ax.bar(index1, 1.65, bar_width,
               alpha=0.4, color='black') #hatch='\\')
rBfsOpencl = ax.bar(index1+1.15*bar_width, 1, bar_width,
                    alpha=0.6, color='black', hatch='//')

rgaussian = ax.bar(index2-0.6*bar_width, gaussian, bar_width,
                   alpha=0.4, color='black')
rgaussian_g = ax.bar(index1+1+0.6*bar_width, 3.34, bar_width,
                     alpha=0.4, color='black')
rgaussian_bfs = ax.bar(index1+2+0.6*bar_width, 1.81, bar_width,
                       alpha=0.6, color='black', hatch='//')
rgaussian_cuda = ax.bar(index1+3+0.6*bar_width, 4.09, bar_width,
                        alpha=0.8, color='black')

ax.set_xticks(index)
ax.set_xticklabels(label)

fig.tight_layout()

def autolabel(rects, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  # normalize the case of the parameter
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
                '{}'.format(height), ha=ha[xpos], va='bottom')

plt.gcf().set_size_inches(6,4.5)
autolabel(rGCuda)
autolabel(rGOpencl)
autolabel(rBfsOpencl)
autolabel(rgaussian)
autolabel(rgaussian_g)
autolabel(rgaussian_bfs)
autolabel(rgaussian_cuda)

plt.ylabel('Relative Runtime')
ax.legend((rGCuda, rGOpencl, rBfsOpencl), ('gaussian (cuda)', 'gaussian (opencl)', 'bfs (cl)'),loc='upper center', ncol=3)
plt.savefig('concurrency.png', dpi = 600, bbox_inches='tight')
plt.show()


import sys

from sketchgraphs.data.sequence import NodeOp, EdgeOp
from src.utils import flat_array
from src.sinks.sink_sequence import SinkSequence
import os
import logging
import unittest

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

class TestSinkSequence(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.output_path = 'tests/asset/out/my_file.npy'
        self.clean = True
        sequence1 = [NodeOp(label=2), EdgeOp(label=2, references=None), NodeOp(label=1)]
        sequence2 = [NodeOp(label=2)]
        sequence3 = [EdgeOp(label=2, references=None)]
        self.list_of_seqs = [sequence1, sequence2, sequence3]

    def test_process(self):
        sink = SinkSequence(conf_filter={'output_path': self.output_path})
        for seq in self.list_of_seqs:
            message = {'sequence': seq}
            _ = sink.process(message)

        self.assertEqual(sink.collect_data, self.list_of_seqs)

    def test_last_process(self):
        sink = SinkSequence(conf_filter={'output_path': self.output_path})
        sink.collect_data = self.list_of_seqs

        _ = sink.last_process(message={})
        saved_sequences = flat_array.load_flat_array(self.output_path)
        for og_seq, saved_seq in zip(self.list_of_seqs, saved_sequences):
            self.assertEqual(og_seq, saved_seq)

    def tearDown(self):
        # Clean and remove created files
        if self.clean and os.path.exists(self.output_path):
            os.remove(self.output_path)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 27 00:40:44 2018

@author: praveen
"""
from models.common import *
from models.activities import *

class Announcement(Object):
  def __init__(self, courseId=None, id=None, text=None, state='PUBLISHED',
               alternateLink=None, creationTime=None, updateTime=None,
               scheduledTime=None, assigneeMode='ALL_STUDENTS', creatorUserId=None):
    self.courseId=courseId
    self.id=id
    self.text=text
    self.state=state
    self.alternateLink=alternateLink
    self.creationTime=creationTime
    self.updateTime=updateTime
    self.scheduledTime=scheduledTime
    self.assigneeMode=assigneeMode
    self.creatorUserId=creatorUserId


from PIL import Image
from collections import defaultdict

def return_colors(img):
    img = Image.open(img)
    by_color = defaultdict(int)
    for pixel in img.getdata():
        by_color[pixel] += 1
    return (sorted(by_color.items(), key=lambda item: item[1]))[-10:]

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', "TIFF", "PSD", "RAW", "BMP"}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


#!/usr/bin/env python
# coding: utf-8

# In[46]:

import panel as pn
pn.extension('plotly')
import plotly.express as px
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os
from pathlib import Path
from dotenv import load_dotenv

import warnings
warnings.filterwarnings('ignore')

import hvplot.pandas

# In[2]:

load_dotenv()
map_box_api = os.getenv("mapbox_token")
px.set_mapbox_access_token(map_box_api)
type(map_box_api)

# In[ ]:

# In[3]:

# housing units per year

## rental analysis

# In[ ]:

# In[4]:

sfo_data = pd.read_csv("C:/Users/danie/smu_files/sfo_neighborhoods_census_data.csv", index_col="year")
sfo_data.head()

# In[5]:

sfo_mean = sfo_data.groupby("year").mean()
sfo_mean

# In[6]:

housing_units_mean = sfo_mean["housing_units"]
housing_units_mean

# In[7]:

housing_units_plots = housing_units_mean.plot.bar(title='housing units in san francisco from 2010 to 2016')

# In[ ]:

# In[8]:

# housing costs in san francisco per year

# In[ ]:

# In[9]:

sfo_mean[['sale_price_sqr_foot','gross_rent']]

# In[10]:

gross_rent = sfo_mean['gross_rent']

# In[11]:

gross_rents_plot = gross_rent.plot(title= 'average gross rent by year')

# In[12]:

sale_price_sqr_foot=sfo_mean['sale_price_sqr_foot']

# In[13]:

rent_plot = sale_price_sqr_foot.plot(title = "average price per sqft by year")

# In[ ]:

# In[14]:

# average prices by neighborhood

# In[ ]:

# In[15]:

year_neighborhood = sfo_data.groupby(["year","neighborhood"]).mean().reset_index()
year_neighborhood.head(10)

# In[16]:

neighborhood_sales = year_neighborhood.hvplot.line(x='year',y='sale_price_sqr_foot', groupby='neighborhood')

# In[17]:

neighborhood_sales

# In[18]:

neighborhood_rents = year_neighborhood.hvplot.line(x='year',y='gross_rent', groupby='neighborhood')

# In[19]:

neighborhood_rents

# In[ ]:

# In[20]:

# top 10 most expensive neighborhoods in SFO

# In[ ]:

# In[21]:

ten_most_expensive=sfo_data.groupby(["neighborhood"]).mean().sort_values('sale_price_sqr_foot', ascending = False).head(10).reset_index()
ten_most_expensive

# In[22]:

top_10 = ten_most_expensive.hvplot.bar(x='neighborhood',y='sale_price_sqr_foot', title = 'top 10 expensive neighborhoods in SFO', rot = 45, height = 500)

# In[23]:

top_10

# In[ ]:

# In[24]:

# comparing cost to purchase versus rental income

# In[ ]:

# In[25]:

year_neighborhood.head()

# In[26]:

side_by_side=year_neighborhood.drop(['housing_units'], axis=1)
side_by_side.head()

# In[ ]:

# In[27]:

side_plot = side_by_side.hvplot.bar('year', groupby = 'neighborhood', rot=90, title = 'average price per square foot versus average monthly rent by year by neighborhood', height = 400)

# In[28]:

side_plot

# In[ ]:

# In[29]:

# neighborhood map

# In[ ]:

# In[30]:

coordinates = pd.read_csv('C:/Users/danie/smu_files/neighborhoods_coordinates.csv')
coordinates.head()

# In[31]:

map_data = sfo_data.groupby("neighborhood").mean().reset_index()
map_data.head()

# In[32]:

map_data.shape

# In[33]:

combined_map = pd.concat([coordinates,map_data], axis = 1, join = 'inner')
combined_map.head()

# In[34]:

scatter_price = px.scatter_mapbox(combined_map,
                 lat='Lat',
                 lon='Lon',
                 color='Neighborhood',
                 size='sale_price_sqr_foot',
                 zoom=11,
                 title = 'average sale price per square foot in san francisco')

# In[35]:

scatter_price

# In[36]:

scatter_rent = px.scatter_mapbox(combined_map,
                 lat='Lat',
                 lon='Lon',
                 color='Neighborhood',
                 size='gross_rent',
                 zoom=11,
                 title = 'average rent price per square foot in san francisco')

# In[47]:

scatter_rent

# In[ ]:

# In[38]:

# dashboard

# In[ ]:

# In[39]:

def get_price_per_sf():
    scatter_price
    return scatter_price

def get_rent_per_sf():
    scatter_rent
    return scatter_rent

# In[40]:

sf_analysis = pn.Column(

    '#real estate analysis of san francisco from 2010 to 2016',
    housing_units_plots.get_figure(),
    gross_rents_plot.get_figure(),
    rent_plot.get_figure()

)

# In[41]:

neighborhood_analysis = pn.Column(

    '#san francisco neighborhood real estate analysis',
    top_10,
    neighborhood_sales,
    neighborhood_rents,
    side_plot

)

# In[42]:

price_rent = pn.Column(

    '#visual map of average neighborhood prices per square foot in san francisco',
    scatter_price,
    scatter_rent

)

# In[43]:

dashboard = pn.Tabs(

    ('real estate prices', sf_analysis ),
    ('neighborhood analysis', neighborhood_analysis),
    ('price vs. rent', price_rent)

)

# In[48]:

dashboard.servable()

# In[ ]:

# In[45]:

# panel serve pyviz_homework_v1_dashboard.ipynb --log-level debug --show

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:


from django.contrib import admin
from django.urls import path, include, re_path
from .views import SerialList, OpinionList
from subeer import views

urlpatterns = [
    path("", SerialList.as_view(), name="list"),
    path("search", views.search, name="search"),
    path("popular", views.popular, name="popular"),
    path("new_serials", views.new_serials, name="new_serials"),
    path("new_episodes", views.new_episodes, name="new_episodes"),
    path("opinion", views.get_opinion, name="opinion"),
    path("list_opinion", OpinionList.as_view(), name="list_opinion"),
    re_path(r"^like/$", views.serial_like, name="like"),
    path("<slug:slug>/", views.detail_episode, name="details"),
]


from data_handler.models import ButtonSlug, ButtonUrl, Request, TelegarmUser, Text, TextButtonSlug, TextButtonUrl
from rest_framework import serializers

class ButtonSlugSerializer(serializers.ModelSerializer):
    slug = serializers.SlugRelatedField(slug_field="slug", read_only=True)

    class Meta:
        model = ButtonSlug
        fields = ("id", "cover_text", "slug")

class ButtonUrlSerializer(serializers.ModelSerializer):
    class Meta:
        model = ButtonUrl
        fields = ("id", "cover_text", "url")

class ButtonSerializer(serializers.Serializer):
    ButtonSlug = ButtonSlugSerializer(many=True)
    ButtonUrl = ButtonUrlSerializer(many=True)

class TextButtonSlugSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source="button.id")
    cover_text = serializers.ReadOnlyField(source="button.cover_text")
    slug = serializers.SlugRelatedField(source="button.slug", slug_field="slug", read_only=True)

    class Meta:
        model = TextButtonSlug
        fields = ("id", "cover_text", "slug", "order")

class TextButtonUrlSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source="button.id")
    cover_text = serializers.ReadOnlyField(source="button.cover_text")
    url = serializers.ReadOnlyField(source="button.url")

    class Meta:
        model = TextButtonUrl
        fields = ("id", "cover_text", "url", "order")

class TextSerializer(serializers.ModelSerializer):
    button_slug = TextButtonSlugSerializer(
        source="buttonslug_list.all",
        many=True,
    )
    button_url = TextButtonUrlSerializer(
        source="buttonurl_list.all",
        many=True,
    )

    class Meta:
        model = Text
        fields = "__all__"

class RequestSerializer(serializers.ModelSerializer):
    text = TextSerializer(required=False)

    class Meta:
        model = Request
        fields = ("id", "text", "request", "processing_status", "counter", "created_at", "requestuser")

    def validate(self, attrs):
        if self.context["request"].method != "POST":
            return attrs
        if Request.objects.filter(**attrs).exists():
            raise serializers.ValidationError("This object already exists")
        return attrs

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = TelegarmUser
        fields = "__all__"

    def validate(self, attrs):
        if self.context["request"].method != "POST":
            return attrs
        if TelegarmUser.objects.filter(**attrs).exists():
            raise serializers.ValidationError("This object already exists")
        return attrs


import matplotlib.pyplot as plt
import os
import pandas as pd
import numpy as np

if __name__ == '__main__':
    train_root = './models/'
    root = './result/'
    res = {
        'method': [],
        'nfilter': [],
        'mean_costs': [],
        'encoding_costs': [],
        'infer_costs': [],
        'sampling_costs': []
    }
    name_map = {'encoding_costs': 'EncodingCost',
                'infer_costs':'InferenceCost',
                'sampling_costs': 'SamplingCost'}
    exps = [('Duet', 'cup98_mlp_binary_filter{}', 'solid', 'x'), ('Naru', 'Naru_cup98_binary_filter{}', 'dashed', 'o'), ('UAE', 'UAE_cup98_binary_filter{}', 'dashdot', '^')]
    nfilters = [2, 4, 8, 16, 32, 64, 100]
    cate_nfilters = list(map(lambda x: str(x), nfilters))
    width = 0.15
    color = ['C0', 'C1', 'C2', 'C3']
    textures = ["///" , "\\\\"  , "---"]
    plt.figure(figsize=(5, 2.5), dpi=300)
    # fig, axes = plt.subplots(nrows=1, ncols=3, sharex='col', sharey='row', squeeze=True, layout='constrained')
    for i, (method_name, exp_root, linestyle, marker) in enumerate(exps):
        methods = []
        mean_costs = []
        encoding_costs = []
        infer_costs = []
        sampling_costs = []
        for nfilter in nfilters:
            exp = exp_root.format(nfilter)
            name = exp.split('_')[1]
            df = pd.read_csv(os.path.join(root, exp, 'summary.csv'))
            mean_cost = df['mean_cost'].values.item()
            encoding_cost = df['encoding_cost'].values.item()
            infer_cost = df['infer_cost'].values.item()
            if method_name in ['Naru', 'UAE']:
                sampling_cost = df['sampling_cost'].values.item()
            else:
                sampling_cost = 0
            sampling_costs.append(sampling_cost)
            methods.append(method_name)
            mean_costs.append(mean_cost)
            encoding_costs.append(encoding_cost)
            infer_costs.append(infer_cost)
        res['method'].extend(methods)
        res['mean_costs'].extend(mean_costs)
        res['encoding_costs'].extend(encoding_costs)
        res['infer_costs'].extend(infer_costs)
        res['nfilter'].extend(nfilters)
        res['sampling_costs'].extend(sampling_costs)
    df = pd.DataFrame(res)
    df.to_csv('./result/nfilter.csv', index=None)
    metrics = ['encoding_costs', 'infer_costs', 'sampling_costs']
    have_labeled = set()
    gap = width + 0.05
    cmap = plt.get_cmap("Set2")
    for i, (method_name, exp_root, linestyle, marker) in enumerate(exps):
        method_data = df[df['method'] == method_name]
        pos = []
        for k, nfilter in enumerate(nfilters):
            position = k + gap * (1 - len(exps)) / 2 + i * gap
            pos.append(position)
            method_nfilter_data = method_data[method_data['nfilter'] == nfilter]
            data = method_nfilter_data[metrics].values.flatten()
            # arg_index = np.argsort(data)
            data_cum = np.cumsum(data)
            for j, idx in enumerate(range(len(data))):
                if j not in have_labeled:
                    plt.bar(position, data[idx], bottom=data_cum[idx-1] if idx>0 else 0, zorder=-j, color=cmap(j), width=width, label=name_map[metrics[j]], alpha=0.8, hatch=textures[j])
                    have_labeled.add(j)
                else:
                    plt.bar(position, data[idx], bottom=data_cum[idx-1] if idx>0 else 0, zorder=-j, color=cmap(j), width=width, alpha=0.8, hatch=textures[j])
        plt.plot(pos, method_data['mean_costs'], label=method_name, linestyle=linestyle, color='black', marker=marker, markersize=5)
    plt.xlabel('#involved_columns')
    plt.ylabel('cost(ms)')
    x = np.arange(0, len(cate_nfilters))
    plt.xticks(x, cate_nfilters)
    plt.legend()
    plt.tight_layout()
    plt.savefig('./result/nfilter.png')
    plt.show()


#!/usr/bin/env python

import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
import numpy as np

# Instantiate CvBridge
bridge = CvBridge()

def image_callback(msg):
    print('RGB Image received!')
    try:
        cv2_img = bridge.imgmsg_to_cv2(msg, "mono8")
    except CvBridgeError as e:
        print(e)
    else:
        cv2.imwrite('camera_image.jpeg', cv2_img)

def convert_depth_image(ros_image):
    cv_bridge = CvBridge()
    print('Depth Image received!')
    try:
        depth_image = cv_bridge.imgmsg_to_cv2(ros_image, 'passthrough')
    except CvBridgeError as e:
        print(e)
    depth_array = np.array(depth_image, dtype=np.float32)
    np.save("depth_img.npy", depth_array)
    depth_array = depth_array.astype(np.uint16)
    cv2.imwrite("depth_img.png", depth_array)

def main():
    rospy.init_node('image_listener')
    rospy.Subscriber("/camera/color/image_raw", Image, image_callback,queue_size=1)
    rospy.Subscriber("/camera/depth/image_raw", Image, convert_depth_image,queue_size=1)

    rospy.spin()

if __name__ == '__main__':
    main()


import warnings
warnings.filterwarnings('ignore')

import numpy as np
import tensorflow as tf
import tensorflow.keras as kb
from tensorflow.keras import backend
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

np.random.seed(42)
tf.random.set_seed(42)

# data downloaded from Kaggle
X_train_dir = '../content/Skin_Data/Cancer/Training' # cancer train
y_train_dir = '../content/Skin_Data/Non_Cancer/Training'# non-cancer train
X_test_dir = '../content/Skin_Data/Cancer/Testing' # cancer test
y_test_dir = '../content/Skin_Data/Non_Cancer/Testing' # non-cancer test

train_data = ImageDataGenerator(rescale=1./255,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)
test_data = ImageDataGenerator(rescale=1./255)

X_train = train_data.flow_from_directory(X_train_dir,
                                                           target_size=(224, 224),
                                                           batch_size=32,
                                                           class_mode='binary')

y_train = train_data.flow_from_directory(y_train_dir,
                                                              target_size=(224, 224),
                                                              batch_size=32,
                                                              class_mode='binary')

X_test = test_data.flow_from_directory(X_test_dir,
                                                         target_size=(224, 224),
                                                         batch_size=32,
                                                         class_mode='binary')

y_test = test_data.flow_from_directory(y_test_dir,
                                                            target_size=(224, 224),
                                                            batch_size=32,
                                                            class_mode='binary')

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Conv2D(256, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Conv2D(512, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(loss='binary_crossentropy',
              optimizer=tf.keras.optimizers.Adam(lr=1e-4),
              metrics=['accuracy'])

# cancer
X_history = model.fit(X_train,
                           steps_per_epoch=len(X_train),
                           epochs=100,
                           validation_data=X_test,
                           validation_steps=len(X_test))

# non-cancer
y_history = model.fit(y_train,
                           steps_per_epoch=len(y_train),
                           epochs=100,
                           validation_data=y_test,
                           validation_steps=len(y_test))

train_loss, train_acc = model.evaluate(X_train)
print('Train Acc for cancer:', train_acc)
train_loss, train_acc = model.evaluate(y_train)
print('Train Acc for non-cancer:', train_acc)

# Evaluate the model on the test data
test_loss, test_acc = model.evaluate(X_test)
print('Test Acc for cancer:', test_acc)
test_loss, test_acc = model.evaluate(y_test)
print('Test Acc for non-cancer:', test_acc)

X_test.reset()
y_test.reset()
y_pred_test_cancer = model.predict(X_test)
y_pred_test_noncancer = model.predict(y_test)

y_pred_test_cancer[y_pred_test_cancer <= 0.5] = 0
y_pred_test_cancer[y_pred_test_cancer > 0.5] = 1
y_pred_test_noncancer[y_pred_test_noncancer <= 0.5] = 0
y_pred_test_noncancer[y_pred_test_noncancer > 0.5] = 1

print('Confusion Matrix for cancer:')
print(confusion_matrix(X_test.classes, y_pred_test_cancer))
print('Confusion Matrix for non-cancer:')
print(confusion_matrix(y_test.classes, y_pred_test_noncancer))


import os
import json
import warnings
import numpy as np

from uvicorn.config import LOGGING_CONFIG
from fastapi import FastAPI, Response
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware

# from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime, date

warnings.simplefilter(action="ignore", category=FutureWarning)

from queries import (
    stock_all,
    get_open_mo,
    all_priority_call,
    all_priority_call_test,
    get_kanban_chart_json,
    call_get_processing,
    demand_all,
    get_mo_log,
    get_hk,
    update_processing,
    hk_unreleased_warning,
    get_kanban,
    post_carts,
    get_missing_mos_from_batches,
    get_kanban_list,
    get_5566,
    get_gy3_total_mos,
    batchedMOs,
    batchedInfo,
    delete_carts,
    check_batch_completion,
    get_set_flag,
)

from util_func import ignore_pytz_warning, NpEncoder
from release_gy3 import get_gy3_release2, post_missing_mo_to_batches
from plantsim import set_default_current
from block import update_block_kanban, block_kanban
from rail_kanban import kanban, update_rail_kanban, get_kanban_data, update_gy3_buffer
from wash_priority import wash_priority, update_wash_priority

from teams import send_edgar
from schemas import (
    TeamsMessage,
    CartData,
)

app = FastAPI()

ignore_pytz_warning()

origins = [
    "*"
    # "http://localhost",
    # "http://localhost:5173",
    # "http://127.0.0.1:5173",
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/stock")
def stock():
    db_response = stock_all()
    return Response(db_response, media_type="application/json")

@app.get("/demand_full")
def demand_all_call():
    db_response = demand_all()
    return Response(db_response, media_type="application/json")

@app.get("/get_hk_unreleased_warning")
def get_hk_unreleased():
    db_response = hk_unreleased_warning()
    return Response(db_response, media_type="application/json")

@app.get("/partial_prediction")
def open_mo():
    db_response = get_open_mo(False)
    json_compatible_item_data = jsonable_encoder(db_response)
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.get("/all_priority")
def all_priority(with_m: bool = False):
    db_response = all_priority_call(with_m)
    return Response(db_response, media_type="application/json")

@app.get("/all_priority_grouped")
def all_priority_grouped():
    db_response = all_priority_call(False)
    return Response(json.dumps(db_response, cls=NpEncoder))

@app.get("/all_priority_test")
async def all_priority_test(with_m: bool = True):
    db_response = await all_priority_call_test(with_m)
    return Response(db_response, media_type="application/json")

@app.get("/get_processing")
def get_processing():
    db_response = call_get_processing()
    return Response(db_response, media_type="application/json")

@app.get("/get_kanban_chart")
def get_kanban_chart():
    db_response = get_kanban_chart_json()
    return Response(
        json.dumps(db_response, cls=NpEncoder), media_type="application/json"
    )

@app.get("/get_kanban_df")
def get_kanban_df():
    db_response = get_kanban().to_json(orient="records")
    return Response(db_response, media_type="application/json")

@app.get("/get_kanban_list")
def call_get_kanban_list():
    db_response = get_kanban_list().to_json(orient="records")
    return Response(db_response, media_type="application/json")

@app.get("/get_unreleased_warning")
def get_unreleas_warning():
    db_response = kanban.get_kanban_unreleased()
    return Response(
        json.dumps(db_response, cls=NpEncoder), media_type="application/json"
    )

def test_encoder(obj):
    if isinstance(obj, np.integer):
        return int(obj)
    if isinstance(obj, np.floating):
        return float(obj)
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    if isinstance(obj, datetime):
        return str(obj)[:10]
    if isinstance(obj, date):
        return str(obj)
    if isinstance(obj, np.nan):
        return None
    if isinstance(obj, object):
        return dict(obj)
    raise TypeError(repr(obj) + " is not JSON serializable")

@app.get("/get_gy3_release2")
def call_gy3_release2(target_week: int = 4, pool_week: int = 12):
    hk_unreleased_warning(date=pool_week * 7)
    db_response = get_gy3_release2(target_week * 7, pool_week)
    json_compatible_item_data = jsonable_encoder(db_response)
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.get("/get_gy3_total_mos")
def call_get_gy3_total_mos():
    return Response(json.dumps(get_gy3_total_mos()), media_type="application/json")

@app.get("/submitted_cart_data")
def call_submitted_cart_data():
    plant_sim_data = batchedMOs()
    grouped_data = None
    if plant_sim_data.empty == False:
        moArray = plant_sim_data["order_id"].to_numpy()
        as400_data = batchedInfo(moArray)
        if as400_data.empty == False:
            joined_data = plant_sim_data.merge(as400_data, how="left", on="order_id")
            grouped_data = (
                joined_data.groupby(["batch_id", "released"])
                .apply(lambda x: x.to_dict(orient="records"))
                .to_json()
            )

    return Response(grouped_data, media_type="application/json")

@app.delete("/delete_cart")
def call_delete_cart(delete_info, delete_type):
    json_delete_info = json.loads(delete_info)
    db_response = delete_carts(delete_info=json_delete_info, delete_type=delete_type)
    return Response(db_response, media_type="application/json")

@app.get("/5566")
async def call_5566():
    db_response = get_5566()
    return Response(db_response, media_type="application/json")

@app.get("/get_5566")
def call_get_5566():
    db_response = get_5566()
    return Response(db_response, media_type="application/json")

@app.post("/post_add_carts")
def call_post_carts(carts: CartData):
    db_response = post_carts(carts)
    return Response(json.dumps(db_response), media_type="application/json")

# RELEASE GY
@app.get("/get_mo_log")
def mo_call(mo: str):
    db_response = get_mo_log(mo)
    json_compatible_item_data = jsonable_encoder(db_response)
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.get("/get_hk")
def hk_call(hk: str):
    db_response = get_hk(hk)
    return Response(db_response, media_type="application/json")

@app.post("/teams_message_edgar")
def send_teams_message(item: TeamsMessage):
    db_response = send_edgar(item.writer, item.comment)
    return Response(db_response)

@app.post("/set_holedrill_default")
def send_teams_message(run_id: str, is_default: bool = False):
    db_response = set_default_current(is_default, run_id)
    return Response(db_response)

@app.get("/get_missing_mos_from_batches")
def get_missing_mos():
    db_response = get_missing_mos_from_batches()
    return Response(db_response, media_type="application/json")

@app.get("/get_block_kanban")
def call_generate_block_kanban():
    # db_response = block_kanban
    # db_response = generate_block_kanban()
    json_compatible_item_data = jsonable_encoder(block_kanban.get_data())
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.get("/get_rail_kanban")
def call_generate_rail_kanban():
    response = {
        "kanban": kanban.df.to_dict(orient="records"),
        "mondays": kanban.mondays_str,
    }
    json_compatible_item_data = jsonable_encoder(response)
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.get("/get_kanban_data")
def call_get_kanban_data(data_type: str, target: str, option: str):
    db_response = get_kanban_data(data_type, target, option)
    json_compatible_item_data = jsonable_encoder(db_response)
    return Response(
        json.dumps(json_compatible_item_data), media_type="application/json"
    )

@app.put("/update_gy3_buffer")
def call_update_gy3_buffer(target: str, buff: int):
    print(target, buff)
    db_response = update_gy3_buffer(target, buff)
    return Response(db_response)

@app.get("/calc_kanban_release")
def call_calc_kanban_release(target_week: int = 12):
    db_response = kanban.calc_kanban_release(target_week)
    return Response(db_response, media_type="application/json")

@app.get("/get_wash_priority")
def get_wash_priority():
    db_response = wash_priority.get_data()
    return Response(db_response, media_type="application/json")

def hourly_job():
    # set_kanban(False)
    check_batch_completion()
    post_missing_mo_to_batches()
    print("HOURLY : check_batch_completion, post_missing_mo_to_batches")

def ten_min_job(is_startup=False):
    update_processing()
    get_set_flag(True)
    stock_all(force_update=True)
    demand_all(force_update=True)
    hk_unreleased_warning(date=96)
    update_block_kanban()
    update_wash_priority()
    update_rail_kanban()

    now = datetime.now().strftime("%H:%M:%S")
    if is_startup:
        print(now, " START UP")
    else:
        print(
            now,
            " 10MIN update",
        )

@app.on_event("startup")
async def startup_event():
    ten_min_job(True)
    hourly_job()

async def check_plant_sim_health():
    print("check_plant_sim_health")
    try:
        await all_priority_test()
    except Exception as e:
        send_edgar("all_priority_error", e)

scheduler = AsyncIOScheduler(timezone="EST")
day_trigger = CronTrigger(
    year="*", month="*", day="*", hour="15", minute="30", second="0"
)
if os.name != "nt":
    scheduler.add_job(check_plant_sim_health, day_trigger)
    scheduler.add_job(hourly_job, "interval", hours=1)
    scheduler.add_job(ten_min_job, "cron", minute="2,12,22,32,42,52")

scheduler.start()

LOGGING_CONFIG["formatters"]["access"][
    "fmt"
] = "%(asctime)s [%(name)s] %(levelprefix)s %(message)s"


import threading
from tkinter.constants import *
from tkinter import ttk, messagebox, Text, StringVar, font, Toplevel
# from DownloaderGUI import Application
from .Redirects import StdoutRedirect, StderrRedirect
class OutWin(Toplevel):
    def __init__(self, master, mode: str, title="New window", geometry: str = "1080x600", block=True, setGrab=True, deleteOnClose=1, beginTask=True):
        Toplevel.__init__(self, master)
        self.config(bg=master.backgrounds[master.appConfig['prefs']['theme']])
        self.master = master
        self.block=block
        self.setGrab = setGrab
        self.delClose=deleteOnClose
        self.title(title)
        self.mode=mode
        self.clsCount=0
        self.geometry(geometry)
        self.textFrm = ttk.Frame(self)
        self.yScroll = ttk.Scrollbar(self.textFrm)
        self.outText = Text(self.textFrm, font=self.master.curr_font, yscrollcommand=self.yScroll.set, relief=FLAT, state=DISABLED)
        self.yScroll.config(command=self.outText.yview)
        if self.master.appConfig['prefs']['print_log']:
            self.outRedir = StdoutRedirect(self.outText, interactive=False)
            self.errRedir = StderrRedirect(self.outText, interactive=False, master=self)
        if self.mode == "yt":
            # self.btnStart = ttk.Button(self, text="Start Download", command=self.task)
            self.yt_frm = ttk.Frame(self)
            self.progress = ttk.Progressbar(self.yt_frm, length=600, mode='determinate', maximum=1, value=0)
            self.progress.grid(column=0, row=0, padx=3, sticky=W)
            self.stat=StringVar(self.yt_frm, value="0MiB/0MiB @ 0MiB/s")
            ttk.Label(self.yt_frm, textvariable=self.stat, font=font.Font(size=14)).grid(column=1, row=0, padx=3)
            self.info = StringVar(self.yt_frm, value="0 / 0 Completed")
            ttk.Label(self.yt_frm, textvariable=self.info, font = font.Font(size=14)).grid(column=0, row=1, sticky=W)
            self.percent=StringVar(self.yt_frm, value=f"{self.progress['value']*100}%")
            ttk.Label(self.yt_frm, font=font.Font(size=10), textvariable=self.percent).grid(column=0, row=0)
            self.yt_frm.pack(side=TOP, pady=7.5)
        elif self.mode == "time":
            # self.btnStart = ttk.Button(self, text="Start Duration Scan", command=self.task)
            pass
        else:
            print(f"mode '{self.mode}' incorrect")

        if beginTask: self.task()
        # self.btnStart.pack(side=BOTTOM)
        self.textFrm.pack(side=TOP, expand=True, fill=BOTH)
        self.yScroll.pack(fill=Y, side=RIGHT)
        self.outText.pack(expand=True, fill=BOTH)
        self.iconbitmap(self.master.relative_path("Resources\\YTDLv2_256.ico"))
        self.protocol("WM_DELETE_WINDOW", self.outWin_close)
        self.focus_set()
        if self.setGrab: self.grab_set()
    def outWin_close(self, event=None):
        self.master = self.master
        if self.master.running and self.block:
            messagebox.showerror("Cannot close", "Unable to close window while download is in progress.", parent=self)
            return
        elif self.master.running and self.delClose == 1:
            # messagebox.showwarning("Download not stopped...", "Download logs continue in the console.", parent=self)
            pass
        self.grab_release()
        if self.delClose == 1: # Do delete
            self.destroy()
            self.outRedir.close()
            self.errRedir.close()
            if self.mode == "yt" and hasattr(self.master, "yt_download_win"):
                self.master.yt_download_win.destroy()
                del self.master.yt_download_win
                self.master.log_debug("Deleted yt win")
            elif self.mode == "time" and hasattr(self.master, "time_window"):
                self.master.time_window.destroy()
                del self.master.time_window
                self.master.log_debug("Deleted time win")
        elif self.delClose == 0: # Don't delete
            self.withdraw()
            self.master.log_debug("Withdrawn")
        self.master.focus_set()
    def task(self):
        if self.mode == "yt" and self.master.appConfig['prefs']['rerun']:
            self.t = threading.Thread(target=self.master.yt_download, args=[2])
        elif self.mode == "yt":
            self.t = threading.Thread(target=self.master.yt_download)
        elif self.mode == "time":
            self.t = threading.Thread(target=self.master.start_time)
        else:
            print(f"mode '{self.mode}' incorrect")
            return
        self.t.start()


import tkinter as tk
import re

from erreur import *
from graphique import *

class RésultatValidateur:
    def __init__(self, défaut = None):
        self.erreurs = []
        self.résultat = défaut

class Validateur:
    def _réel(x):
        if not isinstance(x, float) and not isinstance(x, int):
            x = x.get() if isinstance(x, tk.StringVar) else str(x)
            x = x.strip()

            if re.fullmatch(r'-?[0-9]+(?:\.[0-9]+)?', x):
                try:
                    x = float(x)
                except Exception:
                    x = None
            else:
                x = None

        return x

    def _entier(x):
        if isinstance(x, float):
            x = int(x)
        elif not isinstance(x, int):
            x = variable.get() if isinstance(x, tk.StringVar) else str(x)
            x = x.strip()

            if re.fullmatch(r'-?[0-9]+', x):
                try:
                    x = int(x)
                except Exception:
                    x = None
            else:
                x = None

        return x

    def _couleur(c):
        if not (isinstance(c, tuple) or isinstance(c, list)) or len(c) != 3:
            c = None
        else:
            c = tuple(map(lambda ci: int(ci) if isinstance(ci, float) else ci, c))

            if not all(isinstance(ci, int) and 0 <= ci <= 255 for ci in c):
                c = None

        return c

    def dimensions(largeur, hauteur):
        r = RésultatValidateur()

        largeur = Validateur._réel(largeur)
        if largeur is None:
            r.erreurs.append(Erreur(Erreur.DIMENSIONS_LARGEUR_FORMAT))
        elif largeur <= 0:
            r.erreurs.append(Erreur(Erreur.DIMENSIONS_LARGEUR_NONPOSITIF))

        hauteur = Validateur._réel(hauteur)
        if hauteur is None:
            r.erreurs.append(Erreur(Erreur.DIMENSIONS_HAUTEUR_FORMAT))
        elif hauteur <= 0:
            r.erreurs.append(Erreur(Erreur.DIMENSIONS_HAUTEUR_NONPOSITIF))

        if not r.erreurs:
            r.résultat = (largeur, hauteur)

        return r

    def axe_bornes(min, max):
        r = RésultatValidateur()

        min = Validateur._réel(min)
        if min is None:
            r.erreurs.append(Erreur(Erreur.AXE_BORNES_MIN_FORMAT))

        max = Validateur._réel(max)
        if max is None:
            r.erreurs.append(Erreur(Erreur.AXE_BORNES_MAX_FORMAT))

        if not r.erreurs:
            if min == max:
                r.erreurs.append(Erreur(Erreur.AXE_BORNES_VIDE))
            else:
                r.résultat = (min, max)

        return r

    def axe_étiquette(étiquette):
        return RésultatValidateur(str(étiquette))

    def axe_droite(droite):
        r = RésultatValidateur()

        if droite not in [AXE_FLÈCHE, AXE_LIGNE, AXE_CACHÉ]:
            r.erreurs.append(Erreur(Erreur.AXE_DROITE_TYPE))
        else:
            r.résultat = droite

        return r

    def axe_pas(pas):
        r = RésultatValidateur()

        pas = Validateur._réel(pas)
        if pas is None:
            r.erreurs.append(Erreur(Erreur.AXE_PAS_FORMAT))
        elif pas <= 0:
            r.erreurs.append(Erreur(Erreur.AXE_PAS_NONPOSITIF))
        else:
            r.résultat = pas

        return r

    def axe_interpas(interpas):
        r = RésultatValidateur(0)

        if not isinstance(interpas, int):
            interpas = str(interpas)
            if interpas.strip() != '':
                interpas = Validateur._entier(interpas)
                if interpas is None:
                    r.erreurs.append(Erreur(Erreur.AXE_INTERPAS_FORMAT))

        if not r.erreurs:
            if interpas < 0:
                r.erreurs.append(Erreur(Erreur.AXE_INTERPAS_NÉGATIF))
            else:
                r.résultat = interpas

        return r

    def grillage_ouvert(grillage_ouvert):
        return RésultatValidateur(bool(grillage_ouvert))

    def axe_grillage_majeur(grillage_majeur):
        return RésultatValidateur(bool(grillage_majeur))

    def axe_grillage_mineur(grillage_mineur):
        return RésultatValidateur(bool(grillage_mineur))

    def couleur(couleur):
        r = RésultatValidateur()

        couleur = Validateur._couleur(couleur)
        if couleur is None:
            r.erreurs.append(Erreur(Erreur.COULEUR_FORMAT))
        else:
            r.résultat = couleur

        return r

    def axe_couleur(couleur):
        r = RésultatValidateur()

        couleur = Validateur._couleur(couleur)
        if couleur is None:
            r.erreurs.append(Erreur(Erreur.AXE_COULEUR_FORMAT))
        else:
            r.résultat = couleur

        return r

    def axe_grillage_majeur_couleur(couleur):
        r = RésultatValidateur()

        couleur = Validateur._couleur(couleur)
        if couleur is None:
            r.erreurs.append(Erreur(Erreur.AXE_GMAJEUR_COULEUR_FORMAT))
        else:
            r.résultat = couleur

        return r

    def axe_grillage_mineur_couleur(couleur):
        r = RésultatValidateur()

        couleur = Validateur._couleur(couleur)
        if couleur is None:
            r.erreurs.append(Erreur(Erreur.AXE_GMINEUR_COULEUR_FORMAT))
        else:
            r.résultat = couleur

        return r

    def angles(angles):
        r = RésultatValidateur()

        if angles not in [ANGLE_DEGRÉS, ANGLE_RADIANS]:
            r.erreurs.append(Erreur(Erreur.ANGLES_TYPE))
        else:
            r.résultat = angles

        return r

    def objet_type(type):
        r = RésultatValidateur()

        if type not in [RELATION_F_X, RELATION_F_Y, RELATION_XY_T]:
            r.erreurs.append(Erreur(Erreur.OBJET_TYPE))
        else:
            r.résultat = type

        return r

    def objet_équation(type, *équation):
        return RésultatValidateur(str(équation[0]) if type != RELATION_XY_T else tuple(map(str, équation)))

    def objet_bornes(type, min, max):
        r = RésultatValidateur()

        if type != RELATION_XY_T and isinstance(min, str) and min.strip() == '':
            min = float('-inf')
        else:
            min = Validateur._réel(min)
            if min is None:
                r.erreurs.append(Erreur(Erreur.OBJET_BORNES_MIN_FORMAT))

        if type != RELATION_XY_T and isinstance(max, str) and max.strip() == '':
            max = float('inf')
        else:
            max = Validateur._réel(max)
            if max is None:
                r.erreurs.append(Erreur(Erreur.OBJET_BORNES_MAX_FORMAT))

        if not r.erreurs:
            if min >= max:
                r.erreurs.append(Erreur(Erreur.OBJET_BORNES_VIDE))
            else:
                r.résultat = (min, max)

        return r

    def objet_points_ouverts(points):
        r = RésultatValidateur()

        if isinstance(points, str):
            points = points.split(';')

        if not isinstance(points, list):
            r.erreurs.append(Erreur(Erreur.OBJET_POUVERTS_FORMAT))
        else:
            points = list(map(lambda xi: str(xi).strip(), points))

            for i, p in enumerate(points):
                if not p:
                    continue

                p = Validateur._réel(p)
                if p is None:
                    r.erreurs.append(Erreur(Erreur.OBJET_POUVERTS_ITEM_FORMAT, item = i + 1))
                points[i] = p

            if r.erreurs:
                r.erreurs.insert(0, Erreur(Erreur.OBJET_POUVERTS_FORMAT))
            else:
                r.résultat = list(filter(None, points))

        return r

    def objet_points_fermés(points):
        r = RésultatValidateur()

        if isinstance(points, str):
            points = points.split(';')

        if not isinstance(points, list):
            r.erreurs.append(Erreur(Erreur.OBJET_PFERMÉS_FORMAT))
        else:
            points = list(map(lambda xi: str(xi).strip(), points))

            for i, p in enumerate(points):
                if not p:
                    continue

                p = Validateur._réel(p)
                if p is None:
                    r.erreurs.append(Erreur(Erreur.OBJET_PFERMÉS_ITEM_FORMAT, item = i + 1))
                points[i] = p

            if r.erreurs:
                r.erreurs.insert(0, Erreur(Erreur.OBJET_PFERMÉS_FORMAT))
            else:
                r.résultat = list(filter(None, points))

        return r

    def objet_style(style):
        r = RésultatValidateur()

        if style not in [
            'solid',
            'dotted',
            'densely dotted',
            'loosely dotted',
            'dashed',
            'densely dashed',
            'loosely dashed',
            'dashdotted',
            'densely dashdotted',
            'loosely dashdotted',
            'dashdotdotted',
            'densely dashdotdotted',
            'loosely dashdotdotted'
        ]:
            r.erreurs.append(Erreur(Erreur.OBJET_STYLE_TYPE))
        else:
            r.résultat = style

        return r

    def objet_couleur(couleur):
        r = RésultatValidateur()

        couleur = Validateur._couleur(couleur)
        if couleur is None:
            r.erreurs.append(Erreur(Erreur.OBJET_COULEUR_FORMAT))
        else:
            r.résultat = couleur

        return r

    def objet_étiquette(étiquette):
        return RésultatValidateur(str(étiquette))

    def objet_position(position):
        r = RésultatValidateur()

        position = Validateur._réel(position)
        if position is None:
            r.erreurs.append(Erreur(Erreur.OBJET_ÉTIQUETTE_POS_FORMAT))
        elif position < 0 or position > 1:
            r.erreurs.append(Erreur(Erreur.OBJET_ÉTIQUETTE_POS_ÉTENDU))
        else:
            r.résultat = position

        return r

    def objet_ancre(ancre):
        r = RésultatValidateur()

        if ancre is not None and not (isinstance(ancre, str) and ancre.strip() == ''):
            ancre = Validateur._réel(ancre)
            if ancre is None:
                r.erreurs.append(Erreur(Erreur.OBJET_ANCRE_FORMAT))
            elif ancre < -360 or ancre > 360:
                r.erreurs.append(Erreur(Erreur.OBJET_ANCRE_ÉTENDU))
            else:
                r.résultat = ancre

        return r


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 22:03:02 2020

@author: lucys
"""

low = 0
high = 100
ans = (low + high)/2
print ("Please think of a number between 0 and 100!")
print("Is your secret number "+str(int(ans))+"?")
x = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. Enter: ")

while x != "c":
    if x == "h":
        high = ans
    elif x == "l":
        low = ans
    elif x != "c":
        print("Sorry I did not understand your input")
    ans = (low + high)/2
    print("Is your secret number "+str(int(ans))+"?")
    x = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. Enter: ")
print("Game Over. Your secret number was: "+str(int(ans)))


import cupy as cp
import numpy as np
import string

from .fusion_manager import FusionBase

def alpha_kernel(
    resolution, width, height,
):
    # input the list of layers, amount of channels can slo be input through kernel
    alpha_kernel = cp.ElementwiseKernel(
        in_params="raw U p, raw W pcl_chan, raw W map_lay, raw W pcl_channels",
        out_params="raw U newmap",
        preamble=string.Template(
            """
                __device__ int get_map_idx(int idx, int layer_n) {
                    const int layer = ${width} * ${height};
                    return layer * layer_n + idx;
                }
            """
        ).substitute(resolution=resolution, width=width, height=height),
        operation=string.Template(
            """
            U id = floorf(i/pcl_channels[1]);
            int layer = i % pcl_channels[1];
            U idx = p[id * pcl_channels[0]];
            U valid = p[id * pcl_channels[0] + 1];
            U inside = p[id * pcl_channels[0] + 2];
            if (valid) {
                if (inside) {
                    U theta_max = 0;
                    W arg_max = 0;
                    U theta = p[id * pcl_channels[0] + pcl_chan[layer]];
                        if (theta >=theta_max){
                            arg_max = map_lay[layer];
                            theta_max = theta;
                        }
                    atomicAdd(&newmap[get_map_idx(idx, arg_max)], theta_max);
                }
            }
            """
        ).substitute(),
        name="alpha_kernel",
    )
    return alpha_kernel

class ClassBayesian(FusionBase):
    def __init__(self, params, *args, **kwargs):
        # super().__init__(fusion_params, *args, **kwargs)
        # print("Initialize fusion kernel")
        self.name = "pointcloud_class_bayesian"
        self.cell_n = params.cell_n
        self.resolution = params.resolution
        self.alpha_kernel = alpha_kernel(self.resolution, self.cell_n, self.cell_n,)

    def __call__(self, points_all, R, t, pcl_ids, layer_ids, elevation_map, semantic_map, new_map, *args):
        self.alpha_kernel(
            points_all,
            pcl_ids,
            layer_ids,
            cp.array([points_all.shape[1], pcl_ids.shape[0]], dtype=cp.int32),
            new_map,
            size=(points_all.shape[0]),
        )
        # calculate new thetas
        sum_alpha = cp.sum(new_map[layer_ids], axis=0)
        # do not divide by zero
        sum_alpha[sum_alpha == 0] = 1
        semantic_map[layer_ids] = new_map[layer_ids] / cp.expand_dims(sum_alpha, axis=0)


from pygame_functions import *
import pickle

class SpritePosition:

    def __init__(self, name, prefix=""):
        # Name must be the filename of a sprite
        self.name = name
        # Prefix should be both of img/sprites' subdirectory and prefix of a *Positions file
        if prefix != "":
            newPrefix = prefix + "/"
        self.sprite = makeSprite("img/sprites/" + newPrefix + name + ".png")
        # All the close positions
        self.jumpMove = None
        self.upMove = None
        self.downMove = None
        self.leftMove = None
        self.rightMove = None
        self.nextMove = None
        # Name of the sprite that can eat self
        self.eaterName = None

        dictPositions = self.getAllPositions(prefix)
        self.x = 0
        self.y = 0
        if dictPositions!={}:
            self.x = dictPositions.get(name)[0]
            self.y = dictPositions.get(name)[1]

    def setPositions(self, jump=None, up=None, down=None, left=None, right=None, nextMove=None):
        self.jumpMove = jump
        self.upMove = up
        self.downMove = down
        self.leftMove = left
        self.rightMove = right
        self.nextMove = nextMove

    @staticmethod
    def getAllPositions(fileName):
        newFileName = "positions/" + fileName + "Positions"
        if os.path.isfile(newFileName):
            with open(newFileName, "rb") as positionFile:
                return pickle.Unpickler(positionFile).load()
        return {}


'''
Write a program that reads in a word entered by the user and checks whether:
- the word has at least 8 characters
- starts with a vowel
- has alternating vowels and consonants, and
- the consonants are in increasing alphabetical order

Program should work for upper case or lower case and take use of a
single function (including a loop)
'''

def is_alternating(word): # Create initial function to check alternating condition
    x = 'aeiou'
    i = 0
    alternate = 1 # If alternate is 1, phrase is alternating, otherwise 0

    if len(word) >= 8 and word[0] in x: # Initial check conditions
        while i < (len(word)-1) and (alternate == 1):
            '''
            Check if i is vowel
            Next should be alternate
            otherwise alternate is set to 0
            '''
            if word[i] in x:
                if word[i+1] not in x:
                    alternate = 1
                else:
                    alternate = 0
                    '''
                    Check if i + 1 is a vowel
                    If it is, next consanent should be greater than first
                    If true, alternate set to 1
                    '''
            else:
                if word[i+1] in x:
                    if i+2 < len(word):
                        if word[i] < word[i+2]:
                            alternate = 1
                        else:
                            alternate = 0
                    else:
                        alternate = 1
                else:
                    alternate = 0
            i += 1
    else:
        alternate = 0

    return alternate

altWord = input('Enter a word => ') # Prompt user for input
print(altWord)
altWord2 = altWord.lower()
if is_alternating(altWord2) == 0:
    print("The word" , "'" + altWord + "'", "is not alternating")
else:
    print("The word" , "'" + altWord + "'", "is alternating")


#! /usr/bin/env python3
import socket
import os
import time
import sys
import signal
import time

def sig_handler(signum,frame):
	print("Stopping application")
	exit(0)

signal.signal(signal.SIGINT,sig_handler)

soc = socket.socket()
soc.bind(('',1632))
#help(soc.listen)
soc.listen(1)
while(True):
	c,addr = soc.accept()
	print("Person Connected: ",c,addr)
	# Receiving file from client
	fileName = c.recv(1024).decode('utf-8')
	fileName = "1"+fileName.split('/')[-1]
	print(fileName)
	with open(fileName,'w+') as fd:
		while True:
			print("INSIDE TRUE")
			bi = c.recv(1024)
			print("lol b",bi)
			if bi== b'<<EOF>>':
				break
			fd.write(bi.decode('utf-8'))

	with open(fileName,'r') as fd:
		for line in fd:
			c.sendall(bytes(line,'utf-8'))
	c.sendall(b"\n")
	time.sleep(0.5)
	c.sendall(bytes(time.ctime(os.path.getmtime(fileName))+"\n",'utf-8'))
	c.close()


from correction.helpers.ordered_easydict import OrderedEasyDict as edict
import os
import torch

__C = edict()
cfg = __C
__C.GLOBAL = edict()
__C.GLOBAL.DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")

__C.GLOBAL.BATCH_SIZE = None

__C.GLOBAL.BASE_DIR = '/home'  # Base project folder

__C.GLOBAL.MODEL_SAVE_DIR = os.path.join(__C.GLOBAL.BASE_DIR, 'logs')
assert __C.GLOBAL.MODEL_SAVE_DIR is not None

__C.ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# __C.GLOBAL.USE_SPATIOTEMPORAL_ENCODING = False


import logging
from collections import deque
from copy import deepcopy
from datetime import datetime
from itertools import count

import numpy as np
import torch as t
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm

from calculate_loss import calculate_loss
from device import Device
from optimise_model import optimise_model
from utils import prepare_batch, as_tensor, transition_to_tensor

def optimiser(idx, shared_model, SIMULATOR, args, lock):
    try:
        writer = SummaryWriter('runs/{}/optimiser:{:02}'.format(datetime.now().strftime("%d|%m_%H|%M"), idx))
        logging.basicConfig(filename='logs/optimiser:{:02}.log'.format(idx),
                            filemode='w',
                            format='%(message)s',
                            level=logging.DEBUG)

        sgd = t.optim.SGD(params=shared_model.parameters(), lr=args.lr)

        # allocate a device
        n_gpu = t.cuda.device_count()
        if n_gpu > 0:
            Device.set_device(idx % n_gpu)

        q_network = deepcopy(shared_model)
        q_network.to(Device.get_device())
        q_network.train()

        target_network = deepcopy(q_network)
        target_network.to(Device.get_device())
        target_network.eval()

        buffer = deque(maxlen=args.buffer_size)

        simulator = SIMULATOR()
        for itr in tqdm(count(), position=idx, desc='optimiser:{:02}'.format(idx)):

            state = simulator.reset()
            episode_reward = 0
            for e in count():
                if np.random.RandomState().rand() < max(args.eps ** itr, args.min_eps):
                    action = np.random.RandomState().randint(simulator.n_actions())
                else:
                    action = q_network(as_tensor(state)).argmax().item()

                next_state, reward, terminal = simulator.step(action)

                buffer.append(transition_to_tensor(state, action, reward, next_state, terminal))

                episode_reward += reward
                state = next_state

                # Sample a data point from dataset
                batch = prepare_batch(buffer, args.batch_size)

                # Sync local model with shared model
                q_network.load_state_dict(shared_model.state_dict())

                # Calculate loss for the batch
                loss = calculate_loss(q_network, target_network, batch, args)

                # Optimise for the batch
                loss = optimise_model(shared_model, q_network, loss, sgd, args, lock)

                # Log the results
                logging.debug('Batch loss: {:.2f}'.format(loss))
                writer.add_scalar('batch/loss', loss, e)

                if terminal:
                    break

            logging.debug('Episode reward: {:.2f}'.format(episode_reward))
            writer.add_scalar('episode_reward', episode_reward, itr)
            writer.close()

            if itr % args.target_update_frequency == 0:
                target_network.load_state_dict(q_network.state_dict())

    except KeyboardInterrupt:
        print('exiting optimiser:{:02}'.format(idx))


from collections import defaultdict

from interop import py_interop_run_metrics, py_interop_run, py_interop_summary

class InteropService(object):

    def __init__(self, runfolder):
        run_metrics = py_interop_run_metrics.run_metrics()
        run_metrics.run_info()

        valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, 0)
        py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load)
        run_metrics.read(runfolder, valid_to_load)

        summary = py_interop_summary.run_summary()
        py_interop_summary.summarize_run_metrics(run_metrics, summary)

        self.summary = summary

    def get_non_index_reads(self):
        # First pick-out the reads which are not index reads
        non_index_reads = []
        for read_nbr in range(self.summary.size()):
            if not self.summary.at(read_nbr).read().is_index():
                non_index_reads.append(read_nbr)
        return non_index_reads

    def get_error_rates(self):
        lanes = self.summary.lane_count()

        non_index_reads = self.get_non_index_reads()

        error_rates = defaultdict(dict)
        # "Renumber" the reads to have their intuitive read numbers, i.e. Read 1 -> 1, Read 2 -> 2
        for new_nbr, old_read in enumerate(non_index_reads):
            for lane in range(lanes):
                read = self.summary.at(old_read).at(lane)
                error_rate = read.error_rate().mean()
                error_rates[lane+1][new_nbr+1] = error_rate
        return error_rates

    def get_densities(self):
        lanes = self.summary.lane_count()

        non_index_reads = self.get_non_index_reads()

        densities = defaultdict(dict)
        # "Renumber" the reads to have their intuitive read numbers, i.e. Read 1 -> 1, Read 2 -> 2
        for new_nbr, original_read_nbr in enumerate(non_index_reads):
            for lane in range(lanes):
                read = self.summary.at(original_read_nbr).at(lane)
                cluster_density = read.density().mean()
                pass_filter_density = read.density_pf().mean()
                densities[lane+1][new_nbr+1] = \
                    {"raw_density": cluster_density, "pass_filter_density": pass_filter_density}
        return densities

    def get_q30(self):
        lanes = self.summary.lane_count()

        non_index_reads = self.get_non_index_reads()

        q30s = defaultdict(dict)
        # "Renumber" the reads to have their intuitive read numbers, i.e. Read 1 -> 1, Read 2 -> 2
        for new_nbr, original_read_nbr in enumerate(non_index_reads):
            for lane in range(lanes):
                q30 = self.summary.at(original_read_nbr).at(lane).percent_gt_q30()
                q30s[lane+1][new_nbr+1] = q30
        return q30s


# Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.

# Note: input will never be an empty string

import string

def fake_bin(x):
    s = list(x)
    tab = []
    new_string = ""
    for i in s:
        if int(i) < 5:
            tab.append(0)
        elif int(i) > 4:
            tab.append(1)
    for x in tab:
        new_string += str(x)
    return new_string

def fake_bin(s):
    return s.translate(string.maketrans('0123456789', '0000011111'))


from django.views import generic
from django.urls import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib import messages
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

from admin_panel import models, forms, custom_views

@method_decorator(login_required(login_url='/admin/site/login'), name='dispatch')
class HouseListView(custom_views.ListFilteringView):
    model = models.House
    search_form = forms.HouseFilter
    template_name = 'admin_panel/houses/index.html'

@login_required(login_url='/admin/site/login')
def house_create_view(request):
    house_form = forms.HouseForm()
    house_preview_formset = forms.HousePreviewFormset()
    house_section_formset = forms.HouseSectionFormset()
    house_floor_formset = forms.HouseFloorFormset()
    house_user_admin_formset = forms.HouseUserAdminFormset()
    if request.POST:
        house_form = forms.HouseForm(
            request.POST or None,
        )
        house_preview_formset = forms.HousePreviewFormset(
            request.POST or None,
            request.FILES,
            instance=house_form.instance,
        )
        house_section_formset = forms.HouseSectionFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        house_floor_formset = forms.HouseFloorFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        house_user_admin_formset = forms.HouseUserAdminFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        if house_form.is_valid() and\
                house_preview_formset.is_valid() and\
                house_section_formset.is_valid() and\
                house_floor_formset.is_valid() and\
                house_user_admin_formset.is_valid():
            house_form.save()
            house_preview_formset.save()
            house_section_formset.save()
            house_floor_formset.save()
            house_user_admin_formset.save()
            messages.success(request, 'Все обновлено!')
            return redirect('admin_panel:houses_list')
        else:
            messages.error(request, 'Ошибка сохранения!')
    return render(
        request,
        'admin_panel/houses/create.html',
        {
            'house_form': house_form,
            'house_preview_formset': house_preview_formset,
            'house_section_formset': house_section_formset,
            'house_floor_formset': house_floor_formset,
            'house_user_admin_formset': house_user_admin_formset,
        }
    )

@login_required(login_url='/admin/site/login')
def house_update_view(request, pk):
    house = models.House.get_house_by_pk(pk=pk)
    house_form = forms.HouseForm(
        instance=house,
    )
    house_preview_formset = forms.HousePreviewFormset(
        instance=house,
    )
    house_section_formset = forms.HouseSectionFormset(
        instance=house,
    )
    house_floor_formset = forms.HouseFloorFormset(
        instance=house,
    )
    house_user_admin_formset = forms.HouseUserAdminFormset(
        instance=house,
    )
    if request.POST:
        house_form = forms.HouseForm(
            request.POST or None,
            instance=models.House.get_house_by_pk(pk=pk),
        )
        house_preview_formset = forms.HousePreviewFormset(
            request.POST or None,
            request.FILES,
            instance=house_form.instance,
        )
        house_section_formset = forms.HouseSectionFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        house_floor_formset = forms.HouseFloorFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        house_user_admin_formset = forms.HouseUserAdminFormset(
            request.POST or None,
            instance=house_form.instance,
        )
        if house_form.is_valid() and\
                house_preview_formset.is_valid() and\
                house_section_formset.is_valid() and\
                house_floor_formset.is_valid() and \
                house_user_admin_formset.is_valid():
            house_form.save()
            house_preview_formset.save()
            house_section_formset.save()
            house_floor_formset.save()
            house_user_admin_formset.save()
            messages.success(request, 'Все данные дома обновлены!')
            return redirect('admin_panel:houses_list')
        else:
            messages.error(request, 'Ошибка сохранения!')
            return redirect('admin_panel:house_update', pk=pk)
    return render(
        request,
        'admin_panel/houses/update.html',
        {
            'house_form': house_form,
            'house_preview_formset': house_preview_formset,
            'house_section_formset': house_section_formset,
            'house_floor_formset': house_floor_formset,
            'house_user_admin_formset': house_user_admin_formset,
        }
    )

@login_required(login_url='/admin/site/login')
def house_detail_view(request, pk):
    return render(
        request,
        'admin_panel/houses/detail.html',
        {
            'house_data': models.House.objects.get(pk=pk),
            'house_preview': models.HousePreview.get_queryset_all_images(pk),
            'house_section': models.HouseSection.get_sections_count(pk),
            'house_floor': models.HouseFloor.get_floor_count(pk),
            'house_user_admin_list': models.HouseUserAdmin.get_user_admin_list(pk),
        }
    )

@method_decorator(login_required(login_url='/admin/site/login'), name='dispatch')
class HouseDeleteView(generic.DeleteView):
    model = models.House
    success_url = reverse_lazy('admin_panel:houses_list')
    template_name = 'admin_panel/houses/delete.html'


#!/usr/local/Python/3.6.3/bin/python3

def postVepParserFirst(inputFile,outputFile,workingDir):

	import subprocess
	import argparse
	import os, sys, re

	tempOutputFile = workingDir+'/tempFirstParser.tsv'
	if inputFile.endswith('.gz') == 1:
		cmdLine = "gunzip {}".format(inputFile)
		cmdLine_run = subprocess.run(cmdLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		if cmdLine_run.returncode != 0:
			print("FAILED! Unable to gunzip {}".format(inputFile))
			exit(1)
		else:
			inputFile = inputFile[:-3]

	with open(inputFile,'r') as vepVars1, open(outputFile,'w') as vepOut:
		pos0sep = '0'
		for line1 in vepVars1:
			line1 = line1.rstrip()
			if line1[0] != "#":
				line1Sep = line1.split()
				if pos0sep == line1Sep[0]:
					continue
				else:
					cmdLine = "grep '"+'{}'.format(line1Sep[0])+"' "+inputFile+" > "+tempOutputFile
					cmdLine_run = subprocess.run(cmdLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
					if cmdLine_run.returncode != 0:
						print("FAILED! Unable to use grep command in postVepFirstCmd.py")
						exit(1)
				pos0sep = line1Sep[0]

				with open(tempOutputFile,'r') as select:
					sEnst = 0
					for lines in select:
						lines = lines.rstrip()
						linesSep = lines.split()
						Enst = linesSep[4]
						found1 = re.search(r"ENST0+",Enst)
						cEnst = int(Enst[len(found1.group(0)):])
						if cEnst > sEnst:
							sEnst = cEnst
							out = linesSep
					impactSplit = out[6].split(',')
					for s in impactSplit:
						if (s == 'stop_gained') or (s == 'missense_variant'):
							vepOut.write(lines+'\n')
							break

	cmdLine = "gzip {}".format(inputFile)
	cmdLine_run = subprocess.run(cmdLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	if cmdLine_run.returncode != 0:
		print("FAILED! Unable to gzip {}".format(inputFile))
		exit(1)

	cmdLine = "gzip {}".format(outputFile)
	cmdLine_run = subprocess.run(cmdLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	if cmdLine_run.returncode != 0:
		print("FAILED! Unable to gzip {}".format(outputFile))
		exit(1)

	cmdLine = "rm {}".format(tempOutputFile)
	cmdLine_run = subprocess.run(cmdLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	if cmdLine_run.returncode != 0:
		print("FAILED! Unable to remove {}".format(tempOutFile))
		exit(1)


import numpy as np
import matplotlib.pyplot as plt
import simulation
import harvested_energy_estimation

'''
This script calculates the optimal temperature gradient required for different device power consumption scenarios. It uses the teg_output and ltc3108_output functions from the simulation module, as well as the energy_harvested function from the harvested_energy_estimation module.

The script generates a plot showing the relationship between the optimal temperature gradient and device power consumption.

To generate the plot, execute the following command from the software/optimal_gradient folder:
python optimal_gradient.py

A window with the plot should appear, showing the optimal temperature gradient required for different device power consumption scenarios. This information can be useful for determining the minimum temperature gradient needed for the ThermoBeat system to operate efficiently under various conditions.
'''

def find_optimal_gradient(device_power_consumption_mW):
    temperature_gradients = np.linspace(0.5, 10, 100)
    required_gradients = []

    for temperature_gradient in temperature_gradients:
        output_voltage, output_current = simulation.teg_output(temperature_gradient, 50.4, 3.11)
        output_voltage, output_current = simulation.ltc3108_output(output_voltage, output_current)

        harvested_energy_mW = output_voltage * output_current
        if harvested_energy_mW >= device_power_consumption_mW:
            required_gradients.append(temperature_gradient)
            break
    return required_gradients

def plot_optimal_gradient(device_power_consumptions_mW):
    optimal_gradients = []

    for device_power_consumption_mW in device_power_consumptions_mW:
        optimal_gradient = find_optimal_gradient(device_power_consumption_mW)
        optimal_gradients.append(optimal_gradient)

    plt.plot(device_power_consumptions_mW, optimal_gradients)
    plt.xlabel("Device Power Consumption (mW)")
    plt.ylabel("Optimal Temperature Gradient (°C)")
    plt.title("Optimal Temperature Gradient for Different Device Power Consumption Scenarios")
    plt.grid()
    plt.show()

if __name__ == "__main__":
    device_power_consumptions_mW = np.linspace(50, 500, 10)

    plot_optimal_gradient(device_power_consumptions_mW)