import pygame
from graphics import Graphics
from graphics import Video
from . import _ASSETS_PATH
import os
from enum import Enum

class Menu(object):
    """
    Menu is a class with methods that can draw different menu items or screens
    to the display.
    """

    #: The different states that the menu can take
    State = Enum('State', 'Splash Menu Building Playing Testing Exit')

    #: Becomes true when the first screen (title screen) has been clicked on.
    #: A higher order class can watch this and proceed to the actual menu.
    splashScreenPressed = False

    #: Becomes true when the "start demo" button has been pressed. A higher order
    #: class can watch this and take appropriate action on change
    demoPressed = False

    #: Becomes true when the Rocket builder button has been pressed. A higher
    #: order class can watch htis and take appropriate action on change.
    builderPressed = False

    #: Becomes true when the quit button has been pressed. A higher order class can
    #: watch this and take appropriate action on change
    quitPressed = False

    #: Becomes true when the tests button has been pressed. A higher order class can
    #: watch this and take appropriate action on change
    testsPressed = False

    #: The color to use for the menu buttons
    _menuButtonColor = ((255, 255, 255, 64), (255, 255, 255, 128))
    #: Icons made by `Freepik <www.freepic.com>`_ from `Flaticon <https://www.flaticon.com/>`_. Licensed by `CC 3.0 BY <http://creativecommons.org/licenses/by/3.0/>`_
    _fullscreen_icon = pygame.image.load(os.path.abspath(os.path.join(_ASSETS_PATH, "image", "open_fullscreen.png")))
    #: Icons made by `Freepik <www.freepic.com>`_ from `Flaticon <https://www.flaticon.com/>`_. Licensed by `CC 3.0 BY <http://creativecommons.org/licenses/by/3.0/>`_
    _windowed_icon = pygame.image.load(os.path.abspath(os.path.join(_ASSETS_PATH, "image", "close_fullscreen.png")))

    @classmethod
    def drawBackground(cls, color_rgb, opacity):
        """
        Draws the background using the given color and opacity alpha value.

        :param color_rgb: The color of the background
        :type color_rgb: :py:class:`pygame.Color`
        :param int opacity: The alpha value with which to draw the background
        """
        dispSurface = pygame.display.get_surface()
        surfaceSize = dispSurface.get_size()
        background = pygame.surface.Surface(surfaceSize)
        background.fill(color_rgb)
        background.set_alpha(opacity)
        dispSurface.blit(background, (0,0))

    @classmethod
    def drawSplashScreen(cls, opacity):
        """
        Draws the title screen to pygame's current display surface.

        :param int opacity: The alpha value with which to draw the splash screen background
        """
        surface = pygame.display.get_surface()
        surfaceSize = surface.get_size()
        surfaceCenter = (surfaceSize[0] / 2, surfaceSize[1] / 2)
        titleCenter = (surfaceCenter[0], surfaceCenter[1] - 20)
        subtitleCenter = (surfaceCenter[0], surfaceCenter[1] + 20)

        # fill surface with black
        cls.drawBackground((0, 0, 0), opacity)

        # draw a button
        Graphics.drawButton(surface, (0, 0), surfaceSize,
                            ((0, 0, 0, 0), (0, 0, 0, 0)),
                            0, 0, cls._splashCallback)

        # In the future, may want to draw an image onto the surface
        # as a background
        # for now, just draw text
        titleFont = pygame.font.SysFont("lucidaconsole", 40)
        subtitleFont = pygame.font.SysFont("lucidaconsole", 20)

        Graphics.drawTextCenter(titleCenter, "Flat Earth Space Program",
                                titleFont, (255, 255, 255))
        Graphics.drawTextCenter(subtitleCenter, "Click Anywhere to Continue",
                                subtitleFont, (255, 255, 255))

    @classmethod
    def drawMenu(cls, opacity, tests=False):
        """
        Draws the menu screen and buttons to pygame's current display surface.

        :param int opacity: The alpha value with which to draw the menu background
        """
        surface = pygame.display.get_surface()
        surfaceSize = surface.get_size()
        surfaceCenter = (surfaceSize[0] / 2, surfaceSize[1] / 2)

        titleCenter = (surfaceCenter[0], surfaceCenter[1] - 100)

        # fill screen with black
        cls.drawBackground((0, 0, 0), opacity)

        buttonSize = (400, 50)
        buttonPosition = lambda i: (surfaceCenter[0] - buttonSize[0]/2,
                                    surfaceCenter[1] - buttonSize[1]/2 + 65*i)
        titleFont = pygame.font.SysFont("lucidaconsole", 40)

        Graphics.drawTextCenter(titleCenter, "Flat Earth Space Program",
                                titleFont, (255,255,255))
        Graphics.drawButton(surface, buttonPosition(0), buttonSize,
                            cls._menuButtonColor, "Start Demo", 25,
                            cls._demoCallback)
        Graphics.drawButton(surface, buttonPosition(1), buttonSize,
                            cls._menuButtonColor, "Rocket Builder", 25,
                            cls._builderCallback)
        if tests:
            Graphics.drawButton(surface, buttonPosition(2), buttonSize,
                                cls._menuButtonColor, "Test Suite (Console)", 25,
                                cls._testsCallback)
            Graphics.drawButton(surface, buttonPosition(3), buttonSize,
                                cls._menuButtonColor, "Exit to Desktop", 25,
                                cls._quitCallback)
        else:
            Graphics.drawButton(surface, buttonPosition(2), buttonSize,
                                cls._menuButtonColor, "Exit to Desktop", 25,
                                cls._quitCallback)

        fullscreenSize = (32,32)
        fullscreenPos = (25,25)

        isFullscreen = Video.get_fullscreen()
        icon = cls._windowed_icon if isFullscreen else cls._fullscreen_icon
        Graphics.drawButton(surface, fullscreenPos, fullscreenSize,
                            pygame.Color("black"), "", 25,
                            Video.toggle_fullscreen)
        surface.blit(icon, fullscreenPos)

    @classmethod
    def _splashCallback(cls):
        """
        Callback function to be called when the title screen is clicked. This sets the
        splashScreenPressed bool to be true.
        """
        cls.splashScreenPressed = True

    @classmethod
    def _builderCallback(cls):
        """
        Callback function to be called when the Rocket Builder button is clicked. This sets the
        builderPressed bool to be true.
        """
        cls.builderPressed = True

    @classmethod
    def _quitCallback(cls):
        """
        Callback function to be called when the quit button is clicked. This sets the
        quitPressed bool to be true.
        """
        cls.quitPressed = True

    @classmethod
    def _demoCallback(cls):
        """
        Callback function to be called when the "start demo" button is clicked. This sets the
        demoPressed bool to be true.
        """
        cls.demoPressed = True

    @classmethod
    def _testsCallback(cls):
        """
        Callback function to be called when the "test suite" button is clicked. This sets the
        testsPressed bool to be true.
        """
        cls.testsPressed = True


# 450. 删除二叉搜索树中的节点
# 给定一个二叉搜索树的根节点 root 和一个值 key，删除二叉搜索树中的 key 对应的节点，并保证二叉搜索树的性质不变。返回二叉搜索树（有可能被更新）的根节点的引用。

# 一般来说，删除节点可分为两个步骤：

# 首先找到需要删除的节点；
# 如果找到了，删除它。

# 来源：力扣（LeetCode）
# 链接：https://leetcode.cn/problems/delete-node-in-a-bst
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

# Definition for a binary tree node.
from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        if not root:
            return None
        if key > root.val:
            root.right=self.deleteNode(root.right,key)
        elif key<root.val:
            root.left = self.deleteNode(root.left,key)
        else:
            if not root.left:
                return root.right
            if not root.right:
                return root.left
            tmp = root.right
            while tmp.left:
                tmp=tmp.left
            tmp.left=root.left
            root=root.right
        return root


from pyspark.sql import SparkSession
from pyspark.sql.functions import col, unix_timestamp

# Initialize SparkSession
spark = SparkSession.builder.appName('nyc_taxi_data_processing').getOrCreate()

# Load the dataset
df = spark.read.csv('../data/train.csv', inferSchema=True, header=True)

# Data exploration
df.show()
df.printSchema()

# Data transformation
timeFmt = "yyyy-MM-dd HH:mm:ss"
df = df.withColumn('pickup_time', unix_timestamp(col('pickup_datetime'), timeFmt))
df = df.withColumn('dropoff_time', unix_timestamp(col('dropoff_datetime'), timeFmt))

# Data analysis
df = df.withColumn('actual_duration', (col('dropoff_time') - col('pickup_time')) / 60)
result = df.select('id', 'trip_duration', 'actual_duration')

# Display the first few rows of the result
result.show()

# Save the results
result.coalesce(1).write.option('header', 'true').csv('nyc_taxi_durations.csv')


from Deque import Deque

class Array_Deque(Deque):

  def __init__(self):
    # capacity starts at 1; we will grow on demand.
    self.__capacity = 1
    self.__contents = [None] * self.__capacity
    self.__front = None
    self.__back = None
    self.__size = 0

    '''
      This function is O(1). This because it would only get called
      for an object and it would take the same number of steps each
      time do to assigment operations taking constant time.
    '''

  def __str__(self):
    if len(self) == 0:
      return "[ ]"
    contents = "["
    for element in range(len(self)):
      contents += f" {self.__contents[(self.__front+element)%self.__capacity]},"
    return f"{contents[:-1]} ]"

    '''
      This function is O(n^2). This is because, in the worst case
      scenario this function would have to iterate the the entire
      length of the deque then the function would have to iterate
      the entire sting in order to concatinate the new element.
      For these two reasons, since the string and deque have to
      be interated this function is O(n^2).
    '''

  def __len__(self):
    return self.__size

    '''
      This function is O(1). This is, because regardless of the size
      of the deque we are returning a precomputed value, therefore,
      this works in constant time, meaning this function is O(1).
    '''

  def __grow(self):
    new_Deque = [None] * (self.__capacity * 2)
    new_Deque_size = 0
    for index in range(len(self)):
      new_Deque[index] = self.pop_front()
      new_Deque_size += 1

    self.__size = new_Deque_size
    self.__front = 0
    self.__back = new_Deque_size-1
    self.__capacity *= 2
    self.__contents = new_Deque

    '''
      This function is O(n). This because, in any case the function
      would have to iterate the entire deque in order to copy it over.
      Since, the pop_front function operates in constant time it has no
      extra effects making this function O(n).
    '''

  def __push_empty(self, val):
    self.__front = 0
    self.__back = 0
    self.__contents[self.__front] = val
    self.__size += 1

    '''
      This function is O(1). This is, because the function is always
      inserting on a empty deque which is the same every time, therefore
      it takes the same number of instructions and thus the function
      is O(1).
    '''

  def push_front(self, val):
    if self.__front == None:
      self.__push_empty(val)
      return
    if len(self) == self.__capacity:
      self.__grow()
    self.__front = (self.__front - 1 + self.__capacity) % self.__capacity
    self.__contents[self.__front] = val
    self.__size += 1

    '''
      This function is O(n). This is because pushing to the front would
      be constant time since assignment and math operations are constant
      time and in the worst case the grow function would
      be called which is O(n), therefore, this function is O(n).
    '''

  def pop_front(self):
    if len(self) == 0:
      return
    val = self.__contents[self.__front]
    self.__front = (self.__front + 1) % self.__capacity
    self.__size -= 1
    return val

    '''
      This function is O(1). Since, array lookups are constant time
      and front is already computed this function would always
      take the same number of steps making it O(1).
    '''

  def peek_front(self):
    if len(self) != 0:
      return self.__contents[self.__front]

    '''
      This function is O(1). Since, array lookups are constant time
      and front is already computed this function would always
      take the same number of steps making it O(1).
    '''

  def push_back(self, val):
    if self.__back == None:
      self.__push_empty(val)
      return
    if len(self) == self.__capacity:
      self.__grow()
    self.__back = (self.__back + 1) % self.__capacity
    self.__contents[self.__back] = val
    self.__size += 1

    '''
      This function is O(n). This is because pushing to the back would
      be constant time since assignment and math operations are constant
      time and in the worst case the grow function would
      be called which is O(n), therefore, this function is O(n).
    '''

  def pop_back(self):
    if len(self) == 0:
      return
    val = self.__contents[self.__back]
    self.__back = (self.__back - 1 + self.__capacity) % self.__capacity
    self.__size -= 1
    return val

    '''
      This function is O(1). Since, array lookups are constant time
      and back is already computed this function would always
      take the same number of steps making it O(1).
    '''

  def peek_back(self):
    if len(self):
      return self.__contents[self.__back]

    '''
      This function is O(1). Since, array lookups are constant time
      and back is already computed this function would always
      take the same number of steps making it O(1).
    '''

# No main section is necessary. Unit tests take its place.
# if __name__ == '__main__':
  # pass


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sect_comp import Sector
import pandas as pd

engine = create_engine('sqlite:///sector_comp.db')

Session = sessionmaker(bind=engine)
session = Session()

s = pd.read_csv('/home/pallabeedey/Indian_fins/data/sec2.csv')
l1=len(s)

for i in range(0,l1):
    code= s['sector_code'][i]
    name= s['sector_name'][i]
    session.add(Sector(name, code))

session.commit()


# 236. 二叉树的最近公共祖先
# 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

# 百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”

# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        nodes = set()
        ans = None
        def find(root,p):
            nonlocal ans
            flag = False
            if not root:
                return flag
            flag = root == p or find(root.left,p) or find(root.right,p)
            if flag:
                if root in nodes and ans is None:
                    ans = root
                nodes.add(root)
            return flag
        find(root,p)
        find(root,q)
        return ans


import time, threading, socket

def method1(param):
    param[0]
    try:
        while param[0]:
            data = param[1].recv(1024)
            if (len(data) < 1): break
            print("method3: param: " + str(data))
            time.sleep(1)
    except:
        pass
    print("method1 was ended")

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('192.168.0.23', 10003))
c = [True, s]

t = threading.Thread(target=method1, args=(c,))
t.start()
time.sleep(5)
try:
    #c[0] = False
    c[1].shutdown(socket.SHUT_RD)
    c[1].close()
except:
    print("raised except")

print(str(c[1]))
print("Tried...")

t.join()

print("end")


#! /usr/bin/env python
import time
import select
import socket
ADDR=('192.168.1.101', 8000)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
time.sleep(0.500)
s.send("HelloWorld")
time.sleep(0.500)
print (s.recv(10))
time.sleep(3)
print ("closing")
s.close()


#!/usr/bin/env python

from setuptools import setup

PACKAGE = 'timingandestimationplugin'

setup(name=PACKAGE,
      description='Plugin to make Trac support time estimation and tracking',
      keywords='trac plugin estimation timetracking',
      version='0.1.5',
      url='',
      license='http://www.opensource.org/licenses/mit-license.php',
      author='Russ Tyndall at Acceleration.net',
      author_email='russ@acceleration.net',
      long_description="""
      This Trac 0.10 plugin provides support for Time estimation and tracking.

      See http://trac-hacks.org/wiki/TimeEstimationAndQuotingSpecification for details.
      """,
      packages=[PACKAGE],
      package_data={PACKAGE : ['templates/*.cs', 'htdocs/*']},
      entry_points={'trac.plugins': '%s = %s' % (PACKAGE, PACKAGE)})


import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from toolz.sandbox import unzip
from torch.utils.data import Dataset
from torchvision import transforms
import more_itertools
import numpy as np

class FeedForwardLayer(nn.Module):
    def __init__(self, input_dim, output_dim, dropout, activator=nn.ReLU()):
        super().__init__()
        self.linear = nn.Linear(input_dim, output_dim)
        self.dropout = nn.Dropout(dropout)
        self.norm = nn.BatchNorm1d(output_dim)
        self.activator = activator
        self.residule = (input_dim == output_dim)

    def forward(self, x):
        tmp = self.linear(x)
        shape = tmp.shape
        tmp = tmp.view(shape[0], -1, shape[-1]).permute(0, 2, 1).contiguous()
        tmp = self.dropout(self.activator(self.norm(tmp)))
        tmp = tmp.view(*shape)
        if self.residule:
            return x + tmp
        else:
            return tmp

class MultiLayerFeedForwardLayer(nn.Module):
    def __init__(self, n_layer, input_dim, hidden_size, output_dim, dropout, activator=nn.ReLU(), last_no_activate=False):
        super().__init__()
        linear_stack = [FeedForwardLayer(input_dim, hidden_size, dropout, activator=activator)]
        linear_stack += [FeedForwardLayer(hidden_size, hidden_size, dropout, activator=activator) for _ in range(n_layer-2)]
        linear_stack += [nn.Linear(hidden_size, output_dim)] if last_no_activate else [
            FeedForwardLayer(hidden_size, output_dim, dropout, activator=activator)]
        self.feed_forward_layers = nn.Sequential(
            *linear_stack
        )

    def forward(self, x):
        return self.feed_forward_layers(x)

class ConvolutionLayer(nn.Module):
    def __init__(self, in_channels, output_channels, kernel_size, padding, stride=1,
                 dropout=0.2, activator=nn.ReLU(), dimention=1, pool="max",
                 pool_kernel_size=2, pool_stride=2, pool_pad=0):
        super().__init__()
        self.conv = nn.Conv2d(in_channels=in_channels, out_channels=output_channels,
                              kernel_size=kernel_size, padding=padding, stride=stride)
        self.dropout = nn.Dropout(dropout)
        self.norm = nn.BatchNorm2d(output_channels)
        self.activator = activator
        self.residule = (in_channels == output_channels)
        if pool == "max":
            self.pool = nn.MaxPool2d(pool_kernel_size, stride=pool_stride, padding=pool_pad)

    def forward(self, x):
        tmp = self.dropout(self.activator(self.pool(self.norm(self.conv(x)))))
        if self.residule:
            return x + tmp
        else:
            return tmp

class MultiConvolutionLayer(nn.Module):
    def __init__(self, n_layer, in_channels, output_channels, kernel_size, padding, stride=1,
                 dropout=0.2, activator=nn.ReLU(), pool="max"):
        super().__init__()
        self.feed_forward_layers = nn.Sequential(
            *([ConvolutionLayer(in_channels, output_channels, kernel_size, padding, stride,
                                dropout, activator=activator)] +
              [ConvolutionLayer(output_channels, output_channels, kernel_size, padding, stride,
                                dropout, activator=activator) for _ in range(n_layer - 1)])
        )

    def forward(self, x):
        return self.feed_forward_layers(x)


import contextlib
import glob
import json
import os
from functools import reduce

from core.parse_config import Parse, CustomError
from log.log import logger

class CreatPTFile(Parse):
    def __init__(self, ost, wavs_map, _save_path):
        """
        :param config_path: config文件路径
        :param wav_path: 对应音频文件路径
        """
        super(CreatPTFile, self).__init__(ost)
        self.wav_time_map = wavs_map  # 创建音频地址映射关系
        self._save_path = _save_path

    @staticmethod
    def mkdir(path):
        if not os.path.exists(path):
            os.mkdir(path)
        return path

    def run(self, custom_classfy):
        """
        遍历config文件和音频路径，将其新平台文本格式信息写到output/result.txt文件中
        :param custom_classfy: 自定义分包条数，默认按spk音频数分包
        """
        logger.debug('遍历wav_name,text信息')
        wav_suf = 'wav'
        counter = 0
        wavs_info_map = {}

        for SPK, wav_name, content in self.get_info():  # 遍历说话人id，音频名，音频内容 信息
            logger.debug('[wav_info] %s - %s - %s ' % (SPK, wav_name, content))

            if wav_name not in self.wav_time_map:
                logger.warning('[%s] 未找到音频' % wav_name)
                continue

            wav_time = self.wav_time_map.get(wav_name)
            if not wav_time:
                continue

            wav_info = [  # 填充新平台文本格式
                {
                    "Wav_name": wav_name,
                    "Length_time": wav_time,
                    "Data": [
                        {
                            "text": content,
                            "start_time": 0,
                            "end_time": wav_time
                        }
                    ],
                    "Wav_suf": wav_suf
                }
            ]

            if custom_classfy:  # 指定分包数的模式
                id = f'line_{counter}'
                if id not in wavs_info_map:
                    wavs_info_map[id] = [wav_info]

                else:
                    if len(wavs_info_map[id]) == custom_classfy - 1:
                        counter += 1

                    wavs_info_map[id].append(wav_info)

            else:  # 默认分包模式
                if SPK not in wavs_info_map:
                    wavs_info_map[SPK] = [wav_info]
                else:
                    wavs_info_map[SPK].append(wav_info)

        logger.info(
            '处理完毕！ 共 %s 批次 [%s]' % (len(wavs_info_map.keys()), wavs_info_map.keys()) if not custom_classfy else (
                counter, len(reduce(lambda x, y: x + y, wavs_info_map.values()))))

        with open(self._save_path, 'w', encoding='utf-8') as f:
            for key, value in wavs_info_map.items():
                f.write(json.dumps(value, ensure_ascii=False) + '\n')


import select
import socket
import sys
import threading
from des import decryption, encryption

class Server:
    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 8080
        self.threads = []

    def open_socket(self):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.bind((self.host, self.port))
        self.server.listen(3)

    def run(self):
        self.open_socket()
        input_list = [self.server]
        while 1:
            read_ready, write_ready, exception = select.select(input_list, [], [])
            for r in read_ready:
                if r == self.server:
                    client_socket, client_address = self.server.accept()
                    print("Sudah terhubung dengan klien")
                    c = Client(client_socket, client_address, input_list)
                    c.start()
                    self.threads.append(c)
        self.server.close()

        for c in self.threads:
            c.join()

class Client(threading.Thread):
    def __init__(self, client, address, input_list):
        threading.Thread.__init__(self)
        self.sock = client
        self.SOCKET_LIST = input_list
        self.client = client
        self.address = address
        self.size = 1024

    def run(self):
        try:
            while 1:
                data = self.client.recv(self.size)
                if data:
                    data = data.decode('utf-8')
                    print(f"\nCiphertext : {data}")
                    decrypted = decryption(data)
                    print(f"Decrypted Text: {decrypted}\n")

                    print("Masukkan Pesan:")
                    response = input()
                    encrypted_response = encryption(response)
                    self.client.send(encrypted_response.encode('utf-8'))
                else:
                    self.client.close()
        except:
            if self.sock in self.SOCKET_LIST:
                self.SOCKET_LIST.remove(self.sock)

            print("Klien tidak ditemukan")
            self.client.close()

if __name__ == "__main__":
    try:
        server = Server()
        server.run()
    except KeyboardInterrupt:
        sys.exit(0)


from datetime import date, datetime
import os
from turtle import title
from flask import Flask, request
from flask_restx import Api, Resource, fields
from flask_sqlalchemy import SQLAlchemy

from app.file_to_use import Books

app = Flask(__name__)
api = Api(app, version='1.0', title='BookMVC API',
    description='A simple BookMVC API',
)

basedir = os.path.dirname(os.path.realpath(__file__))

endoint = api.namespace('Book', description='TODO operations on Book')

app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///book.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
app.config['SQLALCHEMY_ECHO']=True

db=SQLAlchemy(app)

class Book(db.Model):
    book_id=db.Column(db.Integer(),primary_key=True)
    author=db.Column(db.String(80),nullable=False)
    country=db.Column(db.String(50),nullable=False)
    imageLink=db.Column(db.String(80),nullable=False)
    language=db.Column(db.String(20),nullable=False)
    link=db.Column(db.String(80),nullable=False)
    pages=db.Column(db.String(10),nullable=False)
    title=db.Column(db.String(50),nullable=False)
    year=db.Column(db.String(10),nullable=False)
    date_added=db.Column(db.String(20), default=date)

    def __init__(self,author,country,imageLink,language,link,pages,title,year,date):
        self.author = author
        self.country = country
        self.imageLink = imageLink
        self.language = language
        self.link = link
        self.pages = pages
        self.title = title
        self.year = year
        self.date_added = date

book_model = api.model('Book', {
    'book_id': fields.Integer(),
    'author': fields.String(),
    'country': fields.String(),
    'imageLink': fields.String(),
    'language': fields.String(),
    'link': fields.String(),
    'pages': fields.Integer(),
    'title': fields.String(),
    'year': fields.Integer(),
    'date_added': fields.Date()
})

@endoint.route('/')
class BookList(Resource):
    @endoint.marshal_list_with(book_model)
    def get(self):
        '''List all books'''
        books = Book.query.all()
        return books

    @endoint.expect(book_model)
    @endoint.marshal_with(book_model, code=201)
    def post(self):
        '''Create a new book'''
        data = request.get_json()
        book_author = data.get('author')
        book_country = data.get('country')
        book_imageLink = data.get('imageLink')
        book_language = data.get('language')
        book_link = data.get('link')
        book_pages = data.get('pages')
        book_title = data.get('title')
        book_year = data.get('year')
        date_added = data.get('date_added')
        new_book = Book(
            author=book_author,
            country=book_country,
            imageLink=book_imageLink,
            language=book_language,
            link=book_link,
            pages=book_pages,
            title=book_title,
            year=book_year,
            date=date_added
        )
        db.session.add(new_book)
        db.session.commit()
        return new_book, 201
        # return DAO.create(api.payload), 201

@endoint.route('/<int:id>')
@endoint.response(404, 'Todo not found')
class Todo(Resource):
    @endoint.marshal_with(book_model)
    def get(self, id):
        '''Fetch a given resource'''
        book = Book.query.get(id)
        return book

    @endoint.response(204, 'Todo deleted')
    def delete(self, id):
        book_to_delete = Book.query.get(id)
        db.session.delete(book_to_delete)
        db.session.commit()
        return '', 204

    @endoint.expect(book_model)
    @endoint.marshal_with(book_model)
    def put(self, id):
        '''Update a task given its identifier'''
        book_to_update = Book.query.get(id)
        data = request.get_json()
        book_to_update.author = data.get('author')
        book_to_update.country = data.get('country')
        book_to_update.imageLink = data.get('imageLink')
        book_to_update.language = data.get('language')
        book_to_update.link = data.get('link')
        book_to_update.pages = data.get('pages')
        book_to_update.title = data.get('title')
        book_to_update.year = data.get('year')
        book_to_update.date_added = data.get('date_added')

        db.session.commit()
        return book_to_update, 200


import base64
import datetime

import dash_bootstrap_components as dbc

from dash import html, dcc, callback, dash_table, no_update
from dash.dependencies import Input, Output, State

from utils.upload import UploadIO

def render_reading_exception(upload, exc):
    file_name = upload.file_name
    error_name = exc.__class__.__name__
    error_message = str(exc)

    return html.P(
        className='alert alert-danger',
        children=[
            html.Strong(f'{file_name} - {error_name}'),
            f': {error_message}'
        ])

def render_unsupported_upload(u):
    return html.P(
        className='alert alert-danger',
        children=[
            html.Strong(f'{u.file_name} - Formato no soportado'),
            f': {u.content_type}'
        ])

def render_upload(upload):
    df = upload.df.head(10)

    return html.Div([
        html.H5(upload.file_name),
        html.H6(datetime.datetime.fromtimestamp(upload.modified_date)),
        dash_table.DataTable(
            df.to_dict('records'),
            [{'name': i, 'id': i} for i in df.columns]
        ),
    ])

class UploadInput(object):
    def __init__(
        self,
        id_suffix,
        outputs,
        upload_fn,
        reading=True,
        rendering_uploads=False,
    ):
        self.upload_id = f'upload-data-{id_suffix}'
        self.output_id = f'output-upload-data-{id_suffix}'
        self.outputs = outputs
        self.reading = reading
        self.rendering_uploads = rendering_uploads
        self.upload_fn = upload_fn

    def display(self):
        layout = self.render_components()
        self.register_callbacks()

        return layout

    def register_callbacks(self):
        @callback(
            Output(self.output_id, 'children'),
            *self.outputs,
            Input(self.upload_id, 'contents'),
            State(self.upload_id, 'filename'),
            State(self.upload_id, 'last_modified'),
            prevent_initial_call=True,
        )
        def upload_main_callback(contents, filenames, dates):
            no_updates = [no_update for n in self.outputs]

            if contents is None:
                return ([], *no_updates)

            uploads = [
                UploadIO(c, n, d) for c, n, d in
                zip(contents, filenames, dates)
            ]

            unsupported = [u for u in uploads if u.validate_support() == False]
            if (len(unsupported) > 0):
                children = [render_unsupported_upload(u) for u in unsupported]
                return (children, *no_updates)

            if self.reading:
                for u in uploads:
                    try:
                        u.read()
                    except Exception as e:
                        children = render_reading_exception(u, e)
                        return (children, *no_updates)

            (error_layout, *values) = self.upload_fn(uploads)
            if (error_layout):
                return (error_layout, *no_updates)
            elif (self.rendering_uploads):
                children = [render_upload(u) for u in uploads]
                return (children, *values)
            else:
                return (no_update, *values)

    def render_components(self):
        return dbc.Container(
            [
                dcc.Upload(
                    id=self.upload_id,
                    children=html.Div([
                        'Agregar archivos\n(click o arrastre)',
                    ]),
                    style={
                        'width': '100%',
                        'height': '60px',
                        'lineHeight': '60px',
                        'borderWidth': '1px',
                        'borderStyle': 'dashed',
                        'borderRadius': '5px',
                        'textAlign': 'center',
                        'margin': '10px',
                        'cursor': 'pointer',
                        'userSelect': 'none',
                    },
                    multiple=True
                ),
                html.Div(id=self.output_id),
            ]
        )


import pyspark.sql.functions as f
import pyspark.sql.types as t

FILE_PATHS = {
    'df_aluno': 'data/enade2019/SUP_ALUNO_2019.CSV',
    'df_curso': 'data/enade2019/SUP_CURSO_2019.CSV',
}

class Enade2019ToParquet:
    def __init__(self, spark_session):

        self.spark = spark_session
        self.read_options = {'header': True, 'sep': '|'}

    def read_data(self):
        self.df_aluno = (self.spark.read.format('csv').options(
            **self.read_options).load(FILE_PATHS['df_aluno']))

        self.df_curso = (self.spark.read.format('csv').options(
            **self.read_options).load(FILE_PATHS['df_curso']))

    def write_data(self):
        self.df_aluno.write.format('parquet').mode('overwrite').save(
            'data/enade2019/parquet/aluno/')

        self.df_curso.write.format('parquet').mode('overwrite').save(
            'data/enade2019/parquet/curso/')

    def run(self):
        self.read_data()
        self.write_data()


"""
출처: https://www.acmicpc.net/problem/11051
"""

import collections
import sys

dp = collections.defaultdict(int)
f_dp = collections.defaultdict(int)

def factorial(n: int) -> int:
    if f_dp[n]:
        return f_dp[n]

    f_dp[0] = 1
    for i in range(1, n + 1):
        f_dp[i] = f_dp[i - 1] * i
    return f_dp[i]

def combination(n: int, r: int) -> int:
    if dp[(n, r)]:
        return dp[(n, r)]

    if n == r or r == 0:
        dp[(n, r)] = 1
        return dp[(n, r)]

    dp[(n, r)] = (factorial(n) // (factorial(r) * factorial(n - r))) % 10007
    return dp[(n, r)]

if __name__ == '__main__':
    n, r = map(int, sys.stdin.readline().rstrip().split())
    print(combination(n, r))


import unittest
from collections import namedtuple
from day_24 import find_strongest_bridge, find_longest_bridge

class TestBridge(unittest.TestCase):
    """Test Bridge."""

    def test_find_strongest_bridge(self):
        Test = namedtuple('Test', ['components', 'expected'])
        tests = [
            Test(expected=([(0, 1), (1, 10), (10, 9)], 31),
                 components=[(2, 0), (2, 2), (2, 3), (3, 4),
                             (3, 5), (0, 1), (10, 1), (9, 10)])
        ]

        for test in tests:
            result = find_strongest_bridge(test.components)
            self.assertEqual(result, test.expected)

    def test_find_longest_bridge(self):
        Test = namedtuple('Test', ['components', 'expected'])
        tests = [
            Test(expected=([(0, 2), (2, 2), (2, 3), (3, 5)], 19),
                 components=[(2, 0), (2, 2), (2, 3), (3, 4),
                             (3, 5), (0, 1), (10, 1), (9, 10)])
        ]

        for test in tests:
            result = find_longest_bridge(test.components)
            self.assertEqual(result, test.expected)

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

Advent of Code 2017/Day 24/test_day_24.py


N, M = map(int, input().split())
board = [list(input()) for _ in range(M)]
visited = [[False] * N for _ in range(M)]
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
BLUE_TEAM = 'B'
WHITE_TEAM = 'W'
blue_team_power = 0
white_team_power = 0

def dfs(row, col, team):
    visited[row][col] = True
    count = 1

    for i in range(len(dr)):
        nr = row + dr[i]
        nc = col + dc[i]

        if (nr < M and nr >= 0 and nc < N and nc >= 0 and board[nr][nc] == team and visited[nr][nc] == False):
            count += dfs(nr, nc, team)

    return count

for i in range(M):
    for j in range(N):
        if (visited[i][j] == False):
            result = dfs(i, j, board[i][j])

            if (board[i][j] == BLUE_TEAM):
                blue_team_power += result ** 2
            else:
                white_team_power += result ** 2

print(white_team_power, blue_team_power)


from manillen_classes import man_player, man_team, man_game, viewer

import manillen_const
import cards
import time
import logging
from manillen_game_logic import card_allowed

class engine:
    def __init__(self, test_module=None):
        logging.basicConfig(level=logging.INFO)
        self.logger_engine = logging.getLogger('engine_working')
        self.logger_game = logging.getLogger('engine_game')

        self.handler = logging.FileHandler('logs/games.log')
        self.handler.setLevel(logging.INFO)

        formatter = logging.Formatter('%(asctime)s ,%(message)s')
        self.handler.setFormatter(formatter)

        self.logger_game.addHandler(self.handler)

        self.logger_engine.info("created engine")

        self.game_set = {}
        self.id_set_games = {}
        self.id_set_player = {}
        self.id_set_viewer = {}

        self.valuedict = {"10": 5, "A": 4, "K": 3, "Q": 2, "J": 1, "9": 0, "8": 0, "7": 0}
        self.comparevalue = {"10": 7, "A": 6, "K": 5, "Q": 4, "J": 3, "9": 2, "8": 1, "7": 0}

        self.function_dict = {"add_player": self.add_player, "answer_troef": self.receive_troef, "answer_card": self.receive_card, "add_viewer": self.add_viewer, "disconnect": self.remove_subscriber, "reset_game": self.reset_game, "keep_waiting" : self.keep_waiting}

        self.test_mod = test_module

    def get_functions(self):
        return self.function_dict

    def restart_play(self, game):
        self.send_all_players("restarted_game", game)
        if game.troef_choosen:
            self.play_cards(game)
        else:
            game.players[game.troef_chooser_pos].send("choose_troef")

    def start_play(self, game):
        if not game.started:
            game.started = True

            team_names = [team.name for team in game.teams]

            game.set_default_indices()

            self.send_all_players("set_teams", game, team_names)

            self.play_round(game)
        else:
            self.logger_engine.error("game should be restarted, not started")

    def play_round(self, game):

        self.distribute_cards(game)

        if game.troef_choosen:
            game.troef_choosen = False
            game.troef_chooser_pos = (game.troef_chooser_pos + 1) % 4
            game.round_start_pos = (game.troef_chooser_pos + 1) % 4
            game.troef = None
            game.cards_played = 0

            score = 0
            for card in game.teams[0].cards:
                score += self.valuedict[card[1:]]

            for team in game.teams:
                team.reset_round()

            if score < 30:
                game.teams[1].add_points(30 - score)
            else:
                game.teams[0].add_points(score - 30)

            self.send_all_players("update_score", game, data={"team0":game.teams[0].prev_scores,"team1":game.teams[1].prev_scores})

            for team in game.teams:
                if team.score > manillen_const.score_end:
                    self.end_game(game)
        troef_chooser = game.players[game.troef_chooser_pos]
        self.logger_engine.info("  " + troef_chooser.name + " was asked for troef")
        troef_chooser.send("choose_troef")

    def distribute_cards(self, game):
        player_cards = cards.getCards({"min": "7", "split_stack": 4, "shuffle": True, "sorted": True})

        for i in range(4):
            game.players[i].set_cards(player_cards[i])

            game.players[i].send("receive_play_cards", data=player_cards[i])

    def play_cards(self, game):
        if game.round_play_offset == 4:
            # see to which team the cards should go
            troef_active = False
            winning_index = 0
            starting_suit = game.table_cards[0][0]
            for i in range(len(game.table_cards)):
                if troef_active:
                    if self.comparevalue[game.table_cards[i][1:]] > self.comparevalue[game.table_cards[winning_index][1:]] and game.table_cards[i][0] == game.troef:
                        winning_index = i
                else:
                    if game.table_cards[i][0] == game.troef:
                        winning_index = i
                        troef_active = True
                    elif game.table_cards[i][0] == starting_suit \
                            and self.comparevalue[game.table_cards[i][1:]] > self.comparevalue[game.table_cards[winning_index][1:]]:
                        winning_index = i
            self.logger_engine.info(" These cards were played: " + str(game.table_cards)
                                    + " and " + str(game.table_cards[winning_index])
                                    + " won, this is player: " + game.players[(game.round_start_pos + winning_index)%4].name)

            game.round_start_pos = (game.round_start_pos + winning_index)%4
            game.players[game.round_start_pos].team.cards.extend(game.table_cards)
            game.table_cards = []
            game.round_play_offset = 0
            game.cards_played += 1

            self.send_all_players("clear_board", game)

        if game.cards_played == 8:
            self.play_round(game)

        else:
            current_player = game.players[(game.round_start_pos + game.round_play_offset) % 4]
            self.logger_engine.info("  " + current_player.name + " was asked to play card")
            current_player.send("play_card")

    def end_game(self, game):
        a = 5

    def send_all_players(self, command, game, data=None, viewer=True):
        for player in game.players:
            if player is not None:
                player.send(command, data=data)

        if viewer:
            for viewer in game.viewers:
                viewer.send(command, data)

    def receive_card(self, id, card):
        # check if valid card and allowed to play
        this_game = self.id_set_games[id]
        this_player = self.id_set_player[id]
        self.logger_engine.info(" received card from: " + this_player.name + " from team: " + this_player.team.name)

        card_from_player = card in this_player.cards
        should_be_index = this_game.players.index(this_player)
        current_index = (this_game.round_start_pos + this_game.round_play_offset)%4
        allowed = should_be_index == current_index

        if allowed and card_from_player and card_allowed(card, this_game.table_cards, this_player.cards, this_game.troef):
            self.logger_engine.info(" card is valid")
            this_player.send("valid_card")
            this_game.table_cards.append(card)

            self.send_all_players("new_table_card", this_game, data= {"card": card, "index": len(this_game.table_cards) - 1})

            this_game.round_play_offset += 1
            this_player.cards.remove(card)

            self.logger_game.info("card;" + str(this_player.position) + ";" + card)

            self.play_cards(this_game)
        else:
            self.logger_engine.info(" card is NOT valid")
            this_player.send("invalid_card")

    def receive_troef(self, id, data):
        # check if players card and allowed to choose troef
        this_game = self.id_set_games[id]
        this_player = self.id_set_player[id]

        # allow for sending full card and only the char
        for card in this_player.cards:
            if data[0] == card[0]:
                card_from_player = True
                break

        allowed = not this_game.troef_choosen and this_game.players.index(this_player) == this_game.troef_chooser_pos

        if card_from_player and allowed:
            self.send_all_players("send_troef", this_game, data=data[0])

            this_game.troef_choosen = True
            this_game.troef = data[0]

            self.logger_game.info("troef;" + str(this_player.position) + ";" + data)

            self.play_cards(this_game)
        else:
            this_player.send("invalid_troef")

    def add_viewer(self, id, data):
        table_name = data["table_name"]
        comm_module = data["comm_module"]

        this_viewer = viewer(id, comm_module)

        if table_name in self.game_set:
            this_game = self.game_set[table_name]
        else:
            this_game = man_game(table_name)
            self.game_set[table_name] = this_game

        this_game.add_viewer(this_viewer)
        self.id_set_viewer[id] = this_viewer
        this_viewer.set_game(this_game)
        this_viewer.send("allow_viewing")

    def add_player(self, id, data):
        table_name = data["game_name"]
        team_name = data["team_name"]
        position_in_team = int(data["location_in_team"])
        position_of_team = int(data["location_of_team"])
        position = position_of_team + 2 * position_in_team
        player_name = data["player_name"]
        comm_module = data["comm_module"]

        if table_name in self.game_set:
            this_game = self.game_set[table_name]
        else:
            this_game = man_game(table_name)
            self.game_set[table_name] = this_game

        if this_game.get_state("rejoin_waiting") or this_game.get_state("wait_decision"):
            this_player = this_game.get_deleted_player(player_name)
            if this_player is not None:
                this_game.reinstate_player(this_player)
                this_player.id = id
                self.id_set_games[id] = this_game
                self.id_set_player[id] = this_player

                team_names = [team.name for team in this_game.teams]

                this_player.send("set_teams", data=team_names)

                this_player.send("receive_play_cards", data=this_player.cards)

                this_player.send("wait_other_players")

                if len(this_game) == 4:
                    self.restart_play(this_game)
        else:
            this_player = man_player(player_name, id, comm_module, position=position)

            this_player.set_game(this_game)

            this_team = this_game.get_team(team_name)
            # team doesn't exist
            if this_team is None:
                this_team = man_team(team_name, position_of_team)
                this_game.add_team(this_team)
                this_team.set_game(this_game)

            this_team.add_player(this_player)
            this_player.add_team(this_team)
            self.id_set_games[id] = this_game
            self.id_set_player[id] = this_player
            this_game.add_player(this_player)

            if len(this_game) == 4:
                if not this_game.started:
                    self.start_play(this_game)

            this_player.send("wait_other_players")

        return id

    def reset_game(self, id):
        this_game = self.id_set_games[id]
        this_game.reset()
        this_game.set_state("not_started")

    def keep_waiting(self, id):
        this_game = self.id_set_games[id]
        this_game.set_state("rejoin_waiting")

    # can be player of viewer
    def remove_subscriber(self, id):
        self.logger_game.info("  player has left game")
        if id in self.id_set_viewer:
            this_viewer = self.id_set_viewer[id]
            this_game = this_viewer.game

            this_game.remove_viewer(this_viewer)
            self.id_set_viewer.pop(id)
        elif id in self.id_set_player:
            this_player = self.id_set_player[id]
            this_game = this_player.game

            this_game.remove_player(this_player)
            self.id_set_player.pop(id)
            self.id_set_games.pop(id)
            self.return_to_test_set(this_player)
            if this_game.started:
                self.send_all_players("reset_game_lost_player", this_game, viewer=False)
                this_game.set_state("wait_decision")

    def return_to_test_set(self, player):
        if self.test_mod is not None:
            table_name = player.game.name
            team_name = player.team.name
            player_name = player.name
            team_location = player.team.position
            in_team_location = player.position // 2

            self.test_mod.return_vector({'game_name': table_name, 'team_name': team_name,
             'player_name': player_name, 'team_location_input': team_location,
             "team_player_location_input": in_team_location})

    def create_player(self, name, id, cards, position, comm):
        return man_player(name, id, comm, position=position, cards=cards)

    def create_team(self, name, position, players):
        this_team = man_team(name, position, players=players)

        for player in players:
            player.set_team(this_team)
        return this_team

    def create_game(self, table_name, teams):
        this_game = man_team(table_name)

        for team in teams:
            this_game.add_team(team)
        return this_game

if __name__ == "__main__":
    print("========== testing engine ==========")
    en = engine()
    print("========== card allowed ==========")
    # card, table cards, player_cards, troef
    # player should play K10
    print(en.card_allowed("KJ", ["K8", "KQ"], ["K10", "H9", "KJ"], 'H') == False)
    # player should buy
    print(en.card_allowed("S10", ["K8", "KQ"], ["S10", "H9", "SJ"], 'H') == False)
    #valid play
    print(en.card_allowed("K10", ["K8", "KQ"], ["S10", "K10", "KJ"], 'H') == True)
    #valid play
    print(en.card_allowed("S10", ["KQ", "K8"], ["S10", "H9", "SJ"], 'H') == True)


'''
    Crie uma rotina que calcule a soma dos 100 primeiros elementos da séria de
    Fibonacci (0, 1, 1, 2, 3, 5, 8, ...).

'''

sequencia = [] ##Iniciando a sequencia de Fibonacci
ultimo = 1
penultimo = 1
sequencia.append(penultimo)
sequencia.append(ultimo)

contador = 3

while contador <= 100:
    numero = ultimo + penultimo
    sequencia.append(numero)
    penultimo = ultimo
    ultimo = numero

    contador = contador + 1

print(sum(sequencia))


import keyboard
from time import sleep

start = int(input("Please provide the starting number: "))
end = int(input("Please provide the end number: "))
print('''The program will start shortly, tab into discord to start.''')
sleep(4)
for i in range(start,end+1):
    keyboard.write(str(i),0.02)
    sleep(3) #shorten this to make it more fast
    keyboard.press("enter")
    sleep(0.01)
    keyboard.release("enter")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    @Author : tangkaize
#
#              _____               ______
#     ____====  ]OO|_n_n__][.      |    |]
#    [________]_|__|________)<
#     oo    oo  'oo OOOO-| oo\_   ~o~~~o~'
# +--+--+--+--+--+--+--+--+--+--+--+--+--+
#    @Time : 2022/12/30 11:09
#    @FIle： demo23.py 依赖性 Depends()的用法
#    @Software: PyCharm
from typing import Union

import uvicorn
from fastapi import FastAPI, Depends

app = FastAPI()

async def common_parameters(
        q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
    return {"q": q, "skip": skip, "limit": limit}

# 依赖的注入
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
    return commons

if __name__ == '__main__':
    uvicorn.run('demo23:app', host='0.0.0.0', port=8000)


import os

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

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'this is a hard to guess string'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    @staticmethod
    def init_app(app):
        pass

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')

class TestingConfig(Config):
    TEST = True
    SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
        'sqlite://'

class ProductionConfig(Config):
    DEBUG = False
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'data.sqlite')

    @classmethod
    def init_app(cls, app):
        Config.init_app(app)

class DockerConfig(ProductionConfig):
    @classmethod
    def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'docker': DockerConfig,
    'default': DevelopmentConfig
}


#!/usr/bin/python2.7
#
# Assignment3 Interface
#

import psycopg2
import os
import sys
import threading

FIRST_TABLE_NAME = 'MovieRating'
SECOND_TABLE_NAME = 'MovieBoxOfficeCollection'
SORT_COLUMN_NAME_FIRST_TABLE = 'Rating'
SORT_COLUMN_NAME_SECOND_TABLE = 'Collection'
JOIN_COLUMN_NAME_FIRST_TABLE = 'MovieID'
JOIN_COLUMN_NAME_SECOND_TABLE = 'MovieID'

numberOfThreads = 5

# Donot close the connection inside this file i.e. do not perform openconnection.close()
def ParallelSort (InputTable, SortingColumnName, OutputTable, openconnection):

    cur = openconnection.cursor()

    #getting min value and max value from the sorting column
    query_str = "SELECT MIN(" + SortingColumnName + "), MAX(" + SortingColumnName + ") FROM " + InputTable + ";"
    cur.execute(query_str)
    minval, maxval = cur.fetchone()

    #creating intervals based on number of threads
    interval = float(maxval - minval) / numberOfThreads

    #getting input table schema to generate partition tables
    query = "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = \'" + InputTable + "\';"
    cur.execute(query)
    InputTableSchema = cur.fetchall()
    #print(InputTableSchema)

    #create "total number of threads" partition tables
    for i in range(numberOfThreads):
        partTable = "range_part" + str(i)
        cur.execute("DROP TABLE IF EXISTS " + partTable)
        temp = "CREATE TABLE " + partTable + " (" + InputTableSchema[0][0] + " " + InputTableSchema[0][1] + ");"
        cur.execute(temp)

        for value in range(1, len(InputTableSchema)):
            temp = "ALTER TABLE " + partTable + " ADD COLUMN " + InputTableSchema[value][0] + " " + InputTableSchema[value][
                1] + ";"
            cur.execute(temp)

    threads = [0]*numberOfThreads

    for i in range(numberOfThreads):

        minvalue = minval + i * interval
        maxvalue = minvalue + interval

        #implementing parallelized threads
        threads[i] = threading.Thread(target=helperSort,
                                      args=(InputTable, SortingColumnName, i, minvalue, maxvalue, openconnection))

        threads[i].start()

    for i in range(numberOfThreads):
        threads[i].join()

    #create output table
    cur.execute("DROP TABLE IF EXISTS " + OutputTable)
    temp = "CREATE TABLE " + OutputTable + " (" + InputTableSchema[0][0] + " " + InputTableSchema[0][1] + ");"
    cur.execute(temp)
    for value in range(1, len(InputTableSchema)):
        temp = "ALTER TABLE " + OutputTable + " ADD COLUMN " + InputTableSchema[value][0] + " " + InputTableSchema[value][
            1] + ";"
        cur.execute(temp)

    #insert data into output table from partition tables
    for i in range(numberOfThreads):
        temp = "INSERT INTO " + OutputTable + " SELECT * FROM range_part" + str(i) + ";"
        cur.execute(temp)

    #delete all the partition tables
    for i in range(numberOfThreads):
        temp = "DROP TABLE IF EXISTS range_part" + str(i) + ";"
        cur.execute(temp)

    openconnection.commit()

def helperSort(InputTable, SortingColumnName, i, minvalue, maxvalue, openconnection):
    cur = openconnection.cursor()
    partTable = "range_part" + str(i)

    #insert data into corresponding partition table
    if i == 0:
        temp = "INSERT INTO " + partTable + " SELECT * FROM " + InputTable + " WHERE " + SortingColumnName + " >= " + str(
            minvalue) + " AND " + SortingColumnName + " <= " + str(
            maxvalue) + " ORDER BY " + SortingColumnName + " ASC;"
    else:
        temp = "INSERT INTO " + partTable + " SELECT * FROM " + InputTable + " WHERE " + SortingColumnName + " > " + str(
            minvalue) + " AND " + SortingColumnName + " <= " + str(
            maxvalue) + " ORDER BY " + SortingColumnName + " ASC;"
    cur.execute(temp)
    return

def ParallelJoin (InputTable1, InputTable2, Table1JoinColumn, Table2JoinColumn, OutputTable, openconnection):
    cur = openconnection.cursor()
    temp = "SELECT MIN(" + Table1JoinColumn + "), MAX(" + Table1JoinColumn + ") FROM " + InputTable1 + ";"
    cur.execute(temp)
    mintbl1,maxtbl1 = cur.fetchone()

    temp = "SELECT MIN(" + Table2JoinColumn + "), MAX(" + Table2JoinColumn + ") FROM " + InputTable2 + ";"
    cur.execute(temp)
    mintbl2,maxtbl2 = cur.fetchone()

    #print(mintbl1,maxtbl1,mintbl2,maxtbl2)

    maxval = max(maxtbl1, maxtbl2)
    minval = min(mintbl1, mintbl2)
    interval = (maxval - minval) / numberOfThreads

    temp = "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = \'" + InputTable1 + "\';"
    cur.execute(temp)
    InputTableSchema1 = cur.fetchall()

    temp = "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = \'" + InputTable2 + "\';"
    cur.execute(temp)
    InputTableSchema2 = cur.fetchall()

    #create schema of output table
    cur.execute("DROP TABLE IF EXISTS " + OutputTable)
    temp = "CREATE TABLE " + OutputTable + " (" + InputTableSchema1[0][0] + " " + InputTableSchema1[0][1] + ");"
    cur.execute(temp)

    for value in range(1, len(InputTableSchema1)):
        temp = "ALTER TABLE " + OutputTable + " ADD COLUMN " + InputTableSchema1[value][0] + " " + \
               InputTableSchema1[value][1] + ";"
        cur.execute(temp)

    for value in range(len(InputTableSchema2)):
        temp = "ALTER TABLE " + OutputTable + " ADD COLUMN " + InputTableSchema2[value][0] + " " + \
               InputTableSchema2[value][1] + ";"
        cur.execute(temp)

    for i in range(numberOfThreads):
        partTable = "parttable1_" + str(i)
        if i == 0:
            minvalue = minval
            maxvalue = minvalue + interval
            temp = "CREATE TABLE " + partTable + " AS SELECT * FROM " + InputTable1 + " WHERE " + Table1JoinColumn + " >= " + str(
                minvalue) + " AND " + Table1JoinColumn + " <= " + str(maxvalue) + ";"
        else:
            minvalue = maxvalue
            maxvalue = minvalue + interval
            temp = "CREATE TABLE " + partTable + " AS SELECT * FROM " + InputTable1 + " WHERE " + Table1JoinColumn + " > " + str(
                minvalue) + " AND " + Table1JoinColumn + " <= " + str(maxvalue) + ";"
        cur.execute(temp)

    for i in range(numberOfThreads):
        partTable = "parttable2_" + str(i)
        if i == 0:
            minvalue = minval
            maxvalue = minvalue + interval
            temp = "CREATE TABLE " + partTable + " AS SELECT * FROM " + InputTable2 + " WHERE " + Table2JoinColumn + " >= " + str(
                minvalue) + " AND " + Table2JoinColumn + " <= " + str(maxvalue) + ";"
        else:
            minvalue = maxvalue
            maxvalue = minvalue + interval
            temp = "CREATE TABLE " + partTable + " AS SELECT * FROM " + InputTable2 + " WHERE " + Table2JoinColumn + " > " + str(
                minvalue) + " AND " + Table2JoinColumn + " <= " + str(maxvalue) + ";"
        cur.execute(temp)

    #create output partition tables to store data by joining input partition tables
    for i in range(numberOfThreads):
        OutputTableRange = "outparttable_" + str(i)
        temp = "CREATE TABLE " + OutputTableRange + " (" + InputTableSchema1[0][0] + " " + InputTableSchema1[0][1] + ");"
        cur.execute(temp)

        for value in range(1, len(InputTableSchema1)):
            temp = "ALTER TABLE " + OutputTableRange + " ADD COLUMN " + InputTableSchema1[value][0] + " " + \
                   InputTableSchema1[value][1] + ";"
            cur.execute(temp)

        for value in range(len(InputTableSchema2)):
            temp = "ALTER TABLE " + OutputTableRange + " ADD COLUMN " + InputTableSchema2[value][0] + " " + \
                   InputTableSchema2[value][1] + ";"
            cur.execute(temp)

    threads = [0]*numberOfThreads
    for i in range(numberOfThreads):
        threads[i] = threading.Thread(target=helperJoin, args=(Table1JoinColumn, Table2JoinColumn, openconnection, i))
        threads[i].start()

    for i in range(numberOfThreads):
        threads[i].join()

    #insert data into main output table from all the output partition tables
    for i in range(numberOfThreads):
        temp = "INSERT INTO " + OutputTable + " SELECT * FROM outparttable_" + str(i) + ";"
        cur.execute(temp)

    #drop all the partition tables
    for i in range(numberOfThreads):
        drop1 = "DROP TABLE IF EXISTS parttable1_" + str(i) + ";"
        drop2 = "DROP TABLE IF EXISTS parttable2_" + str(i) + ";"
        outdrop = "DROP TABLE IF EXISTS outparttable_" + str(i) + ";"
        cur.execute(drop1)
        cur.execute(drop2)
        cur.execute(outdrop)

    openconnection.commit()

def helperJoin(Table1JoinColumn, Table2JoinColumn, openconnection, i):
    cur = openconnection.cursor()

    #insert data into corresponding output partition table by joining two input partition tables
    temp = """INSERT INTO outparttable_""" + str(i) + """ SELECT * FROM parttable1_""" + str(
        i) + """ INNER JOIN parttable2_""" + str(i) + """ ON parttable1_""" + str(i) + """.""" + str(
        Table1JoinColumn).lower() + """ = parttable2_""" + str(i) + """.""" + str(Table2JoinColumn).lower() + """;"""
    cur.execute(temp)
    return

Parallel Sort and Parallel Join/Assignment3_Interface.py


import logging
import functools
import requests
import json
from cfg import config
import time

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger()

def interface_log(log_type):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            tmp = list(args)
            if kw:
                tmp.append(kw)
            try:
                r = func(*args, **kw)
                logger.info('%s,func:%s,args:%s' % (log_type, func.__name__, ','.join(str(x) for x in tmp)))
                return r
            except Exception as e:
                logger.error(e)
                logger.error('%s,func:%s,args:%s' % (log_type, func.__name__, ','.join(str(x) for x in tmp)))

        return wrapper

    return decorator

def get_match_tasks():
    match_tasks = []
    workers = config.workers
    while True:
        for worker in workers:
            ip, port = worker, 4040
            while True:
                uri = 'http://%s:%s/api/v1/applications' % (ip, port)
                try:
                    rsp = requests.get(uri)
                    # only one task would refer to one couple ip:port
                    rsp_content = json.loads(rsp.content)[0]
                    task_name = rsp_content.get('name')
                    if 'match_faces_in_aimDB' not in task_name:
                        continue
                    driver_id = rsp_content.get('id')
                    match_tasks.append(driver_id)
                except requests.exceptions.ConnectionError:
                    # if connect time out then means no any more task on this worker
                    break
                finally:
                    port += 1
        if match_tasks:
            break
        time.sleep(3)
    return match_tasks


from utils import *
import csv

correct_detected = 0
total_images = 0

with open('test.csv', 'r') as file:
    reader = csv.reader(file)
    next(reader)  # skip the header

    for row in reader:
        result = calculate_result(row[0])
        expected_result = row[1]
        if str(result) == str(expected_result):
          correct_detected = correct_detected + 1
        total_images = total_images + 1

accuracy = correct_detected / total_images
print("{:.2f}%".format(accuracy * 100))


"""
1. Create Socket
2. Bind the socket to a particular port number
3. Listen to clients
4. Accept the connect
5. Communicate with the connection
6. Close the active connection
4. Close the server
"""
import socket

# create an socket
client_socket = socket.socket()

client_socket.connect(("localhost", 2000))

client_socket.sendall("Hello World from client".encode())

data = client_socket.recv(1000)

print(data.decode())

client_socket.close()


import numpy as np
import matplotlib.pyplot as plt
import random
import networkx as nx

# Motif with separated social networks extracting from their own resource piles
# But resources are coupled
# Resource (2) is not being extracted

#Assume n,m same for both social networks
#total no. agents
n = 50
#number of links
#May change depending on how network is generated, links are added
#if an isolated node is made
m = 120

# Maximum amount of resource
R1max = 200
R2max = 200

#amount of resource available initial
R1 = 150
R2 = 150

# Social parameters

mu = 1.5 # degree of cheating
ec = 0.483/50. #level of effort (cooperators) #level of effort (defectors)
ed = mu*ec
w = 15 #cost of harvesting

# Resource parameters
# c inflow, d discharge, q catchability
c1, d1 = 50, 50
c2, d2 = 20, 50
q = 1

delta = 0.2 # Resource leakage

# Network

#state of node

#fraction of cooperators initial
# Use this to probabilistically assign
#Also assume
F1prob, F2prob = 0.7, 0.4

states = ['cooperator', 'defector']
prob1 = [F1prob, 1-F1prob]
prob2 = [F2prob, 1-F2prob]

G1 = nx.gnm_random_graph(n, m)
G2 = nx.gnm_random_graph(n, m)

# Need network to have no isolated nodes
# If there is an isolated node, find it and link it the next node
for k in range(n):
    if len([j for j in G1.neighbors(k)]) == 0:
        G1.add_edge(k,(k+1))
    else:
        pass

    if len([j for j in G2.neighbors(k)]) == 0:
        G2.add_edge(k,(k+1))
    else:
        pass

# Randomly assign cooperators and defectors
for k in range(n):
    G1.node[k]['state'] = random.choices(states, prob1)[0]
    G2.node[k]['state'] = random.choices(states, prob2)[0]

def coopNeighbors(G,k):
    # Count cooperating neighbours
    # Returns proportion of neighbours who cooperate
    neighbours = [j for j in G.neighbors(k)]
    coops = 0
    for j in neighbours:
        if G.node[j]['state'] == 'cooperator':
            coops += 1
        else:
            pass
    return coops/len(neighbours)

# Extraction function
def ext(f):
    E = n*(f*ec+(1-f)*ed)
    return E

# Ostracism function (Gompertz growth)
def gompertz(f):
    #parameters (from paper)
    h = 0.34
    t = -150
    g = -10
    gomp = h * np.exp(t * np.exp(g*f))
    return gomp

#Cobb-Douglas production function
def cobbdoug(E,R):
    gamma = 10
    a = 0.6
    b = 0.2
    product = gamma*(E**a)*(R**b)
    return product

def countCoops(G):
    count = 0
    for k in G.nodes():
        if G.node[k]['state'] == 'cooperator':
            count += 1
        else:
            pass
    return count/n

def utilNode(fc, R, k, G):
    # Calculate utility of given node in network
    # Depends on state of node
    E = ext(fc)

    if G.node[k]['state'] == 'cooperator':
        ui = ec*((cobbdoug(E,R)/E)-w)
    else:
        nc = coopNeighbors(G,k)
        ui = ed*((cobbdoug(E,R)/E)-w)-gompertz(nc)*(ed-ec)/ed

    return ui

# initial condition

t = 0
tEnd = 600 #end point
dt = 0.1 #time step
# Lists to store values to plot later
time = []
r1List = []
r2List = []
f1List = []
f2List = []
# Draw initial network

# Sort out colours
colours1 = []
colours2 = []

for k in range(n):
    if G1.node[k]['state'] == 'cooperator':
        colours1.append('b')
    else:
        colours1.append('r')

    if G2.node[k]['state'] == 'cooperator':
        colours2.append('b')
    else:
        colours2.append('r')

nx.draw_networkx(G1, pos=None, node_color=colours1, with_labels=True, node_size=150)
plt.title('Initial Network 1')
plt.show()

nx.draw_networkx(G2, pos=None, node_color=colours2, with_labels=True, node_size=150)
plt.title('Initial Network 2')

plt.show()

while t<tEnd:
    F1 = countCoops(G1)
    F2 = countCoops(G2)

    dR1 = (c1 - d1*(R1/R1max)**2 - q*ext(F1)*R1 + delta*(R2-R1))*dt
    dR2 = (c2 - d2*(R2/R2max)**2 - q*ext(F2)*R2 + delta*(R1-R2))*dt

    #Choose random node in each group to update
    for (G,F,R) in [(G1,F1,R1), (G2,F2,R2)]:
        updateNode = random.choice(range(n))
        compareNode = random.choice([k for k in  G.neighbors(updateNode)])

        # Calculate node utilities
        utilUpdate = utilNode(F, R, updateNode, G)
        utilCompare = utilNode(F, R, compareNode, G)

        delta = utilUpdate - utilCompare

        if delta<0:
            prob = np.abs(delta)/(np.abs(utilUpdate)+np.abs(utilCompare))
            states = [G.node[updateNode]['state'], G.node[compareNode]['state']]
            probs = [1-prob, prob]
            newState = random.choices(states, probs)[0]
            G.node[updateNode]['state'] = newState

    #update quantities
    R1 += dR1
    R2 += dR2
    t += dt

    #append lists
    time.append(t)
    r1List.append(R1)
    r2List.append(R2)
    f1List.append(F1)
    f2List.append(F2)

# Reset colours
colours1 = []
colours2 = []

for k in range(n):
    if G1.node[k]['state'] == 'cooperator':
        colours1.append('b')
    else:
        colours1.append('r')

    if G2.node[k]['state'] == 'cooperator':
        colours2.append('b')
    else:
        colours2.append('r')

# Plot
plt.plot(time, f1List, color='blue', label='Population 1')
plt.plot(time, f2List, color='red', label='Population 2')
plt.legend(loc='best')
plt.xlabel('Time')
plt.ylabel('Fraction of Cooperators')

plt.show()

plt.plot(time, r1List, color='lightgreen', label='Resource 1')
plt.plot(time, r2List, color='darkgreen', label='Resource 2')
plt.legend(loc='best')
plt.xlabel('Time')
plt.ylabel('Resource Stock')

plt.show()

nx.draw_networkx(G1, pos=None, node_color=colours1, with_labels=True, node_size=150)
plt.title('Final Network 1')
plt.show()

nx.draw_networkx(G2, pos=None, node_color=colours2, with_labels=True, node_size=150)
plt.title('Final Network 2')

plt.show()


#uses the ceil function from math
from math import ceil

#takes in inputs and pritns it back out
stars = int(input())
print("{}:".format(stars))

#for each possible stars in a row, from 2 to half the given amount
for i in range(2,ceil(stars/2)+1):
    #check to see if the row and the next row (i-1) are able to evenly
    #divide into the arrangement. This does this by checking if it evenly
    #does so with % = 0 or if its a multiple of the original row.
    if(stars % (2*i-1) == i or stars % (2*i-1)==0):
        print("{},{}".format(i,i-1))

    #does the same but with the rows being the same number
    if(stars % (2*i) == i or stars % (2*i)==0):
       print("{},{}".format(i,i))

Star Arrangements/Star Arrangements Kattis.py


from Crypto import Random
from Crypto.Math.Numbers import Integer

from Crypto.Util.py3compat import iter_range

COMPOSITE = 0
PROBABLY_PRIME = 1

def miller_rabin_test(candidate, iterations, randfunc=None):
    """Perform a Miller-Rabin primality test on an integer.

    The test is specified in Section C.3.1 of `FIPS PUB 186-4`__.

    :Parameters:
      candidate : integer
        The number to test for primality.
      iterations : integer
        The maximum number of iterations to perform before
        declaring a candidate a probable prime.
      randfunc : callable
        An RNG function where bases are taken from.

    :Returns:
      ``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.

    .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    """

    if not isinstance(candidate, Integer):
        candidate = Integer(candidate)

    if candidate in (1, 2, 3, 5):
        return PROBABLY_PRIME

    if candidate.is_even():
        return COMPOSITE

    one = Integer(1)
    minus_one = Integer(candidate - 1)

    if randfunc is None:
        randfunc = Random.new().read

    # Step 1 and 2
    m = Integer(minus_one)
    a = 0
    while m.is_even():
        m >>= 1
        a += 1

    # Skip step 3

    # Step 4
    for i in iter_range(iterations):

        # Step 4.1-2
        base = 1
        while base in (one, minus_one):
            base = Integer.random_range(min_inclusive=2,
                    max_inclusive=candidate - 2,
                    randfunc=randfunc)
            assert(2 <= base <= candidate - 2)

        # Step 4.3-4.4
        z = pow(base, m, candidate)
        if z in (one, minus_one):
            continue

        # Step 4.5
        for j in iter_range(1, a):
            z = pow(z, 2, candidate)
            if z == minus_one:
                break
            if z == one:
                return COMPOSITE
        else:
            return COMPOSITE

    # Step 5
    return PROBABLY_PRIME

def lucas_test(candidate):
    """Perform a Lucas primality test on an integer.

    The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.

    :Parameters:
      candidate : integer
        The number to test for primality.

    :Returns:
      ``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.

    .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    """

    if not isinstance(candidate, Integer):
        candidate = Integer(candidate)

    # Step 1
    if candidate in (1, 2, 3, 5):
        return PROBABLY_PRIME
    if candidate.is_even() or candidate.is_perfect_square():
        return COMPOSITE

    # Step 2
    def alternate():
        value = 5
        while True:
            yield value
            if value > 0:
                value += 2
            else:
                value -= 2
            value = -value

    for D in alternate():
        if candidate in (D, -D):
            continue
        js = Integer.jacobi_symbol(D, candidate)
        if js == 0:
            return COMPOSITE
        if js == -1:
            break
    # Found D. P=1 and Q=(1-D)/4 (note that Q is guaranteed to be an integer)

    # Step 3
    # This is \delta(n) = n - jacobi(D/n)
    K = candidate + 1
    # Step 4
    r = K.size_in_bits() - 1
    # Step 5
    # U_1=1 and V_1=P
    U_i = Integer(1)
    V_i = Integer(1)
    U_temp = Integer(0)
    V_temp = Integer(0)
    # Step 6
    for i in iter_range(r - 1, -1, -1):
        # Square
        # U_temp = U_i * V_i % candidate
        U_temp.set(U_i)
        U_temp *= V_i
        U_temp %= candidate
        # V_temp = (((V_i ** 2 + (U_i ** 2 * D)) * K) >> 1) % candidate
        V_temp.set(U_i)
        V_temp *= U_i
        V_temp *= D
        V_temp.multiply_accumulate(V_i, V_i)
        if V_temp.is_odd():
            V_temp += candidate
        V_temp >>= 1
        V_temp %= candidate
        # Multiply
        if K.get_bit(i):
            # U_i = (((U_temp + V_temp) * K) >> 1) % candidate
            U_i.set(U_temp)
            U_i += V_temp
            if U_i.is_odd():
                U_i += candidate
            U_i >>= 1
            U_i %= candidate
            # V_i = (((V_temp + U_temp * D) * K) >> 1) % candidate
            V_i.set(V_temp)
            V_i.multiply_accumulate(U_temp, D)
            if V_i.is_odd():
                V_i += candidate
            V_i >>= 1
            V_i %= candidate
        else:
            U_i.set(U_temp)
            V_i.set(V_temp)
    # Step 7
    if U_i == 0:
        return PROBABLY_PRIME
    return COMPOSITE

from Crypto.Util.number import sieve_base as _sieve_base_large
## The optimal number of small primes to use for the sieve
## is probably dependent on the platform and the candidate size
_sieve_base = set(_sieve_base_large[:100])

def test_probable_prime(candidate, randfunc=None):
    """Test if a number is prime.

    A number is qualified as prime if it passes a certain
    number of Miller-Rabin tests (dependent on the size
    of the number, but such that probability of a false
    positive is less than 10^-30) and a single Lucas test.

    For instance, a 1024-bit candidate will need to pass
    4 Miller-Rabin tests.

    :Parameters:
      candidate : integer
        The number to test for primality.
      randfunc : callable
        The routine to draw random bytes from to select Miller-Rabin bases.
    :Returns:
      ``PROBABLE_PRIME`` if the number if prime with very high probability.
      ``COMPOSITE`` if the number is a composite.
      For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
    """

    if randfunc is None:
        randfunc = Random.new().read

    if not isinstance(candidate, Integer):
        candidate = Integer(candidate)

    # First, check trial division by the smallest primes
    if int(candidate) in _sieve_base:
        return PROBABLY_PRIME
    try:
        map(candidate.fail_if_divisible_by, _sieve_base)
    except ValueError:
        return COMPOSITE

    # These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
    # with p(k, t) being the probability that a randomly chosen k-bit number
    # is composite but still survives t MR iterations.
    mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
                 (620, 7), (740, 6), (890, 5), (1200, 4),
                 (1700, 3), (3700, 2))

    bit_size = candidate.size_in_bits()
    try:
        mr_iterations = list(filter(lambda x: bit_size < x[0],
                                    mr_ranges))[0][1]
    except IndexError:
        mr_iterations = 1

    if miller_rabin_test(candidate, mr_iterations,
                         randfunc=randfunc) == COMPOSITE:
        return COMPOSITE
    if lucas_test(candidate) == COMPOSITE:
        return COMPOSITE
    return PROBABLY_PRIME

def generate_probable_prime(**kwargs):
    """Generate a random probable prime.

    The prime will not have any specific properties
    (e.g. it will not be a *strong* prime).

    Random numbers are evaluated for primality until one
    passes all tests, consisting of a certain number of
    Miller-Rabin tests with random bases followed by
    a single Lucas test.

    The number of Miller-Rabin iterations is chosen such that
    the probability that the output number is a non-prime is
    less than 1E-30 (roughly 2^{-100}).

    This approach is compliant to `FIPS PUB 186-4`__.

    :Keywords:
      exact_bits : integer
        The desired size in bits of the probable prime.
        It must be at least 160.
      randfunc : callable
        An RNG function where candidate primes are taken from.
      prime_filter : callable
        A function that takes an Integer as parameter and returns
        True if the number can be passed to further primality tests,
        False if it should be immediately discarded.

    :Return:
        A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).

    .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    """

    exact_bits = kwargs.pop("exact_bits", None)
    randfunc = kwargs.pop("randfunc", None)
    prime_filter = kwargs.pop("prime_filter", lambda x: True)
    if kwargs:
        raise ValueError("Unknown parameters: " + kwargs.keys())

    if exact_bits is None:
        raise ValueError("Missing exact_bits parameter")
    if exact_bits < 160:
        raise ValueError("Prime number is not big enough.")

    if randfunc is None:
        randfunc = Random.new().read

    result = COMPOSITE
    while result == COMPOSITE:
        candidate = Integer.random(exact_bits=exact_bits,
                                   randfunc=randfunc) | 1
        if not prime_filter(candidate):
            continue
        result = test_probable_prime(candidate, randfunc)
    return candidate

def generate_probable_safe_prime(**kwargs):
    """Generate a random, probable safe prime.

    Note this operation is much slower than generating a simple prime.

    :Keywords:
      exact_bits : integer
        The desired size in bits of the probable safe prime.
      randfunc : callable
        An RNG function where candidate primes are taken from.

    :Return:
        A probable safe prime in the range
        2^exact_bits > p > 2^(exact_bits-1).
    """

    exact_bits = kwargs.pop("exact_bits", None)
    randfunc = kwargs.pop("randfunc", None)
    if kwargs:
        raise ValueError("Unknown parameters: " + kwargs.keys())

    if randfunc is None:
        randfunc = Random.new().read

    result = COMPOSITE
    while result == COMPOSITE:
        q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc)
        candidate = q * 2 + 1
        if candidate.size_in_bits() != exact_bits:
            continue
        result = test_probable_prime(candidate, randfunc=randfunc)
    return candidate


import sys
sys.stdin = open('input.txt')

T = int(input())
for tc in range(1, T+1):
    n, m = list(map(int, input().split()))
    num = list(map(int, input().split()))

    maxi = 0
    mini = 10000 * m
    for i in range(n-m+1):
        temp = 0
        for j in range(m):
            temp += num[i+j]
        if temp < mini:
            mini = temp
        if temp > maxi:
            maxi = temp

    print(f'#{tc} {maxi-mini}')


from matplotlib import pyplot as plt
import math
import numpy as np

from sympy import symbols, Eq, solve

co=[0]*10

print("Root locus is drawn with help of OLTF, so give value of OLTF")
print("For ax^3+bx^2+cx^1+d, consider this is denomenator and give value of a,b,c,d" )

a1=int(input())
b1=int(input())
c1=int(input())
d1=int(input())

print("For ax^3+bx^2+cx^1+d, consider this is numerator and give value of a,b,c,d" )
a2=int(input())
b2=int(input())
c2=int(input())
d2=int(input())

X=list()
Y=list()
for k in range(0,10000,1):
    k1=k/100
    print(k1)
    x = symbols('x')

    sol = solve(a1*(x**3)+b1*(x**2)+c1*(x**1)+d1+k1*(a2*(x**3)+b2*(x**2)+c2*(x**1)+d2))
    for i in range(0,len(sol)):

        co[i]=complex(sol[i])

        X.append(co[i].real)
        Y.append(co[i].imag)

plt.plot(X,Y,'ro')
plt.show()


import subprocess
import os
path = '/home/inar/MC/MG5_aMC_v2_4_0/bin/DMjune7/Cards'
path2 = '/home/inar/Dropbox/CURRENT/NMSSM/scripts'

# subprocess.call("rm param_card.dat", shell=True)
# wr_data = open('param_card.dat', 'w+')

def rewrite_param_card(MV, MX):
	'''Modify param_card_default: put tags scanMV and scanMX'''
	subprocess.call('rm '+path+'/param_card.dat', shell=True)
	wr_data = open(path+'/param_card.dat', 'w+')
	def_data = open(path+'/param_card_default.dat', 'r')
	for line in def_data:
			if 'scanMV' in line:
				new_line = line.split()
				new_line[1] = "{:.6e}".format(MV)
				new_str='   '
				for w in new_line:
					new_str+=w+' '
				new_str+='\n'
				wr_data.write(new_str)
			elif 'scanMX' in line:
				new_line = line.split()
				new_line[1] = "{:.6e}".format(MX)
				new_str='   '
				for w in new_line:
					new_str+=w+' '
				new_str+='\n'
				wr_data.write(new_str)
			else: wr_data.write(line)
	wr_data.close()
	def_data.close()

par_data = open(path2+'/params.dat', 'r')

os.remove('/home/inar/Dropbox/CURRENT/NMSSM/scripts/param_card.dat')

par_data.close()


from typing import List

def find_max_consecutive_ones(nums: List[int]) -> int:
    count = max_count = 0

    for num in nums:

        if num == 1:

            # Increment the count of 1's by one.
            count += 1

        else:

            # Find the maximum till now.
            max_count = max(max_count, count)

            # Reset count of 1.
            count = 0

    return max(max_count, count)


import click

from services.service_mesh.src.oci_cli_service_mesh.service_mesh_troubleshoot.task_request import TaskRequest, \
    TaskRequestType, FileTaskRequest
from services.service_mesh.src.oci_cli_service_mesh.service_mesh_troubleshoot.tasks.task_worker import MeshTask
from services.service_mesh.src.oci_cli_service_mesh.service_mesh_troubleshoot.utils.bundle_helper import \
    BundleHelper
from services.service_mesh.src.oci_cli_service_mesh.service_mesh_troubleshoot.utils.summary import MeshData

class CsvTask(MeshTask):
    def __init__(self, k8s_context=None):
        super(CsvTask, self).__init__(TaskRequestType.CSV_PROCESSOR)
        self.k8s_context = k8s_context

    def do_work(self, task_request: TaskRequest, kube_command_helper):
        try:
            output_events, tasks = [], []
            data = task_request.get_task_data()
            operator_namespace = data['operator_namespace']
            mesh_id = data['mesh_id']

            csv = kube_command_helper.get_csv(operator_namespace)

            if mesh_id is None:
                relative_path = ""
            else:
                relative_path = MeshData(mesh_id=mesh_id).get_mesh_hierarchy()
            file_task_request = FileTaskRequest(TaskRequestType.FILE_PROCESSOR,
                                                [],
                                                relative_path,
                                                BundleHelper.get_csv_file_name(),
                                                csv)
            tasks.append(file_task_request)
            return tasks, output_events
        except Exception as error:
            click.echo('CsvTask Exception: {}'.format(error))


import random

def shuffle_edges(g):
    """
    This function lets you randomly permute the vertices in a graph. Given a Graph
    g, you can create a Graph g2 with a permuted vertex set by using:
    g2 = Graph(Edges = shuffle_edges(g))
    """
    vertices = [v for v in g.vertices()]
    random.shuffle(vertices)
    perm = dict(zip(g.vertices(), vertices))
    edges = list()
    for e in g.edges():
        edges.append((perm[g.source(e)], perm[g.target(e)]))
    return edges

def add_random_edges(g, num_edges):
    edge_set = set()
    while len(edge_set) < num_edges:
        p = (random.randint(0,g.num_vertices()-1), random.randint(0,g.num_vertices()-1))
        if p[0] == p[1]:
            continue
        edge_set.add(p)
    for x in edge_set:
        ignore = g.add_edge(*x)
    return g

def make_d_regular_graph(g, degree):
    sample_space = dict((v, degree) for v in g.vertices())
    done = False
    while not done:
        try:
            while sample_space:
                u,v = random.sample(sample_space.keys(), 2)
                g.add_edge(u, v)
                sample_space[u] -= 1
                sample_space[v] -= 1
                if sample_space[u] == 0:
                    del sample_space[u]
                if sample_space[v] == 0:
                    del sample_space[v]
        except:
            sample_space = dict((v, degree) for v in g.vertices())
            g.clear_edges()
        else:
            done = True
    return g


from __future__ import print_function

import time
from sr.robot import *

R = Robot()

# Robot constants
R.a_th = 2.0
R.d_th = 0.4
R.tokens_set = []
R.currently_held = -1
R.drive_speed = 100
R.turn_speed = 10
R.turn_interval = 0.1
R.drive_interval = 0.1
R.search_speed = 50
R.search_interval = 0.1
# This is not the best solution but is better than having a
# global variable before the functions that use this parameter
R.print_once_speed = True
R.print_once_anchor_warn = True

# Color constants
# pure debugging
DEBUG = "[\033[90mDEBUG\033[39m] - "
# general information
INFO = "[\033[96mINFO\033[39m] - "
# warning
WARN = "[\033[93mWARN\033[39m] - "
# relevant success
SUCC = "[\033[92mSUCC\033[39m] - "
# task completed successfully
COMP = "[\033[95mCOMP\033[39m] - "

# set this to True to print distance and rotations
DEBUG_INFO = False

def drive(speed, seconds):
    """
    Function for setting a linear velocity

    Args: speed (int): the speed of the wheels
          seconds (int): the time interval
    """
    R.motors[0].m0.power = speed
    R.motors[0].m1.power = speed
    time.sleep(seconds)
    R.motors[0].m0.power = 0
    R.motors[0].m1.power = 0

def turn(speed, seconds):
    """
    Function for setting an angular velocity

    Args: speed (int): the speed of the wheels
          seconds (int): the time interval
    """
    R.motors[0].m0.power = speed
    R.motors[0].m1.power = -speed
    time.sleep(seconds)
    R.motors[0].m0.power = 0
    R.motors[0].m1.power = 0

def set_anchor():
    """
    Function to set the anchor

    Returns:
      - anchor (int): the numeric code of the marker
    """
    dist = 100
    while True:
        for token in R.see():
            if token.dist < dist:
                dist = token.dist
                anchor = token.info.code
        if dist == 100:
            turn(R.turn_speed, R.turn_interval)
        else:
            print(SUCC+"Anchor set")
            return anchor

def speed_regulator(dist):
    """
    Function to reduce speed when near the targets

    Args:
      - dist (float): distance between the robot and the
                      target

    Returns:
      - an appropriate drive speed (float)
    """
    if dist < 1:
        if R.print_once_speed:
            R.print_once_speed = False
            print(INFO+"Moderating speed for beeing near to target")
        return R.drive_speed/2
    else:
        R.print_once_speed = True
        return R.drive_speed

def retrieve_stack_pos(object_seen):
    """
    Function that allows the turtle to position the token
    next to the anchor if the anchor becomes no more visible

    Args:
      - object_seen (int): id of the object to collect
    Returns:
      - rot_y (float): relative rotation between robot and
                       token in polar coordinates
      - dist (float): distance between robot and token
    """
    if object_seen == R.anchor:
        # try if is not obstructed by other objects
        for token in R.see():
            if token.info.code == R.anchor:
                R.print_once_anchor_warn = True
                return (token.rot_y, token.dist)

        """
        if we arrive here the anchor cannot be found
        meaning it's hidden behind other tokens
        The best way to address the issue is to go towards
        a token that is already set
        """
        if R.print_once_anchor_warn:
            print(WARN+"The anchor could not be found "
                  "because hidden by other tokens")
            print(WARN+"Proceding towards one token already set")
            R.print_once_anchor_warn = False

        for token in R.see():
            if token.info.code in R.tokens_set:
                return (token.rot_y, token.dist)
    else:
        for token in R.see():
            if token.info.code == object_seen:
                return (token.rot_y, token.dist)

def move_robot_to(target):
    """
    Function that enables the turtle to go towards it's target.
    The target can be both the anchor or a token

    Args:
      - target (int): the id of the token
    """
    done = False
    while not done:
        (rot, dist) = retrieve_stack_pos(target)
        if DEBUG_INFO:
            print(DEBUG+"Dist: ", round(dist, 2), "\tRot: ", round(rot, 2))
        """
        Setting the rotation of the robot with an higher
        priority in respect to the starting to drive towards
        the target. In testing this seemed to have better
        results
        """
        if rot > R.a_th:
            turn(R.turn_speed, R.turn_interval)
        elif rot < -R.a_th:
            turn(-R.turn_speed, R.turn_interval)
        elif dist >= R.d_th:
            drive(speed_regulator(dist), R.drive_interval)

        """
        If the target of this function is the anchor then
        more distance is taken in consideration in the
        threshold for reaching the anchor because there is
        also the token attached to the grabber
        """
        if target == R.anchor:
            d_aux = R.d_th + 0.3
        else:
            d_aux = R.d_th

        """
        If the robot is alligned and close to the target
        then it's time to perform the required action
        """
        if rot < R.a_th and dist < d_aux:
            if target == R.anchor:
                print(SUCC+"Token carried successfully, releasing it")
                R.release()
                # Adds to the tokens positioned successfully
                # the last held token id
                R.tokens_set.append(R.currently_held)
                # Having released the token now the gripper is empty
                R.currently_held = -1
                done = True
                break
            else:
                print(SUCC+"Token reached successfully, grabbing it")
                R.grab()
                # Set currently held token id
                R.currently_held = target
                done = True
                break

def search_new_token():
    """
    Function to search a new token to take to the stack
    """
    print(INFO+"Searching for new token to take...")
    while 1:
        # Turning in the spot untill a token appears
        turn(R.search_speed, R.search_interval)
        for token in R.see():
            code = token.info.code
            # If the token is not already positioned then
            # it's time to go grab it
            if code not in R.tokens_set and code != R.anchor:
                print(SUCC+"Found new token!")
                move_robot_to(code)
                return

def search_anchor():
    """
    Function to search for the anchor
    """
    print(INFO+"Searching for the anchor...")
    while 1:
        # Turning in the spot untill the anchor appears
        turn(R.search_speed, R.search_interval)
        for token in R.see():
            if token.info.code == R.anchor:
                print(SUCC+"Found the anchor!")
                move_robot_to(R.anchor)
                return

def main():
    # setting the new anchor
    R.anchor = set_anchor()
    while 1:
        search_new_token()
        search_anchor()
        print(INFO+"Backing up...")
        drive(-R.drive_speed, 0.5)
        """
        If the number of tokens that have been positioned next
        to the anchor is 5 then we have finished the task
        """
        if (len(R.tokens_set) == 5):
            print(COMP+"Task completed!")
            exit(0)

main()