import math
import matplotlib.pyplot as plt
import numpy
import pandas
import scipy

import numpy.linalg as linalg
import sklearn.cluster as cluster
import sklearn.neighbors as neighbors

Spiral = pandas.read_csv('C:\\Users\\Lipi\\Downloads\\MachineLearning\\Week4_LIPI\\jain.csv',
                         delimiter=',')

nObs = Spiral.shape[0]

plt.scatter(Spiral['x'], Spiral['y'], c = Spiral['group'])
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

trainData = Spiral[['x','y']]
kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(trainData)

print("Cluster Centroids = \n", kmeans.cluster_centers_)

Spiral['KMeanCluster'] = kmeans.labels_

for i in range(2):
    print("Cluster Label = ", i)
    print(Spiral.loc[Spiral['KMeanCluster'] == i])

plt.scatter(Spiral['x'], Spiral['y'], c = Spiral['KMeanCluster'])
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

# Fourteen nearest neighbors
kNNSpec = neighbors.NearestNeighbors(n_neighbors = 14, algorithm = 'brute', metric = 'euclidean')
nbrs = kNNSpec.fit(trainData)
d3, i3 = nbrs.kneighbors(trainData)

# Retrieve the distances among the observations
distObject = neighbors.DistanceMetric.get_metric('euclidean')
distances = distObject.pairwise(trainData)

# Create the Adjacency matrix
Adjacency = numpy.zeros((nObs, nObs))
for i in range(nObs):
    for j in i3[i]:
        Adjacency[i,j] = math.exp(- (distances[i][j])**2 )

# Make the Adjacency matrix symmetric
Adjacency = 0.5 * (Adjacency + Adjacency.transpose())

# Create the Degree matrix
Degree = numpy.zeros((nObs, nObs))
for i in range(nObs):
    sum = 0
    for j in range(nObs):
        sum += Adjacency[i,j]
    Degree[i,i] = sum

# Create the Laplacian matrix
Lmatrix = Degree - Adjacency

# Obtain the eigenvalues and the eigenvectors of the Laplacian matrix
evals, evecs = linalg.eigh(Lmatrix)

# Series plot of the smallest five eigenvalues to determine the number of clusters
sequence = numpy.arange(1,5,1)
plt.plot(sequence, evals[0:4,], marker = "o")
plt.xlabel('Sequence')
plt.ylabel('Eigenvalue')
plt.xticks(sequence)
plt.grid("both")
plt.show()

# Series plot of the smallest twenty eigenvalues to determine the number of neighbors
sequence = numpy.arange(1,21,1)
plt.plot(sequence, evals[0:20,], marker = "o")
plt.xlabel('Sequence')
plt.ylabel('Eigenvalue')
plt.grid("both")
plt.xticks(sequence)
plt.show()

# Inspect the values of the selected eigenvectors
for j in range(10):
    print('Eigenvalue: ', j)
    print('              Mean = ', numpy.mean(evecs[:,j]))
    print('Standard Deviation = ', numpy.std(evecs[:,j]))
    print('  Coeff. Variation = ', scipy.stats.variation(evecs[:,j]))

Z = evecs[:,[0,1]]

plt.scatter(1e10*Z[:,0], Z[:,1])
plt.xlabel('First Eigenvector')
plt.ylabel('Second Eigenvector')
plt.grid("both")
plt.show()

# Perform 2-cluster K-mean on the first two eigenvectors
kmeans_spectral = cluster.KMeans(n_clusters = 2, random_state = 0).fit(Z)
Spiral['SpectralCluster'] = kmeans_spectral.labels_

plt.scatter(Spiral['x'], Spiral['y'], c = Spiral['SpectralCluster'])
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

Old Materials/Lipi Shah/MachineLearning/Week4_LIPI/Week 4 Jain Spiral.py


from itertools import groupby
from collections import defaultdict

class Solution:
    def longestLine(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        if not M or len(M[0]) == 0:
            return 0

        groups = defaultdict(list)
        for r, row in enumerate(M):
            for c, val in enumerate(row):
                groups[0, r] += [val] # rows
                groups[1, c] += [val] # cols
                groups[2, r + c] += [val] # diagonal
                groups[3, r - c] += [val] # anti-diagonal

        return max(list(map(self.ones, groups.values())))

    def ones(self, line: [int]) -> int:
        lens = [len(list(v)) if k == 1 else 0 for k, v in groupby(line)]
        return max(lens)


import pygame
import random
import time

class Window:
    def __init__(self, win_width, win_height, win_caption):
        self.win_width = win_width
        self.win_height = win_height
        self.win_caption = win_caption
        self.window = pygame.display.set_mode((self.win_width, self.win_height))
        pygame.display.set_caption(self.win_caption)

    def fill(self):
        self.window.fill((0, 0, 0))

class Player:
    def __init__(self, colour_r, colour_g, colour_b, left_walk, right_walk, left_jump, right_jump, idle):
        self.colour_r = colour_r
        self.colour_g = colour_g
        self.colour_b = colour_b
        self.left = False
        self.right = False
        self.walk_count = 0
        self.left_walk = left_walk
        self.right_walk = right_walk
        self.left_jump = left_jump
        self.right_jump = right_jump
        self.idle = idle

    def draw(self, win_, x_rect, y_rect, char_jump):
        if self.walk_count + 1 >= 18:
            self.walk_count = 0
        if self.left is True and char_jump is False:
            win_.blit(self.left_walk[self.walk_count // 3], (x_rect, y_rect))
            self.walk_count += 1
        elif self.right is True and char_jump is False:
            win_.blit(self.right_walk[self.walk_count // 3], (x_rect, y_rect))
            self.walk_count += 1
        elif self.left is True and char_jump is True:
            win_.blit(self.left_jump, (x_rect, y_rect))
            self.walk_count += 1
        elif self.right is True and char_jump is True:
            win_.blit(self.right_jump, (x_rect, y_rect))
            self.walk_count += 1
        else:
            win_.blit(self.idle, (x_rect, y_rect))

class Platform:
    def __init__(self, colour_r, colour_g, colour_b, x_plat, y_plat, w_plat, h_plat):
        self.colour_r = colour_r
        self.colour_g = colour_g
        self.colour_b = colour_b
        self.x_plat = x_plat
        self.y_plat = y_plat
        self.w_plat = w_plat
        self.h_plat = h_plat

    def draw(self, win_plat):
        pygame.draw.rect(win_plat, (self.colour_r, self.colour_g, self.colour_b),
                         (self.x_plat, self.y_plat, self.w_plat, self.h_plat))

def create_platforms(no_of_platforms, window_height):
    platforms = []
    step_plat = round((window_height - 100) / no_of_platforms)
    poss_heights = []
    for poss in range(0, no_of_platforms):
        poss_heights.append(step_plat * poss)
    heights = poss_heights
    print(heights)
    for platform in range(no_of_platforms):
        if len(heights) > 1:
            height_plat = heights[random.randint(0, len(heights)-1)]
            heights.remove(height_plat)
        else:
            height_plat = heights[0]
        platforms.append(Platform(0, 255, 0, random.randint(100, win.win_width-100),
                                  height_plat, random.randint(50, 100), 10))
    return platforms

walkRight = [pygame.image.load('adventurer-run-00-1.3.png'),
             pygame.image.load('adventurer-run-01-1.3.png'),
             pygame.image.load('adventurer-run-02-1.3.png'),
             pygame.image.load('adventurer-run-03-1.3.png'),
             pygame.image.load('adventurer-run-04-1.3.png'),
             pygame.image.load('adventurer-run-05-1.3.png')]
walkLeft = [pygame.image.load('adventurer-run-00-1.3 - Left.png'),
            pygame.image.load('adventurer-run-01-1.3 - Left.png'),
            pygame.image.load('adventurer-run-02-1.3 - Left.png'),
            pygame.image.load('adventurer-run-03-1.3 - Left.png'),
            pygame.image.load('adventurer-run-04-1.3 - Left.png'),
            pygame.image.load('adventurer-run-05-1.3 - Left.png')]
char = pygame.image.load('adventurer-idle-03-1.3.png')
jump = [pygame.image.load('adventurer-smrslt-00-1.3.png'),
        pygame.image.load('adventurer-smrslt-00-1.3 - Left.png')]
bg = pygame.image.load('bg.png')

pygame.init()
x = 250
y = 400
width = 50
height = 37
velocity = 15
jump_count = 10
run = True
is_jump = False
is_crouch = False
crouch_count = 0
rect_y = y
y_plats = [500, 400, 300, 200, 100]
is_land = True
down = False
on_platform = False
clock = pygame.time.Clock()

win = Window(1000, 500, "Escape The Cave!")
player = Player(255, 0, 0, left_walk=walkLeft, right_walk=walkRight, left_jump=jump[1], right_jump=jump[0], idle=char)
main_platform = Platform(255, 0, 0, 0, rect_y + height, win.win_width, 10)
rand_plats = create_platforms(12, 500)
jumped = False
y_s = []
difficulty = 2
count = 500
c = 1
while run:
    clock.tick(27)
    y_s.append(y)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    y_in_game = y
    height_in_game = height
    keys = pygame.key.get_pressed()
    if not is_jump:
        is_land = True
        y_in_game = y
        if keys[pygame.K_LEFT]:
            x -= velocity
            player.left = True
            player.right = False
        elif keys[pygame.K_RIGHT]:
            x += velocity
            player.left = False
            player.right = True
        else:
            player.left = False
            player.right = False
        if keys[pygame.K_UP]:
            is_jump = True
            jumped = True
        if player.left is False and player.right is False:
            player.walk_count = 0
    elif is_jump is True:
        is_land = False
        if jump_count >= -10:
            neg = 1
            if jump_count < 0:
                neg = -1
            y -= (jump_count ** 2) * 0.5 * neg
            y_in_game = y
            on_platform = False
            jump_count -= 1
        else:
            down = False
            is_jump = False
            jump_count = 10
        if keys[pygame.K_LEFT]:
            x -= velocity
            player.left = True
            player.right = False
        elif keys[pygame.K_RIGHT]:
            x += velocity
            player.left = False
            player.right = True
    if len(y_s) >= 2:
        if on_platform is False and jumped is True:
            if y_s[-1] > y_s[-2]:
                down = True
    for random_platform in range(0, len(rand_plats)):
        plat_x = rand_plats[random_platform].x_plat
        plat_y = rand_plats[random_platform].y_plat
        plat_width = rand_plats[random_platform].w_plat
        list_of_plat_x = list(range(plat_x, (plat_x + plat_width)))
        for xes in range(len(list_of_plat_x)):
            if x + width / 2 == list_of_plat_x[xes] and plat_y - 65 < y <= plat_y - 10:
                if down is True:
                    # print(f"Platform X: {rand_plats[random_platform].x_plat} | Platform Y: "
                    #       f"{rand_plats[random_platform].y_plat} | Character X, Y: {x}, {y}")
                    y = plat_y
                    jump_count = -11
                    down = False
                    is_jump = False
                    on_platform = True
                    plat_idx = random_platform
    if on_platform is True:
        y = rand_plats[plat_idx].y_plat - height
        list_of_plat_x = list(range(rand_plats[plat_idx].x_plat,
                                    rand_plats[plat_idx].x_plat + rand_plats[plat_idx].w_plat))
        if x + width / 2 not in list_of_plat_x:
            jump_count = 0
            is_jump = False
            down = True
            on_platform = False
    if on_platform is False and jumped is True:
        if is_jump is False:
            y -= (2 ** 2) * 0.5 * -8
    win.window.blit(bg, (0, 0))
    y_in_game = y
    player.draw(win_=win.window, x_rect=x, y_rect=y_in_game, char_jump=is_jump)
    if jumped is False:
        main_platform.draw(win_plat=win.window)
    if c % count == 0:
        difficulty += 1
    for plat in range(len(rand_plats)):
        if rand_plats[plat].y_plat < win.win_height:
            rand_plats[plat].y_plat += difficulty
        else:
            rand_plats[plat].y_plat = 0
            rand_plats[plat].x_plat = random.randint(100, win.win_width-100)
            rand_plats[plat].w_plat = random.randint(50, 100)
        rand_plats[plat].draw(win.window)
    pygame.display.update()
    if x <= 0 or x >= win.win_width:
        run = False
    if y >= win.win_height - height:
        run = False
    c += 1
    if difficulty > 5:
        run = False
        print("You win!")
    print(f"Difficulty: {difficulty - 1}")
pygame.quit()


# uncompyle6 version 3.7.4
# Python bytecode 2.4 (62061)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.macosx-10.5-i386/egg/fileinfo/plugins/fileinfo_inv_plugin_stats.py
# Compiled at: 2008-06-17 03:23:49
"""A fileinfo plug-in for general file attributes.
"""
from fileinfo.investigator import BaseInvestigator

class StatInvestigator(BaseInvestigator):
    """A class for determining general attributes of files."""
    __module__ = __name__
    attrMap = {'counter': 'counter', 'lc': 'getLineCount', 'wc': 'getWordCount', 'md5': 'getMd5Hash'}
    totals = ('lc', 'wc')

    def __init__(self, path):
        self.path = path
        self.cnt = -1

    def activate(self):
        """Try activating self, setting 'active' variable."""
        self.active = True
        self.content = None
        return self.active

    def counter(self):
        """A counter generator."""
        self.cnt += 1
        return self.cnt

    def getLineCount(self):
        """Return the number of lines in a file."""
        if self.content is None:
            self.content = open(self.path).read()
        content = getattr(self, 'content', self.content)
        return content.count('\n') + int(len(content) > 0)

    def getWordCount(self):
        """Return the number of words in a file."""
        if self.content is None:
            self.content = open(self.path).read()
        content = getattr(self, 'content', self.content)
        return len(content.split())

    def getMd5Hash(self):
        """Return the MD5 hash value of an entire file."""
        import md5
        if self.content is None:
            self.content = open(self.path).read()
        content = getattr(self, 'content', self.content)
        m = md5.new()
        m.update(content)
        hash = m.hexdigest()
        return hash


# bit 全探索
# ２進数の桁が on / off 状態を表す
l = ['a', 'b', 'c']
n = len(l)
for i in range(2 ** n):
    bag = []
    for j in range(n):
        if i >> j & 1:  # 2進数表記の i の j 桁目が 1 のとき
            bag.append(l[j])
    print(bag)


from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST

from shop.models import *
from orders.models import Order
from .cart import Cart
from .forms import CartAddProductForm, GiftForm
from coupons.forms import CouponApplyForm
import requests

# Можно поменять редирект на карточку товара снова
@require_POST
def cart_add(request, flavour_id):
    cart = Cart(request)
    flavour = Flavour.published.get(id=flavour_id)
    form = CartAddProductForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(flavour=flavour,
                 quantity=cd['quantity'],
                 update_quantity=cd['update'])
    return redirect('cart:cart_detail')

@require_POST
def cart_offer_add(request, flavour_id):
    cart = Cart(request)
    flavour = Flavour.published.get(id=flavour_id)
    cart.add(flavour=flavour)
    return cart

def add_offer(request, offer_id):
    products = Offer.published.get(id=offer_id).products.all()
    for product in products:
        flavour_id = product.flavour_by_product()
        cart_offer_add(request, flavour_id)
    cart = Cart(request)
    return redirect('cart:cart_detail')

def cart_remove(request, flavour_id):
    cart = Cart(request)
    flavour = Flavour.published.get(id=flavour_id)
    cart.remove(flavour)
    return redirect('cart:cart_detail')

def cart_detail(request):
    categories = Category.published.all()
    suppliers = Supplier.published.all()
    objectives = Objective.published.all()
    products_rec = Product.published.filter(recommendation=True)
    offers = Offer.published.all()
    cart = Cart(request)
    try:
        orders = Order.published.filter(client=request.user, paid=False)
    except:
        orders = None
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={'quantity': item['quantity'],
                     'update': True})

    coupon_apply_form = CouponApplyForm()
    gift_form = GiftForm()
    list_of_gift = Product.published.filter(available=False)
    gift = None
    sum_for_gift = cart.get_total_price()
    balance = 2500 - sum_for_gift
    balance2 = 5000 - sum_for_gift
    if 2500 <= sum_for_gift <= 5000:
        gift = 2500
    elif sum_for_gift > 5000:
        gift = 5000
    # Проверяем находится ли подарок в корзине перебором
    gift_in_cart = False
    for item in cart:
        flavour = item['flavour']
        # Если недоступный товар в корзине, значит подарок уже добавили
        if flavour.product.available == False:
            gift_in_cart = True
    template = 'cart/detail.html'
    context = locals()
    return render(request, template, context)

@require_POST
def add_gift(request):
    cart = Cart(request)
    gift_form = GiftForm(request.POST)
    product = None
    if gift_form.is_valid():
        gift = gift_form.cleaned_data['gift']
        if gift == 'Батончик':
            product = Product.published.get(name='Батончик(подарок)')
        elif gift == 'Шейкер 3в1':
            product = Product.published.get(name='Шейкер(подарок)')
        elif gift == 'Печенье':
            product = Product.published.get(name='Печенье(подарок)')
        try:
            flavour = product.flavour_for_gift()
            cart.add(flavour=flavour, quantity=1)
        except:
            if gift == 'Батончик+печенье':
                products = Product.published.filter(name__in=('Батончик(подарок)', 'Печенье(подарок)'))
                for product in products:
                    flavour = product.flavour_for_gift()
                    cart.add(flavour=flavour, quantity=1)
    return redirect('cart:cart_detail')


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('searchapp', '0003_auto_20151129_1758'),
    ]

    operations = [
        migrations.CreateModel(
            name='OReferences',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=120, verbose_name=b'Other References')),
            ],
        ),
        migrations.AddField(
            model_name='paper',
            name='references',
            field=models.ManyToManyField(related_name='_paper_references_+', to='searchapp.Paper', blank=True),
        ),
        migrations.AddField(
            model_name='oreferences',
            name='paper',
            field=models.ForeignKey(to='searchapp.Paper'),
        ),
    ]


class Music():
    def __init__(self, wykonawca, tytuł, album, rok):
        self.wykonawca = wykonawca
        self.tytuł = tytuł
        self.album = album
        self.rok = rok
    def __str__(self):
        return f"Wykonawca: {self.wykonawca} \nUtwór: {self.tytuł} \nAlbum: {self.album} \nRok: {self.rok}\n"

print(Music("Dawid Podsiadło", "Nie ma fal", "Małomiasteczkowy", "2018"))
print(Music("Twenty One Pilots", "Trench", "Chlorine", "2018"))
print(Music("Twenty One PIlots", "Blurryface", "Ride", "2015"))


#!/usr/bin/env python3

import getpass
import multiprocessing
import os
import pwd
import socket

import psutil

from prompter import ansi
from prompter import colors
from prompter import config

USERDATA = pwd.getpwnam(getpass.getuser())
XTERM = 'TERM' in os.environ and os.environ['TERM'].casefold() == 'xterm'
HOSTNAME = socket.gethostname()
SUPER = USERDATA.pw_name in config.settings.user.super

USER = r'\u'
AT = '@'
HOST = r'\h'
COLON = ':'
PROMPT_SYMBOL = r'\$'
MEM_SEP = '/'
MEM_UNITS = 'MB'
SWAP_SEP = '/'
SWAP_UNITS = 'MB'
MEM_SYS_SEP = '\t'
SYS_SEP = ' '
PROCS_SEP = '/'
DIRNAME = ''.join([
    r'$(',
    '; '.join([
        r'EC=$?',
        r'DIRNAME=${PWD%/*}',
        r'if [[ $DIRNAME != "/" && $PWD != $HOME ]]',
        r'then echo ${DIRNAME/$HOME/"~"}',
        r'else echo ""',
        r'fi',
        r'exit $EC',
    ]),
    r')'
])
BASENAME = ''.join([
    r'$(',
    '; '.join([
        r'EC=$?',
        r'if [[ $PWD == $HOME || $PWD == "/" ]]',
        r'then echo "\W"',
        r'else echo "/\W"',
        r'fi',
        r'exit $EC',
    ]),
    r')'
])
TEST_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        r'if [[ $EC -eq 0 ]]',
        'then echo "{color_good}"',
        'else echo "{color_bad}"',
        r'fi',
        r'exit $EC',
    ]),
    ')',
])

MEM_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''MEM_FREE=$(free -k | grep '^Mem:' | awk '{print_line}')''',
        '{color_range}',
        r'exit $EC',
    ]),
    ')',
])
MEM_FREE = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''echo "$(free -m | grep '^Mem:' | awk '{print $4}')"''',
        r'exit $EC',
    ]),
    ')',
])
MEM_TOTAL = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''echo "$(free -m | grep '^Mem:' | awk '{print $2}')"''',
        r'exit $EC',
    ]),
    ')',
])

SWAP_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''SWAP_FREE=$(free -k | grep '^Swap:' | awk '{print_line}')''',
        '{color_range}',
        r'exit $EC',
    ]),
    ')',
])
SWAP_FREE = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''echo "$(free -m | grep '^Swap:' | awk '{print $4}')"''',
        r'exit $EC',
    ]),
    ')',
])
SWAP_TOTAL = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        '''echo "$(free -m | grep '^Swap:' | awk '{print $2}')"''',
        r'exit $EC',
    ]),
    ')',
])

LOAD_1M_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'LOADAVG_1=$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 1"]),
            ')',
        ]),
        '{color_range}',
        r'exit $EC',
    ]),
    ')',
])
LOAD_1M = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 1"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])
LOAD_5M_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'LOADAVG_5=$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 2"]),
            ')',
        ]),
        '{color_range}',
        r'exit $EC',
    ]),
    ')',
])
LOAD_5M = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 2"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])
LOAD_15M_FORMAT = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'LOADAVG_15=$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 3"]),
            ')',
        ]),
        '{color_range}',
        r'exit $EC',
    ]),
    ')',
])
LOAD_15M = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 3"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])
CUR_PROCS = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg',
                "cut -d ' ' -f 4", "cut -d '/' -f 1"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])
TTL_PROCS = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg',
                "cut -d ' ' -f 4", "cut -d '/' -f 2"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])
LAST_PID = ''.join([
    '$(',
    '; '.join([
        r'EC=$?',
        ''.join([
            'echo "$(',
            ' | '.join(['cat /proc/loadavg', "cut -d ' ' -f 5"]),
            ')"',
        ]),
        r'exit $EC',
    ]),
    ')',
])

def get_fore_color(color):
    if XTERM:
        seq = ansi.seq.ColorText
    else:
        seq = ansi.seq.AnsiColorText

    return seq(color)

def get_back_color(color):
    if XTERM:
        seq = ansi.seq.ColorBack
    else:
        seq = ansi.seq.AnsiColorBack

    return seq(color)

def get_color(fore=None, back=None):
    items = []

    if fore is not None:
        items.append(get_fore_color(fore))

    if back is not None:
        items.append(get_back_color(back))

    if items:
        return sum(items)
    else:
        return ''

def get_color_from_config(value):
    if isinstance(value, config.Base):  # Is a defined color.
        if 'cube6' in value:
            return colors.from_cube6(**value.cube6)
        elif 'cube5' in value:
            return colors.from_cube5(**value.cube5)
        elif 'cube6_xterm' in value:
            return colors.from_cube6_xterm(**value.cube6_xterm)
        elif 'ansi' in value:
            return colors.from_ansi(**value.ansi)
        elif 'xterm' in value:
            return colors.from_xterm(value.xterm)
        elif 'rgb' in value:
            return colors.from_rgb(**value.rgb)
        elif 'hsv' in value:
            return colors.from_hsv(**value.hsv)
        elif 'hsl' in value:
            return colors.from_hsl(**value.hsl)
        elif 'grayscale' in value:
            return colors.from_grayscale(value.grayscale)
        else:
            return colors.Black

    else:  # Specifies a named color
        return colors[value]

def gen_pct_range_gradient(range):
    ttl_keys = sorted(list(range.keys()))
    key_range = zip(ttl_keys[:-1], ttl_keys[1:])

    last_high = 0

    used = set()

    first = True

    for low, high in key_range:
        low_color = range[low]
        high_color = range[high]
        if not isinstance(range[low], int) or not isinstance(range[high], int):
            low_color = get_color_from_config(low_color)
            high_color = get_color_from_config(high_color)

            if XTERM:
                color_gradient = list(
                    low_color.cube6_xterm.gen_hsv_gradient(high_color)
                )
            else:
                color_gradient = list(
                    low_color.ansi.gen_hsv_gradient(high_color)
                )

        else:
            low_color = colors.from_grayscale(low_color)
            high_color = colors.from_grayscale(high_color)

            if XTERM:
                color_gradient = list(
                    low_color.xterm.gen_grayscale_gradient(high_color)
                )
            else:
                color_gradient = list(
                    low_color.ansi.gen_grayscale_gradient(high_color)
                )

        if not first:
            color_gradient = color_gradient[1:]

        last_pct = 0

        for ndx, color in enumerate(color_gradient):
            pct = last_high + (
                (ndx + (0 if first else 1)) * (
                    (high - low) / (len(color_gradient) - (1 if first else 0))
                ) / 100
            )

            if hasattr(color, 'rgb'):
                color = color.rgb

            if pct not in used:
                last_pct = pct
                used.add(pct)

                yield pct, color

        last_high = last_pct

        first = False

def gen_mem_range_gradient():
    yield from (
        (
            int((psutil.virtual_memory().total / 1024) * pct + 0.5),
            color
        )
        for pct, color in gen_pct_range_gradient(config.settings.memory.range)
    )

def get_mem_free_color_range():
    return '; '.join([
        '; el'.join(
            '; '.join([
                'if [[ $MEM_FREE -ge {threshold} ]]',
                'then echo "{color}"'
            ]).format(
                threshold=threshold,
                color=get_fore_color(color)
            )
            for threshold, color in reversed(list(gen_mem_range_gradient()))
        ),
        'fi'
    ])

def gen_swap_range_gradient():
    yield from (
        (
            int((psutil.swap_memory().total / 1024) * pct + 0.5),
            color
        )
        for pct, color in gen_pct_range_gradient(config.settings.swap.range)
    )

def get_swap_free_color_range():
    return '; '.join([
        '; el'.join(
            '; '.join([
                'if [[ $SWAP_FREE -ge {threshold} ]]',
                'then echo "{color}"'
            ]).format(
                threshold=threshold,
                color=get_fore_color(color)
            )
            for threshold, color in reversed(list(gen_swap_range_gradient()))
        ),
        'fi'
    ])

def gen_load_range_gradient(name):
    yield from (
        (multiprocessing.cpu_count() * (1.0 - pct), color)
        for pct, color in gen_pct_range_gradient(
            config.settings.sys.load[name].back
        )
    )

def get_load_avg_color_range(mins):
    name = 'avg_{mins}m'.format(mins=mins)
    return '; '.join([
        '; el'.join(
            '; '.join([
                ' '.join([
                    'if',
                    '[[',
                    ''.join([
                        '$(',
                        ' | '.join(['echo "$LOADAVG_{mins}>={threshold}"',
                            'bc -l']),
                        ')'
                    ]),
                    '==',
                    '1',
                    ']]'
                ]),
                'then echo "{back_color}"'
            ]).format(
                mins=mins,
                threshold=threshold,
                back_color=get_back_color(color)
            )
            for threshold, color in gen_load_range_gradient(name)
        ),
        'fi'
    ])

class Prompt(config.Base):
    def __init__(self):
        self.bad_names |= {
            'color_wrap',
            'non_printing',
            'wrap',
        }

        self.register_attr(
            'usercolor',
            lambda: (
                get_color_from_config(
                    config.settings.user.super[USERDATA.pw_name]
                )
                if SUPER
                else get_color_from_config(
                    config.settings.user.normal[USERDATA.pw_name]
                )
            ),
            'The color to use for the current user'
        )

        self.register_attr(
            'at_color',
            lambda: get_color_from_config(config.settings.at_symbol),
            'The color to use for the at symbol'
        )

        self.register_attr(
            'hostcolor',
            lambda: (
                get_color_from_config(
                    config.settings.server[HOSTNAME].super
                )
                if SUPER
                else get_color_from_config(
                    config.settings.server[HOSTNAME].normal
                )
            ),
            'The color to use for the hostname'
        )

        self.register_attr(
            'colon_color',
            lambda: get_color_from_config(config.settings.colon),
            'The color to use for the colon symbol'
        )

        self.register_attr(
            'dirname_color',
            lambda: get_color_from_config(config.settings.dirname),
            'The color to use for the current dirname'
        )

        self.register_attr(
            'basename_color',
            lambda: get_color_from_config(config.settings.basename),
            'The color to use for the current basename'
        )

        self.register_attr(
            'good_fore_color',
            lambda: get_color_from_config(config.settings.test.good.fore),
            'The text color to use when the previous command succeeded.'
        )

        self.register_attr(
            'good_back_color',
            lambda: get_color_from_config(config.settings.test.good.back),
            'The back color to use when the previous command succeeded.'
        )

        self.register_attr(
            'bad_fore_color',
            lambda: get_color_from_config(config.settings.test.bad.fore),
            'The text color to use when the previous command failed.'
        )

        self.register_attr(
            'bad_back_color',
            lambda: get_color_from_config(config.settings.test.bad.back),
            'The back color to use when the previous command failed.'
        )

        self.register_attr(
            'test_good',
            lambda: get_color(self.good_fore_color, self.good_back_color),
            ' '.join([
                'The complete color configuration for when',
                'the previous command succeeded'
            ])
        )

        self.register_attr(
            'test_bad',
            lambda: get_color(self.bad_fore_color, self.bad_back_color),
            ' '.join([
                'The complete color configuration for when',
                'the previous command failed'
            ])
        )

        self.register_attr(
            'test_color',
            lambda: TEST_FORMAT.format(
                color_good=self.test_good,
                color_bad=self.test_bad
            ),
            'Returns the complete color setting for previous command test'
        )

        self.register_attr(
            'test',
            lambda: ''.join([
                self.wrap(
                    PROMPT_SYMBOL,
                    self.test_color
                ),
                ' '
            ])
        )

        self.register_attr(
            'reset_colors',
            lambda: (
                ansi.seq.ResetColorText()
                + ansi.seq.ResetColorBack()
                + ansi.seq.Reset()
            )
        )

        self.register_attr(
            'user_host',
            lambda: (
                self.color_wrap(
                    ''.join([USER, AT, HOST]),
                    self.usercolor,
                    self.hostcolor
                )
                if SUPER
                else ''.join([
                    self.color_wrap(USER, self.usercolor),
                    self.color_wrap(AT, self.at_color),
                    self.color_wrap(HOST, self.hostcolor),
                ])
            ),
            'Gets the username@hostname component for the prompt.'
        )

        self.register_attr(
            'colon',
            lambda: self.wrap(
                COLON,
                ansi.seq.Bold() + get_color(self.colon_color)
            ),
            'Gets the colon component for the prompt.'
        )

        self.register_attr(
            'full_path',
            lambda: ''.join([
                self.color_wrap(DIRNAME, self.dirname_color),
                self.wrap(
                    BASENAME,
                    ansi.seq.Bold() + get_color(self.basename_color)
                ),
            ])
        )

        self.register_attr(
            'user_host_path',
            lambda: ''.join([
                self.user_host,
                self.colon,
                self.full_path,
            ]),
            'Gets the username@hostname:/path component for the prompt.'
        )

        self.register_attr(
            'mem_free',
            lambda: self.wrap(
                MEM_FREE,
                MEM_FORMAT.format(
                    print_line='{print $4}',
                    color_range=get_mem_free_color_range()
                )
            ),
            'Gets the memory free component for the prompt.'
        )

        self.register_attr(
            'mem_total',
            lambda: self.color_wrap(
                MEM_TOTAL,
                get_color_from_config(config.settings.memory.total)
            ),
            'Gets the memory total component for the prompt.'
        )

        self.register_attr(
            'mem_sep',
            lambda: self.color_wrap(
                MEM_SEP,
                get_color_from_config(config.settings.memory.sep)
            ),
            'Gets the separator for memory components for the prompt.'
        )

        self.register_attr(
            'mem_units',
            lambda: self.color_wrap(
                MEM_UNITS,
                get_color_from_config(config.settings.memory.units)
            ),
            'Gets the units for memory components for the prompt.'
        )

        self.register_attr(
            'memory',
            lambda: ''.join([
                self.mem_free,
                self.mem_sep,
                self.mem_total,
                self.mem_units,
            ]),
            'Gets the memory free/total component for the prompt.'
        )

        self.register_attr(
            'swap_free',
            lambda: self.wrap(
                SWAP_FREE,
                SWAP_FORMAT.format(
                    print_line='{print $4}',
                    color_range=get_swap_free_color_range()
                )
            ),
            'Gets the swap free component for the prompt.'
        )

        self.register_attr(
            'swap_total',
            lambda: self.color_wrap(
                SWAP_TOTAL,
                get_color_from_config(config.settings.swap.total)
            ),
            'Gets the swap total component for the prompt.'
        )

        self.register_attr(
            'swap_sep',
            lambda: self.color_wrap(
                SWAP_SEP,
                get_color_from_config(config.settings.swap.sep)
            ),
            'Gets the separator for swap components for the prompt.'
        )

        self.register_attr(
            'swap_units',
            lambda: self.color_wrap(
                SWAP_UNITS,
                get_color_from_config(config.settings.swap.units)
            ),
            'Gets the units for swap components for the prompt.'
        )

        self.register_attr(
            'swap',
            lambda: ''.join([
                self.swap_free,
                self.swap_sep,
                self.swap_total,
                self.swap_units,
            ]),
            'Gets the swap free/total component for the prompt.'
        )

        self.register_attr(
            'mem_swap',
            lambda: ' '.join([
                self.memory,
                self.swap,
            ]),
            'Gets the combined memory & swap components for the prompt.'
        )

        self.register_attr(
            'load1',
            lambda: ' '.join([
                self.wrap(
                    ' ',
                    LOAD_1M_FORMAT.format(
                        color_range=get_load_avg_color_range(1)
                    )
                ),
                self.color_wrap(
                    LOAD_1M,
                    get_color_from_config(
                        config.settings.sys.load['avg_1m'].fore
                    )
                ),
            ]),
            'Gets the Avg Load 1m component for the prompt.'
        )

        self.register_attr(
            'load5',
            lambda: ' '.join([
                self.wrap(
                    ' ',
                    LOAD_5M_FORMAT.format(
                        color_range=get_load_avg_color_range(5)
                    )
                ),
                self.color_wrap(
                    LOAD_5M,
                    get_color_from_config(
                        config.settings.sys.load['avg_5m'].fore
                    )
                ),
            ]),
            'Gets the Avg Load 5m component for the prompt.'
        )

        self.register_attr(
            'load15',
            lambda: ' '.join([
                self.wrap(
                    ' ',
                    LOAD_15M_FORMAT.format(
                        color_range=get_load_avg_color_range(15)
                    )
                ),
                self.color_wrap(
                    LOAD_15M,
                    get_color_from_config(
                        config.settings.sys.load['avg_15m'].fore
                    )
                ),
            ]),
            'Gets the Avg Load 15m component for the prompt.'
        )

        self.register_attr(
            'load_avg',
            lambda: SYS_SEP.join([
                self.load1,
                self.load5,
                self.load15
            ]),
            'Gets the combined Avg Load component for the prompt.'
        )

        self.register_attr(
            'cur_procs',
            lambda: self.color_wrap(
                CUR_PROCS,
                get_color_from_config(config.settings.sys.procs.current)
            ),
            'Gets the current processes component for the prompt.'
        )

        self.register_attr(
            'ttl_procs',
            lambda: self.color_wrap(
                TTL_PROCS,
                get_color_from_config(config.settings.sys.procs.total)
            ),
            'Gets the total processes component for the prompt.'
        )

        self.register_attr(
            'sep_procs',
            lambda: self.color_wrap(
                PROCS_SEP,
                get_color_from_config(config.settings.sys.procs.sep)
            ),
            'Gets the separator for processes components for the prompt.'
        )

        self.register_attr(
            'procs',
            lambda: ''.join([
                self.cur_procs,
                self.sep_procs,
                self.ttl_procs
            ]),
            'Gets the combined processes component for the prompt.'
        )

        self.register_attr(
            'last_pid',
            lambda: self.color_wrap(
                LAST_PID,
                get_color_from_config(config.settings.sys.last_pid)
            ),
            'Gets the last PID component for the prompt.'
        )

        self.register_attr(
            'sys',
            lambda: SYS_SEP.join([
                self.load_avg,
                self.procs,
                self.last_pid,
            ]),
            'Gets the combined system information component for the prompt.'
        )

        self.register_attr(
            'mem_sys',
            lambda: MEM_SYS_SEP.join([
                self.mem_swap,
                self.sys
            ]),
            'Gets the memory & system information component for the prompt.'
        )

        self.register_attr(
            'prompt',
            lambda: '\n'.join([
                self.mem_sys,
                self.user_host_path,
                self.test
            ]).replace('\033', r'\e'),
            'Gets the complete prompt.'
        )

    def wrap(self, text, start, end=None):
        if end is None:
            end = self.reset_colors

        return ''.join([
            self.non_printing(start),
            text,
            self.non_printing(end)
        ])

    def color_wrap(self, text, fore=None, back=None):
        return self.wrap(text, get_color(fore=fore, back=back))

    @staticmethod
    def non_printing(sequence):
        return ''.join(['\\[', str(sequence), '\\]'])

    @classmethod
    def get_prompt(cls):
        prompt = cls()

        print(prompt.prompt)

if __name__ == '__main__':
    Prompt.get_prompt()


# -*- coding: utf-8 -*-
#!/usr/bin/python
import json
import time
from datetime import datetime, timedelta, date
import pytz
import sys
from random import randint
from pathlib import Path

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

def is_date(date_text):
    try:
        datetime.strptime(date_text, '%Y/%m/%d')
    except ValueError:
        return False
    else:
        return True

# especificar fecha desde que se hara el recorrido
if len(sys.argv) > 1:
    new_date = sys.argv[1]
    if (is_date(new_date)):
        current_day = datetime.strptime(new_date, '%Y/%m/%d')
    else:
        current_day = date.today()
else:
    current_day = date.today()

current_day_m = current_day.month
current_day_d = current_day.day
c_d = str(current_day.month)+'_'+str(current_day_d)

utc_timezone = pytz.timezone("UTC")
naive_utc = datetime.strptime("1970-1-1", "%Y-%m-%d")
utc_date = utc_timezone.localize(naive_utc, is_dst=None)

with open('entry/sistema.json', encoding='utf-8') as file:
    data = json.load(file)

timestamp_init = int(time.time())

array_week_dates = [datetime.combine(
    current_day + timedelta(days=0), datetime.min.time())]

# definir fecha a X dias
for i in range(0, 8):
    array_week_dates.append(datetime.combine(
        current_day + timedelta(days=i+1), datetime.min.time()))

list_lugares = []

f = open('listaccept.txt', 'r')
f1 = f.readlines()
for x in f1:
    if(x):
        list_lugares.append(int(x))

shard_number = 0
total_shard = len(list_lugares)
nonce = int(random_with_N_digits(10))

#if 2 mean 1 persona
max_personas_mesa = 3
#tiempo_mesa in sec
tiempo_mesa = 900
tiempo_menos_final = int(tiempo_mesa/60)

for lugar in data:

    if lugar['id'] in list_lugares:

        jsonAvailibility = {
            "metadata": {
                "processing_instruction": "PROCESS_AS_COMPLETE",
                "shard_number": shard_number,
                "total_shards": total_shard,
                "nonce": int(nonce),
                "generation_timestamp": int(timestamp_init)
            }
        }

        shard_number += 1

        jsonAvailibilityServ = {}
        jsonAvailibilityServi = []
        jsonAvailibilityServA = []

        local_timezone = pytz.timezone(lugar['timezone'])

        for week_date in array_week_dates:

            for day in lugar['openingDays']:

                # if(week_date.strftime('%A').lower() == day['weekday'] and (day['weekday'] == 'wednesday' or day['weekday'] == 'thursday' or day['weekday'] == 'friday')):
                if(week_date.strftime('%A').lower() == day['weekday']):

                    if(day['start'] != 0 and day['end'] != 0):
                        if(day['start'] is not None and day['end'] is not None):

                            for minutes in range(day['start'], day['end'], (tiempo_menos_final)):
                                # dt = week_date + timedelta(seconds=minutes*60)
                                # timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

                                dt = week_date + timedelta(seconds=minutes*60)
                                local_dt = local_timezone.localize(
                                    dt, is_dst=None)
                                timestamp = (
                                    local_dt - utc_date).total_seconds()

                                # if(day['weekday'] == 'wednesday'):
                                #     print(day['weekday'])
                                #     print(dt)
                                #     print(local_dt)
                                #     print(timestamp)
                                #     print()

                                for party_size in range(1, max_personas_mesa):
                                    jsonAvailibilityServA.append({
                                        "duration_sec": tiempo_mesa,
                                        "start_sec": int(timestamp),
                                        "merchant_id": "merch"+str(lugar['id']),
                                        "service_id": str(lugar['id'])+"-dining",
                                        "spots_open": 10,
                                        "spots_total": 10,
                                        "resources": {
                                            "party_size": party_size
                                        },
                                        "confirmation_mode": "CONFIRMATION_MODE_ASYNCHRONOUS"
                                    })

                    if(day['start2'] != 0 and day['end2'] != 0):
                        if(day['start2'] is not None and day['end2'] is not None):

                            for minutes in range(day['start2'], day['end2'], (tiempo_menos_final)):
                                # dt = week_date + timedelta(seconds=minutes*60)
                                # timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

                                dt = week_date + timedelta(seconds=minutes*60)
                                local_dt = local_timezone.localize(
                                    dt, is_dst=None)
                                timestamp = (
                                    local_dt - utc_date).total_seconds()

                                # if(day['weekday'] == 'wednesday'):
                                #     print(day['weekday'])
                                #     print(dt)
                                #     print(local_dt)
                                #     print(timestamp)
                                #     print()

                                for party_size in range(1, max_personas_mesa):
                                    jsonAvailibilityServA.append({
                                        "duration_sec": tiempo_mesa,
                                        "start_sec": int(timestamp),
                                        "merchant_id": "merch"+str(lugar['id']),
                                        "service_id": str(lugar['id'])+"-dining",
                                        "spots_open": 10,
                                        "spots_total": 10,
                                        "resources": {
                                            "party_size": party_size
                                        },
                                        "confirmation_mode": "CONFIRMATION_MODE_ASYNCHRONOUS"
                                    })

        jsonAvailibilityServ['availability'] = jsonAvailibilityServA
        jsonAvailibilityServi.append(jsonAvailibilityServ)

        jsonAvailibility['service_availability'] = jsonAvailibilityServi

        Path('output/availibility'+c_d).mkdir(parents=True, exist_ok=True)
        with open('output/availibility'+c_d+'/availibility_'+c_d+'_'+str(lugar['id'])+'_'+str(shard_number)+'of'+str(total_shard)+'.json', 'w') as file:
            json.dump(jsonAvailibility, file)


import strax
import straxen
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from argparse import ArgumentParser
import argparse
import cutax
from cutax.cuts.krypton_selections import KrSingleS1S2
from cutax.cuts.krypton_selections import KrDoubleS1SingleS2
import sys
sys.path +=['../../../utils/']

import xomlib

def press_run(run_id):

#    st = cutax.contexts.xenonnt_offline(include_rucio_local=False,include_rucio_remote=True )
    st = cutax.xenonnt_online(_rucio_local_path='/project/lgrandi/rucio', include_rucio_local = True)
    st.storage +=[strax.DataDirectory('/project2/lgrandi/xenonnt/processed', provide_run_metadata=True)]
#    st = cutax.xenonnt_online(output_folder = "/home/gaior/codes/test/.", _rucio_local_path='/project/lgrandi/rucio', include_rucio_local = True)
    st.register([KrSingleS1S2,KrDoubleS1SingleS2])
#    st.storage += [strax.DataDirectory('/project2/lgrandi/xenonnt/processed', provide_run_metadata=True)]
    data_singleS1 = st.get_df(run_id, targets =("event_info_double", "cut_fiducial_volume", "cut_Kr_SingleS1S2"),
                   selection_str= ("cut_fiducial_volume",'cut_Kr_SingleS1S2'))
    data_doubleS1 = st.get_df(run_id, targets =("event_info_double", "cut_fiducial_volume", "cut_Kr_DoubleS1_SingleS2"),
                   selection_str= ("cut_fiducial_volume",'cut_Kr_DoubleS1_SingleS2'))

    ES1a = 32.2
    ES1b = 9.4

    #energie du pic
    ES1 = 41.6

    #Light Yield

    S1_a1 = data_doubleS1['s1_a_area'].values
    S1_b1 = data_doubleS1['s1_b_area'].values
    S1_a = data_singleS1['s1_a_area'].values

    #mean
    S1amoy = np.mean(S1_a1)
    S1bmoy = np.mean(S1_b1)
    S1_41 = np.mean(S1_a)

    #standard deviation
    S1asigma = np.std(S1_a1)
    S1bsigma = np.std(S1_b1)
    S1_41sigma = np.std(S1_a)

    #standard error of mean
    errorS1amoy = S1asigma/np.sqrt(len(S1_a1))
    errorS1bmoy = S1bsigma/np.sqrt(len(S1_b1))
    errorS1_41moy = S1_41sigma/np.sqrt(len(S1_a))

    #light yield
    LYS1a = S1amoy/ES1a
    LYS1b = S1bmoy/ES1b
    LYS1_41 = S1_41/ES1

    #light yield error
    DLyS1a = errorS1amoy/ES1a
    DLyS1b = errorS1bmoy/ES1b
    DLyS1_41 = errorS1_41moy/ES1

    #removing useless datas
    del data_doubleS1
    del data_singleS1
    del S1_a1
    del S1_b1
    del S1_a

    xomresult = xomlib.Xomresult(analysis_name="light_yield",
                                 analysis_version = "v0.0",
                                 variable_name='LYS1_41',
                                 variable_value=LYS1_41,
                                 runid=int(run_id),
                                 data= {"LYS1a":LYS1a, "DLYS1a":DLyS1a,
                                        "LYS1b":LYS1b, "DLYS1b":DLyS1b,
                                        "LYS1_41":LYS1_41, "DLYS1_41":DLyS1_41})
    xomresult.save()
    xomresult.xom_message(success=True)

    # results = []

    # results.append(run_id)
    # results.append(LYS1a)
    # results.append(DLyS1a)
    # results.append(LYS1b)
    # results.append(DLyS1b)
    # results.append(LYS1_41)
    # results.append(DLyS1_41)

    # np.save('/home/pellegriniq/tab22', results)

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("echo")
    args = parser.parse_args()
    print(args.echo)
    print("start")

    press_run(args.echo)
    print('end')

if __name__ == "__main__":
    main()


from django import forms
from django.contrib.auth.forms import AuthenticationForm

from .models import User

class LoginForm(AuthenticationForm):

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = field_name

class ProfileEditForm(forms.ModelForm):
    birthday = forms.DateField(
        widget=forms.DateInput(format="%m/%d/%Y",
                               attrs={'placeholder': 'MM/DD/YYYY', 'class': 'form-control date-input'}),
        required=False
    )

    class Meta:
        model = User
        fields = (
            'first_name', 'last_name',
            'handicap', 'birthday', 'location', 'years_of_experience', 'creation_time', 'photo',
        )

    def __init__(self, *args, **kwargs):
        super(ProfileEditForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

        self.fields['first_name'].required = self.fields['last_name'].required = True
        self.fields['birthday'].widget.attrs['class'] = 'form-control date-input'


import logging
from contextlib import contextmanager
import time
import functools
from typing import Callable, Any
import platform
import signal

class Log:
    """
    Class for logging info
    """
    def __init__(self, name: str, log_file_name: str, level: str ='DEBUG'):
        """
        :param name: name of the logger
        :type name: str

        :param log_file_name : name of the log file
        :type log_file_name :  str

        :param level : level of logger, must of one of ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        :type level : str
        """
        self.logger = logging.getLogger(name)
        self.level = level
        self.level_dict = {'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING,
                           'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL}
        self.set_log_level()
        self.format = logging.Formatter('[%(levelname)s | %(name)s] %(asctime)s >> %(message)s')
        self.file_handler = logging.FileHandler(log_file_name)
        self.file_handler.setFormatter(self.format)
        self.logger.addHandler(self.file_handler)

    def set_log_level(self) -> None:
        """
        set logger's log level, must of one of ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        """
        self.logger.setLevel(self.level_dict[self.level])

    def activate_stream(self) -> None:
        """
        activate StreamHandler
        """
        handler = logging.StreamHandler()
        handler.setFormatter(self.format)
        self.logger.addHandler(handler)

    def debug(self, message: str) -> None:
        """
        :param message : send message to logger in DEBUG level
        :type message : str
        """
        self.logger.debug(message)

    def info(self, message: str) -> None:
        """
        :param message : send message to logger in INFO level
        :type message : str
        """
        self.logger.info(message)

    def write(self, message: str) -> None:
        """
        made for memory_profiler.profile's output stream
        :param message : send message to logger in INFO
        :type message : str
        """
        self.logger.info(message)

    def warning(self, message: str) -> None:
        """
        :param message : send message to logger in WARNING level
        :type message : str
        """
        self.logger.warning(message)

    def critical(self, message: str) -> None:
        """
        :param message : send message to logger in CRITICAL level
        :type message : str
        """
        self.logger.critical(message)

    def error(self, message: str) -> None:
        """
        :param message : send message to logger in ERROR level
        :type message : str
        """
        self.logger.error(message)

    def flush(self) -> None:
        """
        flush handlers in logger
        """
        for handler in self.logger.handlers:
            handler.flush()

    def set_format(self, ex_format: str) -> None:
        """
        Resets format of handlers
        ex) '[%(levelname)s | %(name)s] %(asctime)s >> %(message)s'

        :param ex_format : new_format
        :type ex_format : str
        """
        self.format = logging.Formatter(ex_format)
        for handler in self.logger.handlers:
            handler.setFormatter(self.format)

class TimeoutException(Exception):
    """Custom made exception for time_out"""

class FunctionChecker:
    """
    class for measuring time and memory of function.
    Only consists of staticmethod
    Must not make instance of this class

    Memory check example:

    from memory_profiler import profile
    from utils.timer_log import Log
    test = Log('your_name', 'your_log.log')

    @profile(stream = test)
    def your_func():
        pass
    """
    def __init__(self):
        raise NotImplementedError

    @staticmethod
    @contextmanager
    def timer_context(name: str, time_type: str='milli_second', logger: Log=None) -> None:
        """
        Method for measuring time of function and script

        :param name : name of the function
        :type name : str

        :param time_type : type of the time, must be one of ['micro_second', 'milli_second', 'second']
        :type time_type : str

        :param logger : logger to log the elapsed time. If None, time is printed on the console
        :type logger

        :return time of function and script

        example :

        with FunctionChecker.timer_context('your_name'):
            your_function()
            your_script

        >> [your_name] : elapsed_time milli_second
        """
        time_dict = {'micro_second': 1E+06, 'milli_second': 1E+03, 'second': 1}
        start_time = time.time()
        yield
        end_time = time.time()
        elapsed_time = (end_time - start_time) * time_dict[time_type]
        if logger is None:
            print('[{}] : {} {}'.format(name, elapsed_time, time_type))
        else:
            logger.info('[{}] : {} {}'.format(name, elapsed_time, time_type))

    @staticmethod
    def timer_wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
        """
        Wrapper of function for time check

        example)
        @FunctionChecker.timer_wrapper
        def foo():
            your_script

        foo(your_logger, your_name):

        >> [foo] : time milli_second
        """
        @functools.wraps(func)
        def n_func(logger: Log=None, name: str=func.__name__, time_type: str='milli_second', *args, **kwargs):
            """
            :param logger: logger for logging. If None, log will be printed on the console
            :type logger: logger

            :param name: name of log, default: func.__name__
            :type name: str

            :param time_type: type of the time, must be one of ['micro_second', 'milli_second', 'second']
            :type time_type: str
            """
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            time_dict = {'micro_second': 1E+06, 'milli_second': 1E+03, 'second': 1}
            elapsed_time = (end_time - start_time) * time_dict[time_type]
            if logger is None:
                print('[{}] : {} {}'.format(name, elapsed_time, time_type))
            else:
                logger.info('[{}] : {} {}'.format(name, elapsed_time, time_type))
        return n_func

    @staticmethod
    def break_after_time(seconds: int, logger: Log=None) -> Callable[..., Any]:
        """
        Wrapper of function for terminating the function after input second

        :param seconds: After 'seconds' the function is terminated
        :type seconds: int

        :param logger: logger for handling time_check if None, log will be printed on the console
        :type logger: Log

        ex)
        @FunctionChecker.break_after_time(seconds = 10, None)
        def f(a,b,c):
            pass

        f(1,2,3)
        """
        def timeout_handler(sig_num, frame):
            raise TimeoutException

        def function(function_in):
            if platform.system() == 'Windows':
                if logger is None:
                    print('This function does not support current OS')
                else:

                    logger.warning('This function does not support current OS')
                raise OSError

            def wrapper(*args, **kwargs):
                signal.signal(signal.SIGALRM, timeout_handler)
                signal.alarm(seconds)
                try:
                    res = function_in(*args, **kwargs)
                    signal.alarm(0)
                    return res
                except TimeoutException:
                    if logger is None:
                            print(u'Timeout: %s sec reached.' % seconds, function_in.__name__, args, kwargs)
                    else:
                        logger.info(u'Timeout: %s sec reached. %s %s %s'
                                    % (seconds, function_in.__name__, args, kwargs))
                return
            return wrapper
        return function


from mxnet.gluon import Block, HybridBlock, SymbolBlock
from mxnet.symbol import Symbol, FullyConnected, Variable
import mxnet
from mxnet import symbol
from mxnet import nd
from mxnet import module
from mxnet import init
from mxnet import io
from mxnet.gluon import Block, HybridBlock, SymbolBlock, Trainer
from mxnet.gluon.nn import Sequential, Dense
from sockeye.training import TrainingModel
import numpy
from urllib.request import urlopen, Request
import json
import logging
from types import MethodType

def probe(model, host, port, every=1, select=lambda x : True):
    assert(isinstance(model, (Block, mxnet.module.BaseModule)))
    if isinstance(model, Block):
        def callback(op, ivars, ovar):
            r = Request("http://{}:{}".format(host, port), method="POST", data=json.dumps({"output" : ovar.asnumpy().tolist(),
                                                                                "inputs" : [ivar.asnumpy().tolist() for ivar in ivars],
                                                                                "type" : "LAYER",
                                                                                "metadata" : {"name" : str(op).replace("\n", " "),
                                                                                "framework" : "mxnet",
                                                                                },
            }).encode())
            urlopen(r)
        model.apply(lambda m : m.register_forward_hook(callback))
    elif isinstance(model, mxnet.module.BaseModule):
        def callback(self, *args, **argdict):
            retval = self.forward_(*args, **argdict)
            print(retval)
            #print(self.output_dict) #retval)
            return retval

        class Monitor:
            def install(self, exe):
                #def callback(name, handle):
                #    print(exe.forward())
                    #print(name) #, exe._get_outputs())
                    #o = exe.output_dict #get_outputs()
                    #print(o.keys())
                    #print(name)
                #print(exe)
                #exe.set_monitor_callback(lambda n, v : print(n, mxnet.nd.NDArray(mxnet.base.NDArrayHandle(v)).shape))
                #exe.set_monitor_callback(callback)
                exe.forward_ = exe.forward
                exe.forward = MethodType(callback, exe)
                #print(101)
        model.install_monitor(Monitor())
        # def callback(self, *args, **argdict):
        #     retval = self.forward_(*args, **argdict)
        #     for layers in model.get_params():
        #         for k, v in layers.items():
        #             print(k, v.shape)
        #     return retval
        #model.forward_ = model.forward
        #model.forward = MethodType(callback, model)
        # class Monitor:
        #    def __init__(self, _model):
        #        self._model = _model
        #    def tic(self):
        #        return []
        #    def toc(self):
        #        par, aux = self._model.module.get_params()
        #        r = Request("http://{}:{}".format(host, port), method="POST", data=json.dumps({"output" : len(par),
        #                                                                                "inputs" : len(aux),
        #                                                                                "type" : "LAYER",
        #                                                                                "metadata" : {#"name" : str(op).replace("\n", " "),
        #                                                                                "framework" : "sockeye",
        #                                                                                },
        #        }).encode())
        #        urlopen(r)
        #    def install(self, x):
        #        pass
        # model._monitor = Monitor(model)

class BlockModel(Sequential):
    def __init__(self):
        super(BlockModel, self).__init__()
        self.add(Dense(20))
        self.add(Dense(3))

def block_mlp():
    return BlockModel()

def symbol_mlp():
    data = symbol.Variable("data")
    first_layer = symbol.FullyConnected(data=data, num_hidden=20)
    second_layer = symbol.FullyConnected(data=first_layer, num_hidden=3)
    return data, second_layer

def train(model, x_train, y_train, x_dev, y_dev, epochs):
    model.initialize()
    criterion = mxnet.gluon.loss.SoftmaxCrossEntropyLoss(sparse_label=False)
    trainer = mxnet.gluon.Trainer(model.collect_params(), 'sgd', {'learning_rate': 0.1})

    x_train = nd.array(numpy.asfarray(x_train))
    y_train = nd.array(numpy.asfarray(y_train))
    x_dev = nd.array(numpy.asfarray(x_dev))
    y_dev = nd.array(numpy.asfarray(y_dev))

    for t in range(epochs):
        with mxnet.autograd.record():
            y_pred = model(x_train)
            loss = criterion(y_pred, y_train)
        loss.backward()
        trainer.step(y_train.shape[0])
        logging.info("Train loss: {}".format(mxnet.nd.sum(loss).asscalar()))


# LED를 제어합니다.

import RPi.GPIO as GPIO
import time

# 빨, 주, 노, 초, 파, 남, 보
colors = [0xFF0000, 0xFF0023, 0xFF00FF, 0x0000FF, 0x00FF00, 0x64EB00, 0x4BFB00]
# R, G, B의 핀을 각각 19, 21, 20 으로 지정합니다.
pins = {'pin_R':19, 'pin_G':21, 'pin_B':20}

# GPIO 핀 모드를 BCM으로 설정합니다.
GPIO.setmode(GPIO.BCM)

# 각 핀을 출력으로 설정하고, HIGH로 설정해 LED를 끕니다.
for i in pins:
    GPIO.setup(pins[i], GPIO.OUT)
    GPIO.output(pins[i], GPIO.HIGH)

# PWM 제어를 위해 설정합니다.
p_R = GPIO.PWM(pins['pin_R'], 2000)  # 주파수 설정 2KHz
p_G = GPIO.PWM(pins['pin_G'], 2000)
p_B = GPIO.PWM(pins['pin_B'], 2000)

# 초기 듀티 사이클 = 0 (LED 끄기)
p_R.start(0)
p_G.start(0)
p_B.start(0)

# 간단한 사칙연산을 하는 함수 map을 정의합니다.
def map(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# LED 색을 설정하는 함수
def setColor(col):   # 예)  col = 0x112233
    R_val = (col & 0x110000) >> 16
    G_val = (col & 0x001100) >> 8
    B_val = (col & 0x000011) >> 0

    # R_val, G_val, B_val의 값을 업데이트 합니다.
    R_val = map(R_val, 0, 255, 0, 100)
    G_val = map(G_val, 0, 255, 0, 100)
    B_val = map(B_val, 0, 255, 0, 100)

    # 듀티사이클을 변경합니다.
    p_R.ChangeDutyCycle(100-R_val)
    p_G.ChangeDutyCycle(100-G_val)
    p_B.ChangeDutyCycle(100-B_val)

# 아래의 코드를 시도합니다.
try:
    # while문 안의 코드를 반복합니다.
    while True:
        # 1초의 텀을 두고 다음 색상으로 넘어갑니다.
        for col in colors:
            setColor(col)
            time.sleep(1.0)

# 키 인터럽트가 발생하면 종료합니다.
except KeyboardInterrupt:
    p_R.stop()
    p_G.stop()
    p_B.stop()

    # 각 핀에 대해 LED 조명을 끕니다.
    for i in pins:
        GPIO.output(pins[i], GPIO.HIGH)
    # GPIO의 설정을 초기화합니다.
    GPIO.cleanup()


'''
Created on Jun 20, 2020
Write a program that multiplies two interger number without using
the * operator, using repeated adition.
@author: admin
'''
n1 = int(input("Enter first number - "))
n2 = int(input("Enter second number - "))
product = 0
count = n1
while count>0:
    count = count-1
    product = product+n2
    print(product)

print("The product of ",n1,' and ',n2," is ",product)


"""
	Given a collection of distinct numbers, return all possible permutations.
"""
class Solution(object):
	def permute(self, nums):
		"""
		:type nums: List[int]
		:rtype: List[List[int]]
		"""
		self.permutations = [];
		self.base = nums
		self.length = len( self.base )
		self.generate_pemutation()

		return self.permutations;

	def generate_pemutation( self, Pemutation=None, Elements=None) :

		if Elements is None:
			Elements = self.base;

		if Pemutation is None:
			Pemutation = []

		elif len(Pemutation) == self.length:
			self.permutations.append(Pemutation)
			return;

		for i in range( len( Elements ) ):
			Value = Elements[i];
			newPemutation = Pemutation[:]
			newPemutation.append(Value)

			newElements = Elements[:]
			newElements.remove(Value)
			self.generate_pemutation(Pemutation=newPemutation, Elements=newElements)

print(Solution().permute([1,2,3]));


input_data = open('05/input.txt', 'r').read().split('\n')

def create_list(data):
	global crates
	line = [data[i:i+4] for i in range(0, len(data), 4)]

	if not crates:
		crates = [[] for _ in range(len(line))]

	for i in range(len(line)):
		if line[i].strip() and not line[i].strip().isnumeric():
			crates[i].insert(0, line[i].strip().replace('[', '').replace(']', ''))

crates = []

for data in input_data:
	if data:
		if data[0] != 'm':
			create_list(data)
		elif data[0] == 'm':
			data = data.split()
			for i in range(int(data[1])):
				crates[int(data[-1])-1].append(crates[int(data[3])-1].pop())

top_crates = ""
for crate in crates:
	top_crates += crate[-1]

print(top_crates)

crates = []

for data in input_data:
	if data:
		if data[0] != 'm':
			create_list(data)
		elif data[0] == 'm':
			data = data.split()

			crates[int(data[-1])-1].extend(crates[int(data[3])-1][-(int(data[1])):])
			crates[int(data[3])-1][-(int(data[1])):] = []

top_crates = ""
for crate in crates:
	top_crates += crate[-1]

print(top_crates)


# -*-coding:iso-8859-1 -*
import pygame
from sys import stderr
from pygame.locals import *

#Contient toutes les constantes de l'application
#
#Les constantes de l'application sont des variables utilisées tout au long du programme, et qui ne doivent pas pouvoir être modifiées par la suite.
#Elles sont regroupées ici pour pouvoir être modifiées facilement.

#Données d'odre général

#Fichier vers lequel sont redirigées les erreurs, mais seulement si cette option est activée (à REDIRECTION_FICHIER_ERREURS)
#Dans ce fichier seront écrites toutes les erreurs d'exécution si REDIRECTION_FICHIER_ERREURS est activée.
#Le mode d'écriture dans le fichier doit être précisé à MODE_FICHIER_ERREURS
FICHIER_ERREURS = "Erreurs.txt"

#Mode d'écriture du fichier d'erreurs
#Il y en a plusieurs.
#« w » : Efface les erreurs précedéntes avant d'écrire les nouvelles
#« a » : Ajoute les nouvelles erreurs aux précédentes
MODE_FICHIER_ERREURS ="w"

#Redirection vers un fichier d'erreurs
#Si True, les erreurs sont redirigées dans un fichier
#Si False, les erreurs sont simplement affichées à l'écran.
REDIRECTION_FICHIER_ERREURS = False
if REDIRECTION_FICHIER_ERREURS is True:
	sys.stderr = open(FICHIER_ERREURS, MODE_FICHIER_ERREURS)

#Message affiché lorsqu'il y a une pause (terminal)
MESSAGE_PAUSE_PAR_DEFAUT = "Veuillez appuyer sur la touche « Entrée » pour continuer..."

#Chemin relatif vers le dossier des ressources
DOSSIER_RESSOURCES = "Ressources"

#Si cette constante vaut<True>, une répétition de l'évènement KEYDOWN aura lieu quand une touche est appuyée. Voir la constante suivante pour l'intervalle.
REPETITION_TOUCHES = False

#Intervalle en millisecondes entre deux répétitions de l'évènement KEYDOWN (si et seulement si REPETITION_TOUCHES vaut <True>)
INTERVALLE_REPETITION_TOUCHES = 100

#Liste des évènements utilisateur que le jeu peut capter.
LISTE_EVENTS_AUTORISES = [QUIT, KEYDOWN, KEYUP]

#Le nom de la carte sur laquelle on démarre
NOM_CARTE_LANCEMENT = "LD26-Fin"

#L'extension des fichiers carte
EXTENSION_FICHIER_CARTE = ".narromap"

#Le volume des musiques en boucle, à mettre à 0.0 pour pas se soûler
VOLUME_LONGUE_MUSIQUE = 0.0

##Mobile, PNJ, Joueur
#
#Fichier d'image par défaut du joueur, qui doit être situé dans le dossier des ressources
FICHIER_JOUEUR_PAR_DEFAUT = "Actor1.png"

#La couleur transparente de l'image du joueur par défaut.
COULEUR_TRANSPARENTE_FICHIER_JOUEUR_PAR_DEFAUT = (255,255,255)

#La partie de l'image du joueur lui correspondant.
CHARSET_JOUEUR_PAR_DEFAUT = (0,0)

#Affiche les coordonnées du joueur si <True>
LOG_COORDONNEES_JOUEUR = False

#Le nom qui identifie l'évènement Joueur par défaut
NOM_EVENEMENT_JOUEUR_PAR_DEFAUT = "Joueur"

#La vitesse de déplacement par défaut du joueur en pixels par seconde
VITESSE_DEPLACEMENT_JOUEUR_PAR_DEFAUT = 250

#La vitesse de déplacement par défaut du mobile en pixels par seconde
VITESSE_DEPLACEMENT_MOBILE_PAR_DEFAUT = 120

#Le nombre de millisecondes, au sein d'un tile ou pas, entre deux animations.
DUREE_ANIMATION_MOBILE_PAR_DEFAUT = 200 #3

#Le nombre de millisecondes, au sein d'un tile ou pas, entre deux animations.
DUREE_ANIMATION_JOUEUR_PAR_DEFAUT = 200 #12

#Temps (exprimé en millisecondes) entre deux animations sur place.
DUREE_ANIMATION_SP_PAR_DEFAUT = 100

#La direction de départ par défaut d'un mobile.
DIRECTION_DEPART_MOBILE_PAR_DEFAUT = "Bas"

#L'intelligence par défaut d'un PNJ. Quand elle vaut <True>, le PNJ débloque lui-même une situation de collision, car il est en A*.
#Cette variable n'a donc rien de fixe, elle dépend purement du trajet.
#La valeur par défaut devrait toujours être <False>, sauf quand le PNJ débute par A* (ce qui est rare).
INTELLIGENCE_PAR_DEFAUT = False

#Le courage par défaut d'un PNJ. Quand il vaut <False>, le PNJ abandonne tout déplacement en cas de collision.
COURAGE_PAR_DEFAUT = True

#Longueur d'un sprite de mobilepar défaut
LONGUEUR_SPRITE_PAR_DEFAUT = 32

#Largeur d'un sprite de mobile par défaut
LARGEUR_SPRITE_PAR_DEFAUT = 32

##Zone de pensée
#Des infos relatives à la zone de pensée de bas d'écran
#Le nom du fichier de police par défaut (qui doit être situé dans le dossier des ressources)
NOM_FICHIER_POLICE_PAR_DEFAUT = "BookAntiqua.ttf"

#La taille de la police par défaut
TAILLE_POLICE_PAR_DEFAUT = 15

#La vitesse d'affichage d'une pensée par défaut : c'est le temps d'affichage entre deux pensées (en millisecondes)
VITESSE_PENSEE_PAR_DEFAUT = 50

#Le temps par défaut, en millisecondes, que met une pensée avant d'être considérée comme lue
TEMPS_LECTURE_PENSEE = 2000

#La couleur de fond de la zone de pensée
COULEUR_FOND_ZONE_PENSEE = (0,0,0)

#La couleur par défaut dans laquelle sont écrites les pensées
COULEUR_ECRITURE_PENSEE = (255,255,255)

##Fenêtre
#Données utilisées lors de l'initialisation de la fenêtre
FENETRE = dict()
FENETRE["messageErreurInitialisationPygame"]="Une erreur s'est produite durant l'initialisation de Pygame, le programme doit donc se fermer."
FENETRE["messageErreurInitialisationFenetre"]="Une erreur s'est produite durant l'initialisation de la fenêtre, le programme doit donc se fermer."
FENETRE["longueurFenetre"] = 512
FENETRE["largeurFenetre"] = 384
FENETRE["largeurFenetreReelle"] = 416
FENETRE["couleurFenetre"] = (0,0,0) ##Couleur de fond de la fenêtre (hors zones spéciales comme tileset, outils...)
FENETRE["titreFenetre"] = "Narro Engine"
FENETRE["flagsFenetre"] = DOUBLEBUF#|FULLSCREEN|HWSURFACE
FENETRE["forceDirectX"] = False

#La taille de la police en splashscreen
TAILLE_POLICE_SPLASH_SCREEN = int(FENETRE["largeurFenetre"] / 4)

#L'intégralité des directions possibles
LISTE_DIRECTIONS = ["Haut", "Bas", "Gauche", "Droite", "Aucune"]

#Le nombre maximal de frames par seconde
NOMBRE_MAX_DE_FPS = 120#2000

#<True> si la limite doit être appliquée
LIMITER_FPS = True

#Volume par défaut (compris entre 0 et 1
VOLUME_MUSIQUE = 0.7 #0.0007

#La durée d'une pause lors d'une balade (un trajet aléatoire) exprimée en millisecondes
DUREE_PAUSE_BALADE = 300

#Le nombre de blocs entre deux pauses lors d'une balade
FREQUENCE_PAUSE_BALADE = 2

#Le fait d'être en session de debug. Si <True>, un Debugger/Memory profiler sera initialisé (Pympler).
SESSION_DEBUG = False

#Le fichier qui doit servir d'icône, à placer dans le dossier de ressources.
#S'il n'y en a aucun (<False>), Pygame tentera de mettre l'icône par défaut, mais cela ne fonctionne pas sur tous les systèmes/avec cx_Freeze (du moins on dirait).
FICHIER_ICONE = False

##Messages d'erreurs
##
##

#Messages d'erreur de mutation ou d'accès
#
MESSAGE_ERREUR_MUTATION_CHANGEMENT_CARTE = "<jeu.changementCarte> doit être un booléen."
MESSAGE_ERREUR_MUTATION_EN_MARCHE = "<Bloc.enMarche> doit être un booléen."
MESSAGE_ERREUR_MUTATION_CARTE_A_EXECUTER = "<jeu.carteAExecuter> doit être un <str>."
MESSAGE_ERREUR_CHARGEMENT_TILESET = "Le fichier {0}, qui doit servir de tileset, n'a pas pu être chargé : "
MESSAGE_ERREUR_ACCES_CONSTANTE = "La constante d'indice {0} n'existe pas."
MESSAGE_ERREUR_MUTATION_POSITION_SOURCE = "La nouvelle <positionSource> doit être un tuple de quatre entiers naturels."
MESSAGE_ERREUR_MUTATION_COULEUR_TRANSPARENTE = "La couleur {0} n'est pas valide."
MESSAGE_ERREUR_TILE_INEXISTANT = "Le tile aux coordonnées {0},{1} n'existe pas."
MESSAGE_ERREUR_MUTATION_DIRECTION1 = "La direction {0} doit être un <str>."
MESSAGE_ERREUR_MUTATION_DIRECTION2 = "La direction doit faire partie de la liste des directions possibles."

#Messages d'erreur divers
#
MESSAGE_ERREUR_UTILISATION_INTERRUPTEUR_INVERSE = "Il est impossible d'activer, désactiver, inverser ou changer l'état d'un interrupteur inversé : son état est indexé sur celui de l'interrupteur source."
MESSAGE_ERREUR_TILES_NON_ADJACENTS = "Les tiles {0} et {1} doivent être adjacents, et ce horizontalement ou verticalement uniquement (pas en diagonale)."
MESSAGE_ERREUR_INITIALISATION_ICONE = "L'icône {0} n'a pas pu être chargée. Pygame tentera d'utiliser l'icône par défaut."
from constantes import * #Import des constantes du projet, pour écraser celles du Narro Engine en cas de redéfinition


from __future__ import division

def eval_ast(mod):

    import ast
    import numpy
    from numexpr import evaluate

    context = {}
    context['division'] = division # THAT seems strange !
    context['inf'] = numpy.inf
    context['evaluate'] = evaluate
    context['maximum'] = numpy.maximum
    context['minimum'] = numpy.minimum
    context['exp'] = numpy.exp
    context['log'] = numpy.log
    context['sin'] = numpy.sin
    context['cos'] = numpy.cos
    context['abs'] = numpy.abs

    name = mod.body[0].name
    mod = ast.fix_missing_locations(mod)
    code  = compile(mod, '<string>', 'exec')
    exec(code, context, context)
    fun = context[name]
    return fun


from permutations_all import *
from combinations import *
from combinations_no_repeat import *

f = open('1-13_can_repeat.txt', 'w')

print = f.write

fullist = combinations_no_repeat(list(range(1, 14)), 4)

#print(len(fullist))

def connect(strlst):
	temp = ''
	for i in strlst:
		temp += i
	#print(temp)
	return temp

def combine(s, t):
	if not s:
		return t
	if not t:
		return s
	if s[0] == '(' or s[0] == ')':
		return s[:1] + combine(s[1:], t)
	if t[0] == '(' or t[0] == ')':
		return t[:1] + combine(s, t[1:])
	if s[0] == t[0]:
		return s[:1] + combine(s[1:], t[1:])

	return []

#print(combine(['(',1,'-',2,'+',3,')'],['(',1,'-',2,')','+',3]))

def brackets(a,b,c,d,x,y,z):
	lst = [a,x,b,y,c,z,d]
	l, r = ['('], [')']
	for h in range(4):
		i = h * 2
		c1 = lst[:i]+l+lst[i:]
		for j in range(2, (11-i)//2):
			k = i + j * 2
			c2 = c1[:k]+r+c1[k:]
			#print(connect(c2))
			for h0 in range(4):
				i0 = h0 * 2
				c3 = lst[:i0]+l+lst[i0:]
				for j0 in range(2, (11-i0)//2):
					k0 = i0 + j0 * 2
					c4 = c3[:k0]+r+c3[k0:]
					c5 = combine(c2, c4)
					#print(connect(c5))
					#"""
					marker = c5.count('/')
					if not marker:
						eq = connect(c5)
						if eval(eq) == 24:
							print(eq)
							print('\n')
							return True
					else:

						not_divisible = True

						if marker == 3:
							not_divisible = False

						elif marker == 1:
							for isla in range(11):
								if c5[isla] == '/':
									position = isla
									break

							isla = position

							if c5[isla+1] != '(':
								not_divisible = False
							elif c5[isla+3] == ')':
								not_divisible = False
							elif c5[isla+2] != '(':
								note = False
								for jsla in range(isla+4, 11):
									if c5[jsla] == '(':
										note = True
									elif note and c5[jsla] == ')':
										#print('ok')
										note = False
									elif not note and c5[jsla] == ')':
										#print(jsla, 'ok')
										if eval(connect(c5[isla+2:jsla])):
											not_divisible = False
										break

							else:
								countj = 0
								for jsla in range(isla+4, 11):
									if c5[jsla] == ')':
										countj += 1
										if countj == 2:
											if eval(connect(c5[isla+2:jsla])):
												not_divisible = False
											break

						else:
							for ia in range(11):
								if c5[ia] == '/':
									position1 = ia
									break
							for ib in range(position1+1, 11):
								if c5[ib] == '/':
									position2 = ib
									break

							ib = position2
							if c5[ib+1] != '(':
								not_divisible = False
							elif c5[ib+3] == ')':
								not_divisible = False
							elif c5[ib+2] != '(':
								note = False
								for jb in range(ib+4, 11):
									if c5[jb] == '(':
										note = True
									elif note and c5[jb] == ')':
										#print('ok')
										note = False
									elif not note and c5[jb] == ')':
										#print('ok', ib+2, jb)
										if eval(connect(c5[ib+2:jb])):
											not_divisible = False
										break
							else:
								countj = 0
								for jb in range(ib+4, 11):
									if c5[jb] == ')':
										countj += 1
										if countj == 2:
											if eval(connect(c5[ib+2:jb])):
												not_divisible = False
											break

							if not not_divisible:
								#print('ok')
								ic = position1
								if c5[ic+1] != '(':
									not_divisible = False
								elif c5[ic+3] == ')':
									not_divisible = False
								elif c5[ic+2] != '(':
									#print('ok')
									note = False
									for jd in range(ic+4, 11):
										if c5[jd] == '(':
											note = True
										elif note and c5[jd] == ')':
											#print('ok')
											note = False
										elif not note and c5[jd] == ')':
											#print('ok')
											if not eval(connect(c5[ic+2:jd])):
												not_divisible = True
											break
								else:
									countj = 0
									#print('ok')
									for jf in range(ic+4, 11):
										if c5[jf] == ')':
											countj += 1
											#print('ok')
											if countj == 2:
												#print('ok')
												if not eval(connect(c5[ic+2:jf])):
													not_divisible = True
												break

						if not not_divisible:
							eq = connect(c5)
							if eval(eq) == 24:
								print(eq)
								print('\n')
								return True
					#"""

def alg(nums):
	for p in permutations(nums):
		a, b, c, d = repr(p[0]), repr(p[1]), repr(p[2]), repr(p[3])
		for op in combinations(['+','-','*','/'], 3):
			x, y, z = op[0], op[1], op[2]

			if brackets(a,b,c,d,x,y,z):
				return True

	return False

notideal = []

for i in fullist:
	if not alg(i):
		notideal += [i]

print('\n')
print('Not Applicables:',len(notideal),'\n')
print('\n')
for i in notideal:
	print(repr(i))
	print('\n')

f.close()


#!/usr/bin/python

import math

def recipe_batches(recipe, ingredients):
  remaining_ingredients = ingredients
  check_ingredients = True
  batches = 0

  while check_ingredients:
    has_complete_batch = True
    for item in recipe.keys(): # For each item in recipe, check if there are enough items in ingredients
      if item in remaining_ingredients and remaining_ingredients[item] >= recipe[item]:
        remaining_ingredients[item] -= recipe[item] # If yes then subtract recipe items from ingredients
      else: # If there are not enough items, then return number of batches
        has_complete_batch = False
        break

    if has_complete_batch:
      batches += 1
    else:
      check_ingredients = False

  return batches

if __name__ == '__main__':
  # Change the entries of these dictionaries to test
  # your implementation with different inputs
  recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
  ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
  print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))


"""
Model how processes and applications are intertwined.

The process is the core object - a process starts and ends and can span
other processes or lead to other processes being started. Process
responsibility is supervised by a department, but other departments *may*
be involved in bringing the process to an end.

Applications are actual software applications that *may* assist in bringing
a process to an end. Not all applications are used for all processes - we can
create an overview of which apps are relevant for processes and vice versa.

The applications app relates back to processes.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _

from django_activiti.client import get_client_class as get_activiti_client_class
from django_activiti.fields import (
    ProcessDefinitionField as ActivitiProcessDefinitionField,
)
from django_camunda.client import get_client_class as get_camunda_client_class
from django_camunda.fields import (
    ProcessDefinitionField as CamundaProcessDefinitionField,
)
from treebeard.mp_tree import MP_Node

from .constants import ProcessStatusChoices, RiskLevels, StorageTypes

class Department(MP_Node):
    name = models.CharField(_("name"), max_length=255)
    contact_details = models.TextField(
        _("contact details"),
        blank=True,
        help_text=_("Contact details for the responsible(s) of the department."),
    )

    node_order_by = ["name"]

    class Meta:
        verbose_name = _("department")
        verbose_name_plural = _("departments")

    def __str__(self):
        return self.name

class Process(models.Model):
    """
    Represent a process as practiced by the municipality.

    Contains relations to which applications are involved and generally useful
    information.
    """

    name = models.CharField(
        _("name"),
        max_length=255,
        help_text=_("Human-friendly name."),
    )
    camunda_id = CamundaProcessDefinitionField(
        _("Camunda process"),
        blank=True,
    )
    activiti_id = ActivitiProcessDefinitionField(
        _("Activiti process"),
        blank=True,
    )

    description = models.TextField(
        _("description"),
        blank=True,
        help_text=_("Extended description of the process."),
    )
    department = models.ForeignKey(
        "Department",
        on_delete=models.PROTECT,
        related_name="owned_processes",
        verbose_name=_("department"),
        help_text=_("The department responsible for this process."),
    )
    other_departments = models.ManyToManyField(
        "Department",
        blank=True,
        related_name="involved_in",
        verbose_name=_("other departments"),
        help_text=_("Other departments that may play a role in this process"),
    )

    # relations
    initiating_processes = models.ManyToManyField(
        "self",
        blank=True,
        symmetrical=False,
        related_name="initiates",
        verbose_name=_("initiating processes"),
        help_text=_(
            "The set of processes that may lead to this process being started."
        ),
    )
    applications = models.ManyToManyField(
        "applications.Application",
        blank=True,
        related_name="processes",
        help_text=_("Set of applications used to handle this process"),
    )

    # information for the systematic overview - which is an inventory tracking meta-information
    # of processes
    personal_data = models.BooleanField(
        _("personal data"),
        default=True,
        help_text=_("Does personal data end up in the process?"),
    )
    process_status = models.CharField(
        _("process status"),
        max_length=50,
        choices=ProcessStatusChoices.choices,
        default=ProcessStatusChoices.active,
    )
    deactivation_date = models.DateField(
        _("deactivation date"),
        null=True,
        blank=True,
        help_text=_(
            "Date when this process became deactivated/historical. Leave blank "
            "for 'in production' processes."
        ),
    )
    zaaktype = models.URLField(
        _("zaaktype"),
        max_length=1000,
        blank=True,
        help_text=_("Zaaktype in the Catalogi API."),
    )
    zaaktype_owner = models.ForeignKey(
        "Department",
        on_delete=models.PROTECT,
        blank=True,
        null=True,
        related_name="+",
        verbose_name=_("zaaktype owner"),
        help_text=_("The department owning the zaaktype."),
    )
    risk_level = models.CharField(
        _("risk level"), max_length=50, choices=RiskLevels.choices, blank=True
    )

    # locations of archive
    location_digital = models.ForeignKey(
        "StorageLocation",
        on_delete=models.PROTECT,
        limit_choices_to={"storage_type": StorageTypes.digital},
        blank=True,
        null=True,
        verbose_name=_("Location digital"),
        related_name="+",
    )
    location_analogue = models.ForeignKey(
        "StorageLocation",
        on_delete=models.PROTECT,
        limit_choices_to={"storage_type": StorageTypes.analogue},
        blank=True,
        null=True,
        verbose_name=_("Location analogue"),
        related_name="+",
    )

    class Meta:
        verbose_name = _("process")
        verbose_name_plural = _("processes")

    def __str__(self):
        return self.name

    @property
    def applications_with_layers(self):
        apps = [
            {"layer": app.layer, "application": app}
            for app in self.applications.order_by("-layer")
        ]
        return apps

    @property
    def camunda_key(self) -> str:
        if not self.camunda_id:
            return ""
        return self.camunda_id.split(":")[0]

    @property
    def activiti_key(self) -> str:
        if not self.activiti_id:
            return ""
        return self.activiti_id.split(":")[0]

    @property
    def version(self) -> str:
        if self.activiti_id:
            return self.activiti_id.split(":")[1]
        elif self.camunda_id:
            return self.camunda_id.split(":")[1]
        return ""

    def xml(self) -> str:
        if self.activiti_id:
            client = get_activiti_client_class()()
            xml_data = client.get(
                f"repository/process-definitions/{self.activiti_id}/resourcedata"
            ).decode()
            return xml_data

        if self.camunda_id:
            client = get_camunda_client_class()()
            response = client.get(f"process-definition/{self.camunda_id}/xml")
            return response["bpmn20_xml"]

        return ""

class StorageLocation(models.Model):
    name = models.CharField(_("name"), max_length=100)
    storage_type = models.CharField(
        _("storage type"),
        max_length=50,
        choices=StorageTypes.choices,
        default=StorageTypes.digital,
    )

    class Meta:
        verbose_name = _("storage location")
        verbose_name_plural = _("storage locations")

    def __str__(self):
        return self.name


from lib.base import QualysBaseAction

import json

__all__ = [
    'GetScanResults'
]

class LaunchScanAction(QualysBaseAction):
    def run(self, scan_ref=None):
        payload = {
            'scan_ref': scan_ref,
            'action': 'fetch',
            'output_format': 'json'
        }
        scan_results = None
        try:
            scan_results = self.connection.request(
                api_call='api/2.0/fo/scan',
                data=payload,
                api_version=2,
                http_method='GET'
            )
            return True, json.loads(scan_results)
        except ConnectionError as e:
            return False, e


import random
import chen

class Player:
    VERSION = "Default Python folding player"

    MAX_BET = 300

    def betRequest(self, game_state):
        print (game_state)
        in_action=game_state['in_action']
        me=game_state['players'][in_action]
        current_buy_in=game_state['current_buy_in']

        cards = me['hole_cards']
        self.rank1 = None
        self.rank2 = None
        if len(cards) > 1:
            self.rank1 = cards[0]['rank']
            self.rank2 = cards[1]['rank']
            value = chen.get_value(cards)
            if value < 8 and self.rank1 != 'A' and self.rank2 != 'A':
                self.log_check()
                return 0 # check only, no raise
            if self.rank1 == self.rank2 and self.rank1 == 'A':
                self.log_allin()
                return 1000 # all in

        minimum_raise = game_state['minimum_raise'] if 'minimum_raise' in game_state else 0

        amount = current_buy_in - me['bet']
        if amount > self.MAX_BET and self.rank1 != self.rank2:
            print('CHECK only (HIGH bet)')
            return 0 # fold

        if len(cards) > 1:
            r = minimum_raise + random.random()*10 if random.random()>0.3 else 0
            amount += int(r)
        self.log_call(amount)
        return amount # always call

    def showdown(self, game_state):
        return True

    def log_check(self):
        if self.rank1:
            print('{} {}: CHECK only'.format(self.rank1, self.rank2))
        else:
            print('CHECK only')

    def log_call(self, amount):
        if self.rank1:
            print('{} {}: CALL: {}'.format(self.rank1, self.rank2, amount))
        else:
            print('CALL: {}'.format(amount))

    def log_allin(self):
        if self.rank1:
            print('{} {}: ALL IN'.format(self.rank1, self.rank2))
        else:
            print('ALL IN')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 11:27:21 2019

@author: root
"""

string=""
x=open("text.txt","w+")
while True:
    y=input()
    if y == "-1":
        break
    string=string+y
x.write(string)
x.close()