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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('flavourdb2', '0002_chef_chefbiofoodimage_comuna_menu_menuimage'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='comuna',
            name='chefs',
        ),
        migrations.AddField(
            model_name='chef',
            name='comunas',
            field=models.ManyToManyField(to='flavourdb2.Comuna'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='menu',
            name='name',
            field=models.CharField(default=b'', max_length=200),
            preserve_default=True,
        ),
    ]


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 12:06:22 2017

@author: Work
"""

import nltk
from nltk.book import *
from __future__ import print_function
from __future__ import division

def unusual_words(text):
    text_vocab = set(w.lower() for w in text if w.isalpha())
    english_vocab = set(w.lower() for w in nltk.corpus.words.words())
    unusual = text_vocab - english_vocab
    return sorted(unusual)

unusual_words(nltk.corpus.gutenberg.words('austen-sense.txt'))

unusual_words(nltk.corpus.nps_chat.words())

from nltk.corpus import stopwords
stopwords.words('english')
len(stopwords.words('english'))

def content_fraction(text):
    stopwords = nltk.corpus.stopwords.words('english')
    content = [w for w in text if w.lower() not in stopwords]
    #return content
    return len(content) / len(text)

content_fraction(nltk.corpus.reuters.words())

len(nltk.corpus.brown.words())
content_fraction(nltk.corpus.brown.words())

puzzle_letters = nltk.FreqDist('egivrvonl')
obligatory = 'r'
wordlist = nltk.corpus.words.words()
[w for w in wordlist if len(w) >= 6
                         and obligatory in w
                         and nltk.FreqDist(w) <= puzzle_letters]

names = nltk.corpus.names
names.fileids()
male_names = names.words('male.txt')
female_names = names.words('female.txt')
[w for w in male_names if w in female_names]

cfd = nltk.ConditionalFreqDist(
        (fileid, name[-1])
        for fileid in names.fileids()
        for name in names.words(fileid))
cfd.plot()

entries = nltk.corpus.cmudict.entries()
len(entries)

for entry in entries[42371:42379]:
    print(entry)

syllable = ['N', 'IHO', 'K', 'S']
[word for word, pron in entries if pron[-4:] == syllable]

[w for w, pron in entries if pron[-1] == 'M' and w[-1] == 'n']

from nltk.corpus import swadesh
swadesh.fileids()
swadesh.words('en')

fr2en = swadesh.entries(['fr', 'en'])
fr2en
translate = dict(fr2en)
translate['chien']
translate['jeter']

de2en = swadesh.entries(['de', 'en'])
es2en = swadesh.entries(['es', 'en'])
translate.update(dict(de2en))
translate.update(dict(es2en))
translate['Hund']
translate['perro']

languages = ['en', 'de', 'nl', 'es', 'fr', 'pt', 'la']
for i in [139, 140, 141, 142]:
    print(swadesh.entries(languages)[i])

from nltk.corpus import toolbox
toolbox.entries('rotokas.dic')

from nltk.corpus import wordnet as wn
wn.synsets('motorcar')
wn.synset('car.n.01').lemma_names()

wn.synset('car.n.01').definition()
wn.synset('car.n.01').examples()

wn.synset('car.n.01').lemmas()
wn.lemma('car.n.01.automobile')
wn.lemma('car.n.01.automobile').synset()
wn.lemma('car.n.01.automobile').name()

wn.synsets('car')
for synset in wn.synsets('car'):
    print(synset.lemma_names())
wn.lemmas('car')

motorcar = wn.synset('car.n.01')
types_of_motorcar = motorcar.hyponyms()
types_of_motorcar[0]
sorted(lemma.name() for synset in types_of_motorcar for lemma in synset.lemmas())

motorcar.hypernyms()
paths = motorcar.hypernym_paths()
len(paths)
[synset.name() for synset in paths[0]]
[synset.name() for synset in paths[1]]


#!/usr/bin/env python
import json
from argparse import ArgumentParser
from collections import defaultdict

import pandas as pd

parser = ArgumentParser()
parser.add_argument("filepath", help="The full path to the Google Search JSON file")
args = parser.parse_args()

with open(args.filepath) as f:
    data = json.load(f)

res = defaultdict(list)
for record in data:
    if record["title"].startswith("Searched for "):
        res["search"].append(record["title"].replace("Searched for ", ""))
        res["time"].append(record["time"])

        if "locations" in record:
            map_url = record["locations"][0]
            latitude, longitude = map(float, map_url["url"].split("=")[1].split(","))
        else:
            latitude, longitude = None, None
        res["latitude"].append(latitude)
        res["longitude"].append(longitude)

df = pd.DataFrame(res, columns=res.keys())
df["time"] = pd.to_datetime(df["time"])

df["year"] = df.time.dt.strftime("%Y")
df["year_month"] = df.time.dt.strftime("%Y-%m")
df["month"] = df.time.dt.strftime("%m")
df["year_week"] = df.time.dt.strftime("%G-%V")
df["day"] = df.time.dt.strftime("%Y-%m-%d")
df["weekday"] = df.time.dt.strftime("%w")
df["hour"] = df.time.dt.strftime("%H")

df.to_csv("data.csv", index=False)


from abc import ABC, abstractmethod
import random

# Base class for constraints
class Constraint(ABC):
    """
    Abstract base class for a 'constraint' in the context of
    constraint-satisfaction problems.

    Contains a list of variables on which the constraint is applied, and an
    abstract method satisfied() to test whether constraint is met.
    """
    def __init__(self, variables):
        self.variables = variables

    @abstractmethod
    def satisfied(self, assignment):
        raise NotImplementedError

class ConstraintSatisfactionProblem(object):
    """
    Class for setting up and solving a generic constraint satisfaction problem.

    Requires a list of *variables* and a dictionary *domains* that maps each
    variable to a list of domains.
    """
    def __init__(self, variables, domains, verbose=False, relaunch=1e6):
        self.variables = variables
        self.domains = domains
        self.verbose = verbose
        self.relaunch = relaunch
        self._call_count = 0

        # Initialize constraints
        self.constraints = {}
        for var in self.variables:
            # Make sure problem is set up appropriately
            if var not in self.domains:
                raise LookupError(("Every variable must have at least one ",
                                   "domain assigned to it"))
            self.constraints[var] = []

    def add_constraint(self, constraint):
        """
        Add a constraint to the variables listed in the CSP.
        """
        for var in constraint.variables:
            if var not in self.variables:
                raise LookupError("{} not found in variables".format(var))
            else:
                self.constraints[var].append(constraint)

    def consistent(self, variable, assignment):
        """
        Check if given assignment is consistent with all constraints on
        given variable.
        """
        for constraint in self.constraints[variable]:
            if not constraint.satisfied(assignment):
                return False
        return True

    def backtracking_search(self, assignment={}):
        """
        Recursive search through variables to ensure all variables are
        assigned with all constraints met.
        """
        self._call_count += 1
        if self.verbose:
            print("Call # {} to backtracking search".format(self._call_count))
        # If the church has gon
        if self._call_count > self.relaunch:
            assignment = {}
            random.shuffle(self.variables)
            self._call_count = 0
        # Base-case of recursion: all variables successfully assigned
        if len(assignment) == len(self.variables):
            return assignment

        # Get all variables from the problem that are not in the assignment
        unassigned = [v for v in self.variables if v not in assignment]

        # Get all possible domain values of the first unassigned variable
        first = unassigned[0]
        for value in self.domains[first]:
            local_assignment = assignment.copy()
            local_assignment[first] = value
            if self.consistent(first, local_assignment):
                result = self.backtracking_search(local_assignment)
                if result is not None:
                    return result
        return None


import rclpy
import rclpy.node
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point

class MarkerPublisher(rclpy.node.Node):

    def __init__(self):
        super().__init__('urdf_to_dh_marker_pub')
        self.marker_id = 0
        self.marker_publisher = self.create_publisher(Marker, 'topic', 10)

    def publish_arrow(self, frame, origin, direction, color):
        # Make publish arrow. Start at xyz, then xyz + axis
        marker_msg = Marker()
        marker_msg.header.frame_id = frame
        marker_msg.header.stamp = self.get_clock().now().to_msg()
        marker_msg.id = self.marker_id
        self.marker_id += 1
        marker_msg.type = Marker.ARROW
        marker_msg.action = Marker.ADD
        marker_msg.frame_locked = True
        marker_msg.color.r = color[0]
        marker_msg.color.g = color[1]
        marker_msg.color.b = color[2]
        marker_msg.color.a = color[3]
        marker_msg.scale.x = 0.01
        marker_msg.scale.y = 0.02
        start_pt = Point()
        start_pt.x = origin[0]
        start_pt.y = origin[1]
        start_pt.z = origin[2]
        marker_msg.points.append(start_pt)
        end_pt = Point()
        end_pt.x = origin[0] + direction[0] * 0.2
        end_pt.y = origin[1] + direction[1] * 0.2
        end_pt.z = origin[2] + direction[2] * 0.2
        marker_msg.points.append(end_pt)

        self.marker_publisher.publish(marker_msg)

    def publish_frame(self, frame_name, tf):
        self.publish_arrow(frame_name, tf[0:3, 3], tf[0:3, 0], [1.0, 0.0, 0.0, 0.5])
        self.publish_arrow(frame_name, tf[0:3, 3], tf[0:3, 1], [0.0, 1.0, 0.0, 0.5])
        self.publish_arrow(frame_name, tf[0:3, 3], tf[0:3, 2], [0.0, 0.0, 1.0, 0.5])


def cache(func):
    cache_dict = {}

    def inner(*args, **kwargs):
        try:
            key = repr(args, kwargs)
            print(key)
        except Exception as e:
            print(e)
        try:
            return cache_dict[key]
        except KeyError:
            cache_dict[key] = func(*args, **kwargs)
            return cache_dict[key]
    inner.csrf_exempt = True
    return inner

@cache
def query_limit(sql=None):
    print(sql)

import better_exceptions
request = "test test test"
a, b, c, d = request.split()  # 处理数据


from sklearn.metrics import accuracy_score, roc_auc_score, f1_score, precision_score, recall_score

from common import utils
import numpy as np
from discrimination.discrimination_utils import load_data_demencia, results_to_csv, roc_auc_score_multiclass
from discrimination.svm_utils import train_svm

config = utils.load_config('config/config_demencia16k-225B.yml')  # loading configuration
x_train, y_train = load_data_demencia(config=config)  # loading data
# out_results =

# train
# print("Checkpoint utilized:", config['pretrained_model_details']['checkpoint_path'])
list_c = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 0.1]
for c in list_c:
    array_preds, array_trues, array_probs = train_svm(svm_type='linear-loocv', C=c, X=x_train, y=np.ravel(y_train))

    acc = accuracy_score(array_trues, array_preds)
    auc = roc_auc_score(array_trues, array_probs, multi_class='ovo', labels=np.unique(y_train))
    # auc = roc_auc_score(array_trues, array_probs[:, 1])
    aucs = roc_auc_score_multiclass(actual_class=array_trues, pred_class=array_preds)

    array_preds[array_preds == 3] = 2
    array_trues[array_trues == 3] = 2
    f1 = f1_score(array_trues, array_preds)
    prec = precision_score(array_trues, array_preds)
    rec = recall_score(array_trues, array_preds)
    # results_to_csv(file_name=out_results,
    #                list_values=,
    #                list_columns=)
    print("with", c, "acc:", acc, " f1:", f1, " prec:", prec, " recall:", rec, 'AUC:', auc, 'auc-c0:', aucs[1],
          'auc-c1:', aucs[2])


"""
Module for processing aspect data
"""
from __future__ import division, absolute_import, print_function

from sys import stdout
from operator import attrgetter, itemgetter
import warnings
import inspect

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import pandas as pd
from scipy.optimize import curve_fit
from skimage.feature import match_template, peak_local_max
from skimage.transform import warp
from astropy.io import fits

from ..util.time import oeb2utc
from ..util.fitting import parapeak

__all__ = ['PYFrame', 'PYSequence', 'RFrame', 'RSequence']

NUM_ROWS = 960
NUM_COLS = 1280

def _kernel(radius):
    """The empirically chosen kernel to represent both the Sun and the fiducials."""
    axis = np.arange(-(radius * 2), radius * 2 + 1)
    x, y = np.meshgrid(axis, axis)
    template = 1 - np.cosh(np.sqrt(x**2 + y**2) * 5. / radius) / 200.
    template[template < 0] = 0
    return template

template_sun = _kernel(50)
template_fiducial = 1 - _kernel(4)

class Frame(object):
    """Base class for a camera frame

    Parameters
    ----------
    filename : str
        The name of the FITS file of the camera frame
    uid : int
        The UID of the camera to check for consistency with the camera frame.
        The default of None means that consistency is not checked.
    decimation_range : tuple of int
        The allowable range of decimation levels.
    """
    def __init__(self, filename, uid=None, decimation_range=(2, 10)):
        with fits.open(filename) as f:
            if uid != None and f[0].header['CAMERA'] != uid:
                raise RuntimeError
            self.filename = filename
            self.header = f[0].header
            self.data = f[1].data.astype(np.uint8)
            self.trigger_time = f[0].header['GT_TRIG']
        self.decimation = self._detect_decimation(decimation_range)

    def _detect_decimation(self, decimation_range):
        """Detects the decimation level of the camera frame.

        Parameters
        ----------
        decimation_range : tuple of int
            The inclusive range of decimation levels to check against the camera frame

        Returns
        -------
        decimation_level : int
            For a decimation_level of N, N-1 rows out of every N rows is empty
        decimation_index : int
            The index of the non-empty row for every decimation block
            (i.e. strictly less than decimation_level)
        """
        dead1 = (self.data == 0).sum(1) == NUM_COLS
        for step in range(decimation_range[0], decimation_range[1] + 1):
            sub_rows = NUM_ROWS // step
            dead2 = dead1[:sub_rows * step].reshape(sub_rows, step).max(0)
            idx = np.flatnonzero(~dead2)
            if len(idx) == 1:
                return (step, idx[0])
        return (1, 0)

    def plot_image(self, **imshow_kwargs):
        """Plots the camera frame, defaulting to no interpolation."""
        args = {'cmap'   : 'gray',
                'extent' : [-0.5, NUM_COLS - 0.5, NUM_ROWS - 0.5, -0.5],
                'interpolation' : 'nearest'}
        args.update(imshow_kwargs)
        return plt.imshow(self.image, **args)

    @property
    def image(self):
        if self.decimation == (1, 0):
            return self.data
        else:
            transformation = np.matrix([[1, 0, 0],
                                        [0, 1. / self.decimation[0], -self.decimation[1] / self.decimation[0]],
                                        [0, 0, 1]])
            return warp(self.data[self.decimation[1]::self.decimation[0], :], transformation,
                        output_shape=(NUM_ROWS, NUM_COLS), mode='edge', preserve_range=True)

class PYFrame(Frame):
    """Class for a pitch-yaw image

    Parameters
    ----------
    filename : str
        The name of the FITS file of the camera frame
    uid : int
        Defaults to the UID of the pitch-yaw camera, but can be set to a different camera's UID or to None
    """
    def __init__(self, filename, uid=158434):
        try:
            Frame.__init__(self, filename, uid=uid)
        except RuntimeError:
            raise RuntimeError("This file does not appear to be a valid frame from the pitch-yaw camera")

        self.peaks, self.fiducials = self._process()

    def _process(self):
        """Finds the Suns and the fiducials."""
        # Perform a coarse search for Suns
        coarse_image = self.image[::10, ::10]
        coarse_match = match_template(coarse_image, template_sun[::10, ::10], pad_input=True)
        coarse_peaks = peak_local_max(coarse_match, threshold_abs=0.9, num_peaks=3)

        fine_peaks = []
        strength = []
        fiducials = []

        for coarse_peak in coarse_peaks:
            # For each coarse detection, do a detection at the full resolution
            if coarse_peak[0] < 11 or coarse_peak[0] > 84 or coarse_peak[1] < 11 or coarse_peak[1] > 116:
                break
            sub_image = self.image[coarse_peak[0] * 10 - 110:coarse_peak[0] * 10 + 111,
                                   coarse_peak[1] * 10 - 110:coarse_peak[1] * 10 + 111]
            match = match_template(sub_image, template_sun, pad_input=True)
            peak = peak_local_max(match, threshold_abs=0.9, num_peaks=1)
            if len(peak) > 0:
                peak = peak[0]
                peak_r, peak_c = parapeak(match[peak[0] - 1:peak[0] + 2, peak[1] - 1:peak[1] + 2])
                peak += coarse_peak * 10 - 110

                fine_peaks.append((peak[0] + peak_r, peak[1] + peak_c))

                #FIXME: need a more robust estimate of the strength of each peak
                strength.append(self.image[peak[0], peak[1]])

                # Find fiducials near the center of the Sun
                match = match_template(self.image[peak[0]-60:peak[0]+61, peak[1]-60:peak[1]+61],
                                       template_fiducial, pad_input=True)
                fids = peak_local_max(match, threshold_abs=0.8)
                for fid in fids:
                    fid_r, fid_c = parapeak(match[fid[0] - 1:fid[0] + 2, fid[1] - 1:fid[1] + 2])
                    fid += peak - 60

                    fiducials.append((fid[0] + fid_r, fid[1] + fid_c))

        # Sort the peaks in order of decreasing strength
        fine_peaks = [peak for (strength, peak) in sorted(zip(strength, fine_peaks), reverse=True)]

        return fine_peaks, fiducials

    def plot_image(self, **imshow_kwargs):
        """Plots the pitch-yaw image, including Sun/fiducial detections."""
        if self.peaks:
            # Draw an X at the center of each Sun
            arr_peaks = np.array(self.peaks)
            plt.plot(arr_peaks[:, 1], arr_peaks[:, 0], 'rx')

            # Draw circles around each Sun
            radius = 60
            angle = 2 * np.pi * np.arange(0, 101, 0.01)
            for peak in self.peaks:
                plt.plot(peak[1] + radius * np.cos(angle), peak[0] + radius * np.sin(angle), 'r')

        if self.fiducials:
            # Draw a cross at each fiducial
            arr_fiducials = np.array(self.fiducials)
            plt.plot(arr_fiducials[:, 1], arr_fiducials[:, 0], 'b+')

        return Frame.plot_image(self, **imshow_kwargs)

class RFrame(Frame):
    """Class for a roll image

    Parameters
    ----------
    filename : str
        The name of the FITS file of roll image
    uid : int
        Defaults to the UID of the roll camera, but can be set to a different camera's UID or to None
    """
    def __init__(self, filename, uid=142974):
        try:
            Frame.__init__(self, filename, uid=uid, decimation_range=(10, 10))
        except RuntimeError:
            raise RuntimeError("This file does not appear to be a valid frame from the roll camera")

        self.midpoint = self._process()

    def _process(self, plot=False):
        """Fit the horizons"""
        # For now, fit the whole thing
        data = np.mean(self.data[self.decimation[1]::self.decimation[0], :], 0)
        left = np.min(np.flatnonzero(data[0:640] < np.mean(data[0:640])))
        right = np.max(np.flatnonzero(data[640:] < np.mean(data[640:]))) + 640

        subx = np.arange(left, right + 1)
        guess = (639.5, 0.02, 0.04, 10)
        try:
            popt, pcov = curve_fit(RFrame.atmosphere_sym, subx, data[left:right+1], guess)
        except RuntimeError:
            warnings.warn_explicit("Could not automatically fit the horizon",
                                   RuntimeWarning, __file__, inspect.currentframe().f_lineno)
            return None

        if plot:
            print(popt)

            plt.plot(data)
            plt.plot(subx, RFrame.atmosphere_sym(subx, *popt))

        return popt[0]

    def plot_image(self, **imshow_kwargs):
        """Plots the roll image, including annotations."""
        return Frame.plot_image(self, **imshow_kwargs)

    @staticmethod
    def atmosphere_sym(x, midpoint, scale, amp, dc):
        """Exponential atmospheric model with symmetry (i.e., hyperbolic cosine)"""
        return amp * np.cosh(scale * (x - midpoint)) + dc

    @staticmethod
    def atmosphere_asym(x, midpoint, scale, amp1, amp2, dc):
        """Exponential atmospheric model with asymmetry in normalization"""
        return amp1 * np.exp(-scale * (x - midpoint)) + amp2 * np.exp(scale * (x - midpoint)) + dc

class FrameSequence(list):
    """Base class for a sequence of camera frames"""
    def __init__(self, list_of_files, frame_class=Frame):
        for entry in list_of_files:
            self.append(frame_class(entry))
            stdout.write(".")

        stdout.write("\n")

    def animate(self, fps=4, fig=None, **imshow_kwargs):
        """Return a matplotlib animation of the frame sequence.  Extra keyword arguments are passed on to
        `matplotlib.pyplot.imshow`.

        Parameters
        ----------
        fps : int
            Number of frames per second for interactive display

        fig : `matplotlib.figure.Figure`
            If None, the current figure is used

        Returns
        -------
        `matplotlib.animation.FuncAnimation`

        Examples
        --------
        To save a matplotlib animation as an animated GIF:

        >>> anim = framesequence.animate()
        >>> anim.save('animation.gif', writer='imagemagick', fps=4)

        On Windows, you may need to configure matplotlib to find `convert.exe`, e.g.:

        >>> import matplotlib as mpl
        >>> mpl.rcParams['animation.convert_path'] = 'C:\\Program Files\\ImageMagick-6.9.2-Q16\\convert.exe'

        """
        if fig is None:
            fig = plt.gcf()

        args = {'cmap'   : 'gray',
                'extent' : [-0.5, NUM_COLS - 0.5, NUM_ROWS - 0.5, -0.5],
                'clim' : (0, 256),
                'interpolation' : 'nearest'}
        args.update(imshow_kwargs)
        im = plt.imshow(np.zeros_like(self[0].image), **args)

        iterator = self.__iter__()

        # Although this function does nothing, otherwise matplotlib "burns" the first frame for initialization
        def init():
            pass

        # Update with the next frame's data
        def update_im(frame, im):
            im.set_data(frame.image)
            plt.gca().set_title(frame.filename)
            return im,

        ani = animation.FuncAnimation(fig, update_im, iterator, fargs=(im,), init_func=init,
                                      repeat=False, interval=1000 / fps)

        return ani

    def compact(self):
        """Crude compaction of a decimated sequence"""
        for i in range(len(self) - 1, 0, -1):
            if (self[i].decimation[0] == self[i-1].decimation[0]) and\
               (self[i].decimation[1] > self[i-1].decimation[1]):
                self[i-1].data += self[i].data
                self.pop(i)
            else:
                self[i].decimation = (1, 0)
        self[0].decimation = (1, 0)

class PYSequence(FrameSequence):
    """Class for a sequence of pitch-yaw images

    Parameters
    ----------
    list_of_files : list of str
        List of FITS files with pitch-yaw images
    """
    def __init__(self, list_of_files):
        FrameSequence.__init__(self, list_of_files, frame_class=PYFrame)

    @property
    def dataframe(self):
        """Obtain a pandas DataFrame"""
        center = [x.peaks[0] for x in self]
        return pd.DataFrame({'center_x' : [z[1] for z in center],
                             'center_y' : [z[0] for z in center]},
                            index=oeb2utc([x.trigger_time for x in self]))

    def plot_centers(self, **dataframe_plot_kwargs):
        """Plot the center of the brightest Sun across the entire image sequence"""
        return self.dataframe.plot(**dataframe_plot_kwargs)

class RSequence(FrameSequence):
    """Class for a sequence of roll images

    Parameters
    ----------
    list_of_files : list of str
        List of FITS files with roll images
    """
    def __init__(self, list_of_files):
        FrameSequence.__init__(self, list_of_files, frame_class=RFrame)

    @property
    def dataframe(self):
        """Obtain a pandas DataFrame"""
        return pd.DataFrame({'midpoint' : [x.midpoint for x in self]},
                            index=oeb2utc([x.trigger_time for x in self]))

    def plot_midpoint(self, **dataframe_plot_kwargs):
        """Plot the midpoints"""
        return self.dataframe.plot(**dataframe_plot_kwargs)


import datetime
from individual import Individual
from family import Family

individuals = {}
families = {}

supported_tags: list = [
    "INDI",
    "NAME",
    "SEX",
    "BIRT",
    "DEAT",
    "FAMC",
    "FAMS",
    "FAM",
    "MARR",
    "HUSB",
    "WIFE",
    "CHIL",
    "DIV",
    "DATE",
    "HEAD",
    "TRLR",
    "NOTE",
]

def parse_date(date: str) -> datetime.date:
    """Helps to parse date"""

    month_dict = {
        "JAN": 1,
        "FEB": 2,
        "MAR": 3,
        "APR": 4,
        "MAY": 5,
        "JUN": 6,
        "JUL": 7,
        "AUG": 8,
        "SEP": 9,
        "OCT": 10,
        "NOV": 11,
        "DEC": 12,
    }
    date = date.split()
    return datetime.datetime(int(date[2]), month_dict[date[1]], int(date[0])).date()

def is_supported_tag(tag: str) -> bool:
    """check weather in"""
    return tag in supported_tags

def process_family(rows) -> Family:
    """read"""
    family = Family()

    # by default will not process marriage and divorce assuming level will be 0
    process_marriage = False
    process_divorce = False

    for row in rows:

        # Reads each row and sets the corresponding field in the family object
        if row[1] == "FAM":
            family.identifier = row[2].strip()
        elif row[1] == "HUSB":
            family.husband_id = row[2].strip()
        elif row[1] == "WIFE":
            family.wife_id = row[2].strip()
        elif row[1] == "CHIL":
            family.children.append(row[2].strip())
        elif row[1] == "DIV":
            # Begin reading in the divorce date
            process_divorce = True
            family.is_divorced = True
        elif row[1] == "MARR":
            # Begin reading in the marriage date
            process_marriage = True
        elif int(row[0]) == 2 and row[1] == "DATE":
            if process_marriage:
                family.married = parse_date(row[2].strip())
            elif process_divorce:
                family.is_divorced = True
                family.divorced = parse_date(row[2].strip())

    return family

def process_individual(rows: list) -> Individual:
    """Helps to read individual"""

    # create a new individual.
    individual = Individual()

    # by default will not process birth and death assuming level will be 0
    process_birth = False
    process_death = False

    for row in rows:

        if int(row[0]) == 1:
            process_birth = False
            process_death = False

        if row[1] == "INDI":
            individual.identifier = row[2].strip()
        elif row[1] == "BIRT":
            process_birth = True
        elif int(row[0]) == 2 and row[1] == "DATE":
            if process_birth:
                individual.birthday = parse_date(row[2].strip())
            elif process_death:
                individual.death_day = parse_date(row[2].strip())
        elif row[1] == "FAMS":
            individual.spouse_family.append(row[2].strip())
        elif row[1] == "FAMC":
            individual.children_family.append(row[2].strip())
        elif row[1] == "NAME":
            individual.name = row[2].strip()
        elif row[1] == "SEX":
            individual.gender = row[2].strip()
        elif row[1] == "DEAT":
            if "Y" == row[2].strip():
                process_death = True
                individual.alive = False
            else:
                individual.alive = True

    # process age
    individual.process_age()

    return individual

def parser_file(file_path: str):
    """"""

    is_individual = False
    is_family = False

    lines_list = []

    # default  tags and args to str

    tag = ""
    level = 0

    with open(file_path, "r") as lines:

        for line in lines:

            list_of_words = line.split()
            level = int(list_of_words.pop(0))

            if len(list_of_words) == 1:
                tag = list_of_words[0]
                args = ""
            else:
                tag = (
                    list_of_words.pop(1)
                    if list_of_words[1] == "INDI" or list_of_words[1] == "FAM"
                    else list_of_words.pop(0)
                )
                args=""
                for word in list_of_words:
                    args = args + word + " "

            if level == 0:
                if is_individual:
                    new_individual = process_individual(lines_list)
                    individuals[new_individual.identifier] = new_individual
                if is_family:
                    new_family = process_family(lines_list)
                    families[new_family.identifier] = new_family
                if tag == "INDI":
                    is_individual = True
                    is_family = False
                    lines_list = []
                elif tag == "FAM":
                    is_individual = False
                    is_family = True
                    lines_list = []
                else:
                    is_individual = False
                    is_family = False

            if tag in supported_tags:
                lines_list.append([level, tag, args])

            for family in families.keys():
                families[family].husband_name = individuals[families[family].husband_id].name
                families[family].wife_name = individuals[families[family].wife_id].name
        individual_list = []
        family_list = []
        individual_list = []
        for individual in sorted(individuals.keys()):
            ind = individuals[individual]
            individual_list.append(
                [
                    ind.identifier,
                    ind.name,
                    ind.gender,
                    ind.birthday,
                    ind.age,
                    ind.alive,
                    ind.death_day,
                    ind.get_children_family() ,
                    ind.get_spouse_family(),
                ]
            )
        for family in sorted(families.keys()):
            fam = families[family]
            family_list.append(
                [
                    fam.identifier,
                    fam.married,
                    fam.get_is_divorced(),
                    fam.husband_id,
                    fam.husband_name,
                    fam.wife_id,
                    fam.wife_name,
                    fam.get_children(),
                ]
            )

        return individual_list ,family_list


import json

import pytest

from src.main import app

from fastapi.testclient import TestClient

headers = {"Accept": "application/json"}
client = TestClient(app, headers=headers)

def test_get_echo_reply():
    response = client.get('/')
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, stranger"}

@pytest.mark.parametrize("test_input", [
    ({"name": "Vasiliy"}),
    ({"surname": "Petrov"}),
    ({})
])
def test_post_echo_reply(test_input):
    response = client.post('/',  json=test_input)
    assert response.status_code == 200
    assert json.loads(response.json()) == test_input

def test_get_request_parser():
    response = client.get('/request')
    assert response.status_code == 200
    assert response.json() == {
        "headers": dict(response.request.headers),
        "cookies": dict(client.cookies),
        "method": response.request.method,
        "body": {}
    }

@pytest.mark.parametrize("test_input", [
    ({"name": "Vasya", "surname": "Vasiliev"}),
    ({"color": "black", "something": 5}),
    ({})
])
def test_post_request_parser(test_input):
    response = client.post('/request', json=test_input)
    assert response.status_code == 200
    assert response.json() == {
        "headers": dict(response.request.headers),
        "cookies": dict(client.cookies),
        "method": response.request.method,
        "body": test_input
    }


from Aluno import Aluno
from Disciplina import Disciplina
from AlunoDisciplina import AlunoDisciplina

def cadastrarAluno():
    matricula = input("Digite a matrícula: ")
    nome = input("Digite o nome do aluno: ")
    email = input("Digite o e-mail do aluno: ")
    telefone = input("Digite o telefone do aluno: ")
    curso = input("Qual o curso do aluno: ECA ou BSI? ")
    while curso.upper() not in ["ECA", "BSI"]:
        curso = input("Qual o curso do aluno: ECA ou BSI? ")

    return Aluno(matricula, nome, email, telefone, curso)

def cadastrarDisciplina():
    codigo = input("Digite o código da disciplina: ")
    nome = input("Digite o nome da disciplina: ")
    ementa = input("Digite a ementa da disciplina")

    return Disciplina(codigo, nome, ementa)

def vincularAlunoDisciplina(aluno, disciplina):
    nap1 = float(input(f"Qual a nota do NAP1 do aluno {aluno.getNome()} na disciplina {disciplina.getNome()}? "))
    nap2 = float(input(f"Qual a nota do NAP2 do aluno {aluno.getNome()} na disciplina {disciplina.getNome()}? "))
    ad = AlunoDisciplina()
    ad.cadastrarNotas(aluno, disciplina, nap1, nap2)
    return ad

# principal

# a = cadastrarAluno()
# d = cadastrarDisciplina()
a = Aluno(000, "edvar", "ed@", 333, "BSI")
d = Disciplina(111, "POO", "poo")

# vincular/matricular
ad = vincularAlunoDisciplina(a, d)

#armazenar em lista

bsi = []
eca = []

if(ad.getAluno().getCurso() == "BSI"):
    bsi.append(ad)
else:
    eca.append(ad)
print("\n\n")
print("Listagem de alunos de BSI (questão 1")
for b in bsi:
    print(b.getAluno().getNome(),b.getDisciplina().getNome())

print(bsi)
print(eca)


import string
from random import choice
from typing import Optional, TYPE_CHECKING

from quart import Blueprint, jsonify

from litecord.auth import admin_check
from ...errors import InternalServerError, NotFound
from litecord.types import timestamp_
from litecord.schemas import validate
from litecord.admin_schemas import INSTANCE_INVITE

if TYPE_CHECKING:
    from litecord.typing_hax import app, request
else:
    from quart import current_app as app, request

bp = Blueprint("instance_invites", __name__)
ALPHABET = string.ascii_lowercase + string.ascii_uppercase + string.digits

def _gen_inv() -> str:
    """Generate an invite code"""
    return "".join(choice(ALPHABET) for _ in range(6))

async def gen_inv(ctx) -> Optional[str]:
    """Generate an invite."""
    for _ in range(10):
        possible_inv = _gen_inv()

        created_at = await ctx.db.fetchval(
            """
        SELECT created_at
        FROM instance_invites
        WHERE code = $1
        """,
            possible_inv,
        )

        if created_at is None:
            return possible_inv

    return None

@bp.route("", methods=["GET"], strict_slashes=False)
async def _all_instance_invites():
    await admin_check()

    rows = await app.db.fetch(
        """
    SELECT code, created_at, uses, max_uses
    FROM instance_invites
    """
    )

    rows = [dict(row) for row in rows]

    for row in rows:
        row["created_at"] = timestamp_(row["created_at"])

    return jsonify(rows)

@bp.route("", methods=["POST"], strict_slashes=False)
async def _create_invite():
    await admin_check()

    j = validate(await request.get_json(), INSTANCE_INVITE)

    code = await gen_inv(app)
    if code is None:
        raise InternalServerError()

    await app.db.execute(
        """
    INSERT INTO instance_invites (code, max_uses)
    VALUES ($1, $2)
    """,
        code,
        j["max_uses"],
    )

    inv = await app.db.fetchrow(
        """
        SELECT code, created_at, uses, max_uses
        FROM instance_invites
        WHERE code = $1
        """,
        code,
    )
    dinv = dict(inv)
    dinv["created_at"] = timestamp_(dinv["created_at"])

    return jsonify(dinv)

@bp.route("/<invite>", methods=["GET"])
async def _get_invite(invite):
    inv = await app.db.fetchrow(
        """
        SELECT code, created_at, uses, max_uses
        FROM instance_invites
        WHERE code = $1
        """,
        invite,
    )

    if not inv:
        raise NotFound(10006)
    dinv = dict(inv)
    dinv["created_at"] = timestamp_(dinv["created_at"])
    return jsonify(dinv)

@bp.route("/<invite>", methods=["DELETE"])
async def _del_invite(invite: str):
    await admin_check()

    res = await app.db.execute(
        """
    DELETE FROM instance_invites
    WHERE code = $1
    """,
        invite,
    )
    if res == "DELETE 0":
        raise NotFound(10006)

    return "", 204


import sys
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml

from a3d import KWSBrain
from a3d.dataset import prep_speechcommands
from a3d.dataset import create_datasets_speechcommands

def main(hparams, hparams_file, run_opts, overrides):
    # Create experiment directory
    sb.create_experiment_directory(
        experiment_directory=hparams["output_folder"],
        hyperparams_to_save=hparams_file,
        overrides=overrides,
    )

    # Data prep to run on the main thread
    sb.utils.distributed.run_on_main(
        prep_speechcommands,
        kwargs={
            "data_folder": hparams["data_folder"],
            "save_folder": hparams["annotation_folder"]
        },
    )

    # Create dataset objects
    datasets, label_encoder = create_datasets_speechcommands(hparams)

    # Initialize the Trainer
    brain = KWSBrain(
        modules=hparams["modules"],
        hparams=hparams,
        run_opts=run_opts
    )

    # Evaluate the best checkpoint on the test set
    brain.evaluate_robustness(
        test_set=datasets["test"],
        test_loader_kwargs=hparams["dataloader_options"]
    )

if __name__ == "__main__":
    # Reading command line arguments
    hparams_file, run_opts, overrides = sb.parse_arguments(sys.argv[1:])

    # Load hyperparameters file with command-line overrides
    with open(hparams_file) as f:
        hparams = load_hyperpyyaml(f, overrides)

    # Initialize ddp (useful only for multi-GPU DDP training)
    sb.utils.distributed.ddp_init_group(run_opts)

    main(hparams, hparams_file, run_opts, overrides)


#012 두 개의 숫자를 입력받는다. 만약 첫 번째 숫자가 두 번째 숫자보다 크면, 두 번째 숫자를 먼저 출력한 다음에 첫 번째 숫자를 출력하라.
#그렇지 않다면 첫 번째 숫자를 출력한 다음에 두 번째 숫자를 출력하라

num1 = int(input('첫 번째 숫자: '))
num2 = int(input('두 번째 숫자: '))

if num1 > num2:
    print(num2, num1)
else:
    print(num1, num2)

#013 사용자에게 20보다 작은 숫자를 입력하라고 요청한다. 만약 입력된 값이 20과 같거나 크면 "Too high" 라는 메세지를 출력하라. 그렇지 않다면 "Thank you"를 출력하라

number = int(input("20보다 작은 숫자: "))

if number >= 20:
    print("\"Too high\"")

else:
    print("\"Thank you\"")

#014 사용자에게 10과 20(포함) 사이의 숫자를 입력하라고 요청한다. 만약 입력한 값이 이 범위 안의 숫자이면 "Thank you"라는 메시지를 출력하라.
#그렇지 않다면 "Incorrect answer"라는 메세지를 출력하라.

number = int(input('10이상 20이하의 숫자: '))

if number >= 10 and number <= 20:
    print("Thank you")
else:
    print("Incorrect answer")

#015 사용자에게 좋아하는 색을 입력하라고 요청한다. 만약 "red"나 "RED" 또는 "Red"를 입력하면 "I like red too"라는 메세지를 출력하라
#그렇지 않다면 "I don't like that colour, I prefer red"라는 메세지를 출력하라.

favorite = input("좋아하는 색: ")

if favorite == 'red' or favorite == 'RED' or favorite == 'Red':
    print("I like red too")

else:
    print("I don't like that colour, I prefer red")

#016 사용자에게 지금 비가 오는지 묻고 그 대답을 소문자로 변환하여 대소문자에 상관없도록 한다. 만약 "yes"라고 입력한다면 바람이 부는지 묻는다.
#두 번째 질문에 대해 "yes"라고 입력하면 "It is too windy for an umbrella"라는 메시지를 표시하라. 그렇지 않다면 "Take an umbrella"라는 메세지를
#표시하라. 만약 첫 번째 질문에 대해 "yes"라고 입력하지 않는다면 "Enjoy your day"라는 메시지를 표시하라.

rain = input("지금 비가 오나요?: ")

if rain == "yes":
    wind = input("바람이 부나요?: ")
    if wind == "yes":
        print("It is too windy for an umbrella")
    else:
        print("Take an umbrella")

else:
    print("Enjoy your day")

#017 사용자의 나이를 묻자. 만약 18세 이상이면 "You can vote"라는 메시지를 표시하라. 만약 17세라면 "You can learn to drive"라는
#메시지를 표시하라. 만약 16세 라면 "You can buy a lottery ticket"이라는 메시지를 표시하라. 만약 16세 미만이라면 "You can go
#Trick-or-treating"이라는 메시지를 표현하라

age = int(input("몇 살인가요?: "))

if age >= 18:
    print("You can vote")

elif age == 17:
    print("You can learn to drive")

elif age == 16:
    print("You can buy a lottery ticket")

else:
    print("You can go Trick-or-treating")

#018 사용자에게 숫자를 입력하라고 요청하자. 만약 10 미만이면 "Too low"라는 메시지를 표시하라. 만약 입력한 숫자가 10에서 20 사이라면
#"Correct"라고 표시하라. 그렇지 않다면 "Too high"라고 표시하라.

number = int(input("숫자를 입력하세요: "))

if number < 10:
    print("Too low")

elif 10 < number < 20:
    print("Correct")

else:
    print("Too high")

#019 사용자에게 1이나 2또는 3을 입력하라고 하자. 만약 1을 입력하면 "Thank you"라는 메시지를 표시하라. 만약 2를 입력하면 "Well done"을
#표시하라. 만약 3을 입력하면 "Correct"를 표시하라. 만약 사용자가 다른 것을 입력하면 "Error message"를 표시하라.

number = int(input("1이나 2또는 3을 입력하시오: "))

if number == 1:
    print("Thank you")

elif number == 2:
    print("Well done")

elif number == 3:
    print("Correct")

else:
    print("Error message")


import pytest

import abjad

def test_LilyPondParser__spanners__HorizontalBracket_01():

    maker = abjad.NoteMaker()
    target = abjad.Container(maker([0] * 4, [(1, 4)]))
    abjad.horizontal_bracket(target[:])
    abjad.horizontal_bracket(target[:2])
    abjad.horizontal_bracket(target[2:])

    assert abjad.lilypond(target) == abjad.string.normalize(
        r"""
        {
            c'4
            \startGroup
            \startGroup
            c'4
            \stopGroup
            c'4
            \startGroup
            c'4
            \stopGroup
            \stopGroup
        }
        """
    )

    parser = abjad.parser.LilyPondParser()
    result = parser(abjad.lilypond(target))
    assert abjad.lilypond(target) == abjad.lilypond(result) and target is not result

def test_LilyPondParser__spanners__HorizontalBracket_02():
    """
    Starting and stopping on the same leaf.
    """

    string = r"""{ c \startGroup \stopGroup c c c }"""
    with pytest.raises(Exception):
        abjad.LilyPondParser()(string)

def test_LilyPondParser__spanners__HorizontalBracket_03():
    """
    One group stopping on a leaf, while another begins on the same leaf.
    """

    string = r"""{ c \startGroup c \stopGroup \startGroup c c \stopGroup }"""
    with pytest.raises(Exception):
        abjad.LilyPondParser()(string)

def test_LilyPondParser__spanners__HorizontalBracket_04():
    """
    Unterminated.
    """

    string = r"""{ c \startGroup c c c }"""
    with pytest.raises(Exception):
        abjad.LilyPondParser()(string)

def test_LilyPondParser__spanners__HorizontalBracket_05():
    """
    Unstarted.
    """

    string = r"""{ c c c c \stopGroup }"""
    with pytest.raises(Exception):
        abjad.LilyPondParser()(string)


# check duplicate characters in a string
def check_char_duplicate(String1):
    str_len = len(String1)
    index = 0
    for char1 in String1:
        if index == str_len:
            pass
        sub_string = String1[index+1:]
        for char in sub_string:
            if char1 == char:
                return True
        index = index+1

    return False

# check duplicate characters in a string without new data structure
def check_char_dup(String1):
    str_len = len(String1)
    index = 0
    for char1 in String1:
        if index == str_len:
            pass
        for i in range(index+1,str_len,1):
            if char1 == String1[i]:
                return True
        index = index+1
    return False

#Check if two strings are just permutation of one another
def check_string_permu(String1, String2):
    for char1 in String1:
        for i in range(0,len(String2)):
            if char1 == String2[i]:
                if i == 0:
                    String2 = String2[i+1:]
                else:
                    String2 = String2[:i]+String2[i+1:]
                break
    if len(String2) == 0:
        return True
    else:
        return False

#urlify a string. extra spaces present in input string
def urlify(String1, length):
    char_space = " "
    char_url = "%20"
    url_string = ""
    for i in range(0,len(String1)):
        if String1[i] == char_space:
            if len(url_string) == 0:
                url_string = String1[:i] + char_url
            else:
                url_string = url_string + char_url
        else:
            url_string = url_string + String1[i]
        if len(url_string) == length:
            break
    return url_string

#check if string is a palindrome
def check_palindrome(string1):
    flag = True
    fw_index = 0
    bw_index = len(string1)
    string1 = string1.lower()
    string1 = string1.replace(" ,.?!",)

    for char in string1:
        if char == " ":
            fw_index = fw_index +1
            continue
        while string1[bw_index-1] == " ":
            bw_index = bw_index - 1

        if char == string1[bw_index-1]:
            fw_index = fw_index+1
            bw_index = bw_index-1
        else:
            flag = False
            break
        if fw_index >= bw_index:
            break
    return flag

#Check if two strings are one edit away
def check_edit(string1, string2):
    flag = True
    diff_len = len(string1) - len(string2)
    if diff_len == 0:
        changes = 0
        for i in range(len(string1)):
            if string1[i] != string2[i]:
                changes = changes+1
            if changes > 1:
                flag = False
                break
    elif diff_len ==1:
        flag = check_changes(string1,string2)
    elif diff_len ==-1:
        flag = check_changes(string2,string1)
    else:
        flag = False
    return flag

def check_changes(string1, string2):
    index = 0
    changes = 0
    for char in string1:
        if char == string2[index]:
            index = index +1
        else:
            changes = changes +1
        if changes > 1 or index>=len(string2):
            break
    if changes > 1:
        return False
    else:
        return True

# String compress function
def string_compress(string1):
    string_dic = {}
    char_count = 0
    for char in string1:
        if char in string_dic:
            string_dic[char] = string_dic[char] + 1
        else:
            string_dic[char] = 1
    out_string = ""
    for key,value in string_dic.items():
        out_string = out_string + key + str(value)
    return out_string


import sys
import os
from PyQt5.QtWidgets import QMainWindow, QPushButton,\
    QApplication, QInputDialog, QLineEdit, QLabel, \
    QFileDialog, QComboBox, QAction, QMessageBox
from PyQt5.QtCore import pyqtSlot, QByteArray, Qt
from PyQt5.QtGui import QIcon, QPixmap, QColor
import client
from final import image_parser, make_hist, decode
import skimage
from skimage.viewer import ImageViewer
from PIL import Image
from matplotlib import pyplot as plt
import io

global_user_email = ""
global_image_name = []
global_selected_name = ""
global_process_type = ""
global_image_dict = {}
global_process_image = ""

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'BME 590 Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.init_gui()
        self.next = None

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Welcome!')
        self.display_text()
        self.button_new_user()
        self.button_existing_user()
        self.show()

    def display_text(self):
        label = QLabel('Authors: Sarah Putney, '
                       'Erica Skerrett, Roujia Wang', self)
        label.setAlignment(Qt.AlignCenter)
        label.move(120, 300)
        label.setMinimumSize(480, 40)

    def button_new_user(self):
        button = QPushButton('Create New User', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(150, 200)
        button.clicked.connect(self.create_user)

    def button_existing_user(self):
        button = QPushButton('Existing User', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(400, 200)
        button.clicked.connect(self.get_user)

    @pyqtSlot()
    def create_user(self):
        user_email, ok_pressed = QInputDialog.getText(
            self, "Account Information", "User Email:", QLineEdit.Normal, "")
        if ok_pressed and user_email != '':
            global global_user_email
            global_user_email = user_email
            client.post_create_user(global_user_email)
            self.next = App2()
            self.close()

    @pyqtSlot()
    def get_user(self):
        user_email, ok_pressed = QInputDialog.getText(
            self, "Account Information", "User Email:", QLineEdit.Normal, "")
        if ok_pressed and user_email != '':
            global global_user_email
            global_user_email = user_email
            email = client.get_returning_user(global_user_email)
            if email.get("error_message") == 'None':
                self.next = App2()
                self.close()
            else:
                print(email)
                button_reply = QMessageBox.question(
                    self, 'Error Message', email.get("error_message"),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if button_reply == QMessageBox.Yes:
                    self.next = App()
                    self.close()
                else:
                    self.close()

class App2(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.label = QLabel()
        self.next = None
        self.init_gui()

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Step 1: Choose Images!')
        self.display_image()
        self.button_choose()
        self.show()

    def display_image(self):
        label = QLabel(self)
        pixmap = QPixmap('christmas.jpg')
        pixmap2 = pixmap.scaledToWidth(400)
        label.setPixmap(pixmap2)
        label.setGeometry(160, 50, 640, 280)

    def button_choose(self):
        button = QPushButton('Choose Image', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(260, 340)
        button.clicked.connect(self.image_dialog)

    def image_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getOpenFileNames(
            self, "QFileDialog.getOpenFileNames()", "",
            "All Files (*)", options=options)
        if file_name:
            global global_image_name
            global global_user_email
            global global_image_dict
            global_image_name = file_name
            global_image_dict = image_parser(global_image_name)
            client.post_uploaded_images(global_user_email, global_image_dict)
            self.close()
            self.next = App3()
        else:
            button_reply = QMessageBox.question(
                self, 'Error Message', 'Please Choose Image(s) to Proceed',
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if button_reply == QMessageBox.Yes:
                self.next = App2()
                self.close()
            else:
                self.close()

class App3(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.next = None
        self.init_gui()

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Step 2: Upload Image(s)!')
        self.display_text()
        self.scroll_down_menu()
        self.button_upload()
        self.show()

    def display_text(self):
        label = QLabel('Please Select From Following Options'
                       ' by Clicking the Image Name:', self)
        label.setAlignment(Qt.AlignCenter)
        label.move(40, 150)
        label.setMinimumSize(640, 40)

    def scroll_down_menu(self):
        global global_user_email
        global global_image_name
        uploaded_images = global_image_name
        combo = QComboBox(self)
        for i in uploaded_images:
            combo.addItem(i)
        combo.move(140, 200)
        combo.setMinimumSize(440, 40)
        combo.activated[str].connect(self.on_activated)

    def on_activated(self, name):
        global global_image_name
        global global_selected_name
        for i in global_image_name:
            if name in i:
                global_selected_name = name
        print(global_selected_name)

    def button_upload(self):
        button = QPushButton('Upload Image', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(260, 320)
        button.clicked.connect(self.next_window)

    def next_window(self):
        global global_selected_name
        if global_selected_name == '':
            button_reply = QMessageBox.question(
                self, 'Error Message', 'You must click on the image to'
                                       ' select it!',
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if button_reply == QMessageBox.Yes:
                self.next = App3()
                self.close()
            else:
                self.close()
        else:
            self.close()
            self.next = App4()

class App4(QMainWindow):

    def __init__(self):
        super().__init__()
        global global_selected_name
        self.title = 'Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.next = None
        self.path, self.filename = os.path.split(global_selected_name)
        self.init_gui()
        print(global_selected_name)

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Step 3: Process Image!')
        self.display_image()
        self.button1()
        self.button2()
        self.button3()
        self.button4()
        self.show()

    def display_image(self):
        label = QLabel(self)
        pixmap = QPixmap(os.path.join(self.path, self.filename))
        pixmap2 = pixmap.scaledToWidth(400)
        label.setPixmap(pixmap2)
        label.setGeometry(50, 20, 640, 400)

    def button1(self):
        button = QPushButton('Histogram Equalization', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(470, 120)
        button.clicked.connect(self.histogram)

    def button2(self):
        button = QPushButton('Contrast Stretching', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(470, 170)
        button.clicked.connect(self.contrast)

    def button3(self):
        button = QPushButton('Log Compression', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(470, 220)
        button.clicked.connect(self.compression)

    def button4(self):
        button = QPushButton('Reverse Video', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(470, 270)
        button.clicked.connect(self.reverse)

    @pyqtSlot()
    def histogram(self):
        global global_user_email
        global global_process_type
        global global_selected_name
        global_process_type = "HistogramEqualization"
        print(global_user_email)
        print(global_selected_name)
        print(global_process_type)
        client.post_processed_image(global_user_email,
                                    global_selected_name, global_process_type)
        print('posted')
        print(global_selected_name)
        self.close()
        self.next = App5()

    @pyqtSlot()
    def contrast(self):
        global global_user_email
        global global_process_type
        global global_selected_name
        global_process_type = "ContrastStretching"
        print(global_user_email)
        print(global_selected_name)
        print(global_process_type)
        client.post_processed_image(global_user_email,
                                    global_selected_name, global_process_type)
        self.close()
        self.next = App5()

    @pyqtSlot()
    def compression(self):
        global global_user_email
        global global_process_type
        global global_selected_name
        global_process_type = "LogCompression"
        print(global_user_email)
        print(global_process_type)
        client.post_processed_image(global_user_email,
                                    global_selected_name, global_process_type)
        self.close()
        self.next = App5()

    @pyqtSlot()
    def reverse(self):
        global global_user_email
        global global_process_type
        global global_selected_name
        global_process_type = "ReverseVideo"
        print(global_user_email)
        print(global_process_type)
        client.post_processed_image(global_user_email,
                                    global_selected_name, global_process_type)
        self.close()
        self.next = App5()

class App5(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.next = None
        self.init_gui()

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Step 4: Download Processed Image!')
        self.display_images()
        self.display_images_info()
        self.button_download()
        self.upload_new_images()
        self.button_histogram()
        self.show()

    def display_images(self):
        global global_user_email
        global global_process_type
        global global_selected_name
        global global_process_image
        image_strip = global_selected_name.split('/')[-1]
        image_name = image_strip.split('.')[0]
        processed_images = client.get_processed_image(
            global_user_email, image_name, global_process_type)
        print(processed_images.keys())
        label = QLabel(self)
        s = processed_images[image_name]
        global_process_image = s
        data = QByteArray.fromBase64(s.encode())
        image_type = image_strip.split('.')[1]
        upload_sizes = client.get_upload_sizes(global_user_email)
        upload_size = upload_sizes[image_name]
        size_string = "Upload Size: " + str(upload_size)
        upload_times = client.get_upload_time(global_user_email)
        upload_time = upload_times[image_name]
        print(upload_time)
        time_string = "Upload Time: " + upload_time
        pixmap = QPixmap()
        if pixmap.loadFromData(data, image_type):
            pixmap2 = pixmap.scaledToWidth(250)
            label.setPixmap(pixmap2)
            label.setGeometry(460, 100, 640, 250)
        label1 = QLabel(size_string, self)
        label1.move(455, 30)
        label1.setMinimumSize(220, 40)
        label2 = QLabel(time_string, self)
        label2.move(410, 50)
        label2.setMinimumSize(290, 40)

    def display_images_info(self):
        global global_user_email
        info = client.get_user_metrics(global_user_email)
        user_metrics = list(info.keys())
        user_metrics_info = list(info.values())
        for i, n in enumerate(user_metrics):
            label1 = QLabel(str(n), self)
            label1.move(30, 100 + i * 20)
            label1.setMinimumSize(220, 40)
        for i, n in enumerate(user_metrics_info):
            label2 = QLabel(str(n), self)
            label2.move(260, 100 + i * 20)
            label2.setMinimumSize(200, 40)

    def button_download(self):
        button = QPushButton('Download Image', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(130, 370)
        button.clicked.connect(self.download)

    def upload_new_images(self):
        button = QPushButton('Upload New Image(s)', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(130, 410)
        button.clicked.connect(self.new_upload)

    def button_histogram(self):
        button = QPushButton('View Histograms', self)
        button.setMinimumSize(200, 40)
        button.setToolTip('This is an example button')
        button.move(130, 330)
        button.clicked.connect(self.histogram_window)

    @pyqtSlot()
    def download(self):
        global global_process_image
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, options = QFileDialog.getSaveFileName(
            self, "QFileDialog.getSaveFileName()",
            "", "JPEG Files(*.jpeg);; "
                "TIFF Files(*.tiff);; "
                "PNG Files(*.png)", options=options)
        if file_name:
            options = options.split('.')[-1]
            options = options.strip(')')
            img_buf = decode(global_process_image)
            img_array = skimage.io.imread(img_buf)
            plt.imsave(file_name + '.' + options,
                       img_array)

    @pyqtSlot()
    def new_upload(self):
        print('Upload New Images')
        self.close()
        self.next = App2()

    @pyqtSlot()
    def histogram_window(self):
        global global_selected_name
        global global_image_dict
        image_strip = global_selected_name.split('/')[-1]
        image_key = image_strip.split('.')[0]
        image_data = global_image_dict[image_key]
        make_hist(image_data)
        self.close()
        self.next = App6()

class App6(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Image Processor'
        self.left = 10
        self.top = 10
        self.width = 720
        self.height = 480
        self.next = None
        self.init_gui()

    def init_gui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(204, 204, 255))
        self.setPalette(p)
        self.statusBar().showMessage('Step 5: View Histograms!')
        self.upload_new_images()
        self.histogram_original()
        self.histogram_processed()
        self.show()

    def upload_new_images(self):
        button = QPushButton('Upload New Image(s)', self)
        button.setMinimumSize(200, 30)
        button.setToolTip('This is an example button')
        button.move(260, 400)
        button.clicked.connect(self.new_upload)

    def histogram_original(self):
        label_text = QLabel('Original Image', self)
        label_text.move(105, 80)
        label_text.setMinimumSize(150, 40)
        label = QLabel('Original Image', self)
        pixmap = QPixmap('hist.jpeg')
        pixmap2 = pixmap.scaledToWidth(300)
        label.setPixmap(pixmap2)
        label.setGeometry(30, 120, 640, 200)

    def histogram_processed(self):
        global global_process_image
        vals = make_hist(global_process_image)
        label_text = QLabel('Processed Image', self)
        label_text.move(465, 80)
        label_text.setMinimumSize(150, 40)
        label = QLabel('Processed Image', self)
        pixmap = QPixmap('hist.jpeg')
        pixmap2 = pixmap.scaledToWidth(300)
        label.setPixmap(pixmap2)
        label.setGeometry(390, 120, 640, 200)

    @pyqtSlot()
    def new_upload(self):
        self.close()
        self.next = App2()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


import os
import rnmd.extract_code
import rnmd.compile_markdown

default_compile_dir="/tmp/rnmd"
os.makedirs(default_compile_dir, exist_ok=True)

def run_markdown(source, args):

    temp_compile_path = os.path.join(default_compile_dir, os.path.basename(source))

    rnmd.compile_markdown.compile_markdown(source, temp_compile_path)

    command = ""
    if(args is None):
        command = temp_compile_path
    else:
        all_args = [temp_compile_path] + args
        command = (" ").join(all_args)

    os.system(command)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(
        description="Run markdown contained code"
    )
    parser.add_argument('source', help="Source of the documentation file")
    arguments = parser.parse_args()
    source = arguments.source

    run_markdown(source)


from basedecoder import BaseDecoder
from cipherenum import CipherType
from cipher import InputText
import math

class RailDecoder(BaseDecoder):

    """
    A decoder class to decode rail ciphers (transposition ciphers)

    Given a text encoded like below
    'This is a test' encoded with 4 rails

    T     A
     H   S T
      I I   E T
       S     S

    A rail chunk consists of the characters from
    the top of one hump to the start of the next.
    So in this instance THISIS is the first rail
    chunk and ATEST is the begining of the second
    chunk but isn't complete.
    """

    def __init__(self):
        super().__init__()
        self.add_key([('rails', self.key_rails_validate, 'Number of rails to use to decode')])

    def __rail_chunk_size(rails):
        if rails < 3:
            raise ValueError('Must have at least 3 rails.')

        return (rails * 2) - 2

    def __rail_char_count(rails, str_len):
        if rails < 3:
            raise ValueError('Must have at least 3 rails')

        chunk_size = rail_chunk_size(rails)
        chunk_multiplier = [2] * rails
        chunk_multiplier[0] -= 1
        chunk_multiplier[-1] -= 1

        chunk_count = str_len // chunk_size
        extra_chars = str_len % chunk_size

        rail_chars = [None] * rails
        for i, val in enumerate(chunk_multiplier):
            rail_chars[i] = val * chunk_count

        for i in range(extra_chars):
            rail_index = i
            if i >= rails:
                # It is on the upward slope of the last chunk
                rail_index = (rails - 1) - ((i + 1) % rails)
            rail_chars[rail_index] += 1

        return rail_chars

    def __solve_rail_fence(rails, text: str, strip_spaces=True):

        if strip_spaces:
            text = text.replace(' ', '')
        pattern = __rail_char_count(rails, len(text))

        working_text = text
        rail_text = [None] * rails
        for rail in range(rails):
            rail_text[rail] = working_text[:pattern[rail]]
            working_text = working_text[pattern[rail]:]

        final_str = ''
        chunk_size = rail_chunk_size(rails)
        for i in range(len(text)):
            i = i % chunk_size
            rail_index = i
            if i >= rails:
                # This char is on the upward slope
                rail_index = (rails - 1) - ((i + 1) % rails)

            # Take the first char from the rail and add it to the final string
            final_str += rail_text[rail_index][:1]
            rail_text[rail_index] = rail_text[rail_index][1:]

        return final_str

    def decode(self, inputText: InputText) -> bool:
        """
        Returns a True if there is suffecient information (keys)
        provided to decode the input text provided. Otherwise false
        is returned by this function.
        """

        if not self.can_decode():
            return None

        start_rails = None
        end_raiuls = None
        val_rails = self.get_key('rails')

        results = []

        if ':' in val_rails:
            start_rails, end_rails = val_rails.split(':')

            # Convert the strings to integers
            start_rails = int(start_rails)
            end_rails = int(end_rails)
        else:
            start_rails = val_rails

            # Convert the strings to integers
            start_rails = int(start_rails)
            end_rails = start_rails + 1

        print("Decoding")
        for rail_count in range(start_rails, end_rails + 1):
            text = inputText.text()
            result = inputText.copy()
            res_text = results.append(self.__solve_rail_fence(text, rail_count))
            result.add_decoded_output(res_text, self)

        return results

    @staticmethod
    def key_rails_validate(value: str):
        """
        Validates that the key the user set is valid.

        Parsing or processing of the value can happen here.
        The value returned will be stored automatically, and
        if the value is not valid at all this function returns None.
        """

        if value is None:
            return None

        if '-' in value:
            arr = value.split('-')

            if len(arr) != 2:
                return None

            start = arr[0].strip()
            end = arr[1].strip()
            return start + ':' + end

        try:
            rail_num = int(value)
            return rail_num
        except ValueError:
            # Not an int value
            pass

        return None

    @staticmethod
    def type():
        return CipherType.RAIL_FENCE


# patricia.lisa.main.py
__author__ = "Victória Regina Caruzo"
__version__ = "09.07.20"

from _spy.vitollino.main import Cena, Elemento, STYLE
from random import shuffle
""" from grace.main import Praia """

__version__ = "1.0"
__author__ = "ECHO"
STYLE["width"] = 1150
STYLE["height"] = "620px"
TABULEIRO = "http://www.infcross.com.br/mestrado/tabuleiro.jpg"
BOTAO = "http://www.infcross.com.br/mestrado/botao3.jpg"
DADO1 = "http://www.infcross.com.br/mestrado/dado1.png"
DADO2 = "http://www.infcross.com.br/mestrado/dado2.png"
DADO3 = "http://www.infcross.com.br/mestrado/dado3.png"
DADO4 = "http://www.infcross.com.br/mestrado/dado4.png"
DADO5 = "http://www.infcross.com.br/mestrado/dado5.png"
DADO6 = "http://www.infcross.com.br/mestrado/dado6.png"

dado1 = Cena(DADO1)
dado2 = Cena(DADO2)
dado3 = Cena(DADO3)
dado4 = Cena(DADO4)
dado5 = Cena(DADO5)
dado6 = Cena(DADO6)

class Tabuleiro:
    def vai(self):
        """ Mostra a cena do tabuleiro """
        Cena(TABULEIRO).vai()

class Jogo:
    """ Representa uma cena de tabuleiro com o botão """
    def __init__(self):
        """ Mostra o tabuleiro com o botão start"""
        self.cena = Cena(TABULEIRO, direita=Tabuleiro())
        self.start = Elemento(BOTAO, x=5, y=15, cena=self.cena)
        #Cena(CENA_JOGO).vai()
    def vai(self):
        """ Mostra o tabuleiro """
        self.cena.vai()
        #Cena(CENA_JOGO).vai()

dados = ["dado1", "dado2", "dado3", "dado4", "dado5", "dado6"]
shuffle(dados)
print(dados)

    #def __init__(self, outra):

if __name__ == "__main__":
    Jogo().vai()


import os

PORT = 4013

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
STATIC_DIR = os.path.realpath(
    os.path.join(SCRIPT_DIR, '..', 'frontend', 'dist'))
PRIVATE_FACTORY_RELPATH = os.path.join(
    'chromeos-base', 'factory-board', 'files')


# key builder test
from flexmock import flexmock
from keyBuilder import buildKey
from assertpy import assert_that

def test_buildKey():
	config = flexmock(keyName="test",
		keyPattern=".*",
		hasGroup=False,
		groupNum=None)

	assert_that(buildKey("alan", [config])).is_equal_to({"test":"alan"})

def test_buildKey_two_elements():
	config = flexmock(keyName="test",
		keyPattern=".*",
		hasGroup=False,
		groupNum=None)

	config1 = flexmock(keyName="test1",
		keyPattern=".*",
		hasGroup=False,
		groupNum=None)

	assert_that(buildKey("alan", [config, config1])).is_equal_to({"test":"alan", "test1":"alan"})

def test_buildKey_has_group():
	config = flexmock(keyName="test",
		keyPattern="\w+:(\w+)",
		hasGroup=True,
		groupNum=0)

	assert_that(buildKey("name:string", [config])).is_equal_to({"test":"string"})


__author__ = "JJ.sven"

import threading
import time
import random

'''互斥锁 mutex
   3.0应该是做了优化（估计只是简单计算不会出问题，复杂task多线程间应该也会出现数据线程不安全）
   所以问了保证数据在多线程间的安全问题，有时候要给修改数据的步骤加同步锁，并且步骤不能太耗时
'''
def run(n):
    lock.acquire()
    global  num
    num +=1
    # 加了锁就等于之间的操作是串行的，如果有耗时操作，等于累加这些耗时，多线程时就会出现等待
    # time.sleep(1)
    lock.release()

lock = threading.Lock()
num = 0
t_objs = [] #存线程实例
for i in range(50):
    t = threading.Thread(target=run,args=("t-%s" %i ,))
    t.start()
    t_objs.append(t) #为了不阻塞后面线程的启动，不在这里join，先放到一个列表里

for t in t_objs: #循环线程实例列表，等待所有线程执行完毕
    t.join()

print("----------all threads has finished...",threading.current_thread(),threading.active_count())

print("num:",num)


from nptdms import TdmsFile

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

input_file="M9_Default_200921-123303_Courants50Hz.tdms"
with TdmsFile.open(input_file) as tdms_file:
    # Iterate over all items in the file properties and print them
    for name, value in tdms_file.properties.items():
        print("{0}: {1}".format(name, value))

    # List groups
    all_groups = tdms_file.groups()
    print("all_groups=", all_groups)

    # for a given group
    group = tdms_file['Courants et Ref. Alimentations']

    # List Groups and Channels per Group
    all_group_channels = group.channels()
    print(all_group_channels)

    for group in all_groups:
        print("group=", group.name)
        all_group_channels = group.channels()
        print(all_group_channels)

        for channel in all_group_channels:
            print("channel=", channel.name)

            # Get a channel property
            property_list = tdms_file[group.name][channel.name].properties
            print("property_list=", property_list, "type(property_list)=", type(property_list))

            all_channel_data = channel[:]
            # print("data=", all_channel_data)

    group = tdms_file['Courants et Ref. Alimentations']
    channel = group['Courant_A1']

    # 'wf_start_time'
    start_timestamp = channel.properties['wf_start_time']
    print("start_time=", start_timestamp)

    # 'wf_start_offset'
    start_offset = channel.properties['wf_start_offset']
    print("start_offset=", start_offset)

    # 'wf_increment'
    increment = channel.properties['wf_increment']
    print("increment=", increment)

    # 'wf_samples'
    samples = channel.properties['wf_samples']
    # 'unit_string'
    time_steps = np.array([i*increment for i in range(0,samples)])

    ax = plt.gca()
    plt.plot(time_steps, channel[:], label="A1")
    plt.plot(time_steps, group['Courant_A2'][:], label="A2")
    plt.ylabel(channel.name + " [" + channel.properties['unit_string'] + "]")
    plt.xlabel("t [s]")
    plt.grid(b=True)
    ax.legend()
    plt.show()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('Data.csv')
x = data.iloc[:,[0]].values
y = data.iloc[:,[1]].values

x_t = np.transpose(x)
first_inv = np.matmul(x_t, x)
second = np.matmul(x_t, y)
first = np.linalg.inv(first_inv)
theta = np.matmul(first, second)
y_prad = theta*x

regressor = LinearRegression()
regressor.fit(x, y)
y_prad2 = regressor.predict(x)
plt.scatter(x, y)
plt.plot(x, y_prad, 'red')
plt.plot(x, y_prad2, 'green')


from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score, davies_bouldin_score

def clustering_k_means(df, columns_clustering, n_clusters=3, label_column_name='label',
                       post_analysis=True, figure_file_path=None, colors_plot=None, metrics=True):
    """
    Perform k-means clustering on a DataFrame using specified columns and optionally conduct post-analysis.

    Args:
        df (pandas.DataFrame): The input DataFrame containing the data to be clustered.
        columns_clustering (list of str): A list of column names in the DataFrame to be used for clustering.
        n_clusters (int, optional): The number of clusters to create. Default is 3.
        label_column_name (str, optional): The name of the column where cluster labels will be added to the DataFrame.
            Default is 'label'.
        post_analysis (bool, optional): Whether to conduct post-analysis and generate density plots. Default is True.
        figure_file_path (str, optional): The file path to save the generated density plot figure.
        colors_plot (list of str, optional): A list of colors for plotting each cluster's density distribution.
        metrics (bool, optional): Whether to compute and return internal evaluation metrics. Default is True.

    Returns:
        pandas.DataFrame: A DataFrame with an additional column containing cluster labels.
        dict or None: A dictionary containing internal evaluation metrics if metrics=True, otherwise None.

    Example:
        >>> data = {
        ...     'feature1': [1.2, 2.5, 3.1, 4.8, 5.2],
        ...     'feature2': [0.9, 1.8, 2.5, 3.7, 4.0]
        ... }
        >>> df = pd.DataFrame(data)
        >>> columns_to_cluster = ['feature1', 'feature2']
        >>> clustered_df, metrics_dict = clustering_k_means(df, columns_to_cluster, n_clusters=2, post_analysis=False)
        >>> print(clustered_df)
           feature1  feature2  label
        0       1.2       0.9      0
        1       2.5       1.8      0
        2       3.1       2.5      0
        3       4.8       3.7      1
        4       5.2       4.0      1
        >>> print(metrics_dict)
        {
            'Silhouette Score': 0.654,
            'Davies-Bouldin Index': 0.529,
            'Inertia': 2.371
        }
    """
    # Obtain dataframe with the variables for clustering
    df_clustering = df[columns_clustering]

    # Standardize data before clustering
    scaler = StandardScaler()
    df_clustering = scaler.fit_transform(df_clustering)

    # Perform k-means clustering for the specified number of clusters
    clustering_kmeans = KMeans(n_clusters=n_clusters, random_state=0, n_init="auto").fit(df_clustering)

    # Add cluster labels to the original dataframe
    df[label_column_name] = list(clustering_kmeans.labels_)

    if post_analysis:
        # Plot density distribution for each variable by clustering label

        # Set up the figure and subplots
        # Calculate the number of rows and columns based on the length of columns_clustering
        num_plots = len(columns_clustering)
        num_cols = min(3, num_plots)
        num_rows = -(-num_plots // num_cols)  # Ceiling division to ensure enough rows

        fig, axe = plt.subplots(nrows=num_rows, ncols=num_cols, figsize=(15, 5))
        # Unpack all the axes subplots
        axes = axe.ravel()

        # Generate colors for plotting if not provided
        if colors_plot is None:
            colors_plot = [plt.cm.jet(i / n_clusters) for i in range(n_clusters)]
        else:
            # Check if the length of colors_plot matches the number of clusters
            if len(colors_plot) != n_clusters:
                raise ValueError("The length of colors_plot must be the same as the number of clusters.")

        # Loop through the continuous variables to create plots
        for i, var in enumerate(columns_clustering):
            ax = axes[i]
            for group_label in df[label_column_name].unique():
                group_data = df[df[label_column_name] == group_label]
                group_color = colors_plot[group_label]
                group_data[var].plot(kind='kde', legend=True, ax=ax, label=group_label, color=group_color)

            # Set title and legend for each subplot
            ax.set_title(f'Density Plot of {var}')
            ax.legend()

        # Add overall title
        title_plot = "Clustering post-analysis"
        fig.suptitle(title_plot, fontsize=16)
        # Adjust layout and save the figure if a file path is provided
        if figure_file_path:
            plt.tight_layout()
            plt.savefig(figure_file_path)
        plt.show()

    if metrics:
        # Compute Silhouette Score (a higher score is better)
        silhouette_avg = silhouette_score(df_clustering, df[label_column_name])

        # Compute Davies-Bouldin Index (lower values are better)
        db_index = davies_bouldin_score(df_clustering, df[label_column_name])

        # Compute Inertia (within-cluster sum of squares) (lower values are better)
        inertia = clustering_kmeans.inertia_

        # Create a dictionary with score information
        score = {
            'Type of Score': ['Silhouette Score', 'Davies-Bouldin Index', 'Inertia'],
            'Range of Values': ['[-1, 1]', '[0, Inf)', '[0, Inf)'],
            'Best Value': ['Higher', 'Lower', 'Lower'],
            'Value for the Score': [silhouette_avg, db_index, inertia]
        }

    return df, score


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 17:49:23 2018
@author: kzeman2

NitroShed Model

"""

from mesa import Agent, Model
import random
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from schedule import model_schedule
#import matplotlib.pyplot as plt

#Agent Classes used in model
from farmer_agent import *
from bmp_agent import *
from community_agent import *
from farmland_agent import *
from environment_agent import *

######## Model Control ##########
"""
A model with some number of farmer agents. Farmers are influence based on
the other agents within the model.These are the CommunityAgent, the
FarmLandAgent, the EnvironmentAgent, and the BMPAgent.

"""
class NitroShedModel(Model):
    """
    Creates the NitroShed Super Class which creates all of the model Agents

    classes used in this model are:
        farmer_agent: creates all of the farmers with typology parameters and
        places them at a location of farmland

        farmland_agent: creates the farmland from information givent from the
        environement agent

        bmp_agent: creates the bmps that can be used by the farmer

        community_agent: creates the community which acts as all other
        stakeholders in the model
        environment_agent: creates the environment HRU's and watershed where
        the model takes place

    """

    print('initalizing Nitroshed Model')

    def __init__(self, Num_Farmers, width, height, bmps_available):
        r"""
        Initializes the model and creates the agents

        Takes in parameters designated from runModel.py to create the farmer
        agents, BMP agents, Farmland agents, community agent and environment
        agent.

        Parameters
        ----------

        Num_Farmers: int
            Number of farmer agents which will be created and run in the model.
            Each farmer has a typology and other inherint traits which can be
            found in farmer_agent.py

        width: int
            designates how wide the model space is

        height: int
            designates how tall the model space is

        bmps_available: int
            gives the number of BMP's that are created in the model. Used in
            the creation of bmp_agent.py

        %%%%%%%%%%%%%

        num_agents: int
        number of farmers created in the model

        grid: matrix

        schedule: class
        function schedule.py that creates the order that the agents in the model are
        called to take a step

        bmps_available:
        int
            gives the number of BMP's that are created in the model. Used in
            the creation of bmp_agent.py

        returns
        -------
        completed model

        """
        self.num_agents = Num_Farmers
        #self.schedule = RandomActivation(self)
        self.grid = MultiGrid(width, height, True)
        self.schedule = model_schedule(self)
        self.bmps_available=bmps_available

        #Create BMP's
        print('Creating BMPs')
        for i in range(self.bmps_available):
            bmp= BMPAgent(i, self)
            self.schedule.add(bmp)

        #Create Environment
        print('Creating EnvironmentAgent')
        env=EnvironmentAgent(self)

        #Creat Community
        print('Creating Community Agent')
        community= CommunityAgent(self)

        # Create agents
        print('Creating Agents')
        for i in range(self.num_agents):
            a = FarmerAgent(i, self)
            self.schedule.add(a)
            b= FarmLandAgent(i, self)
            self.schedule.add(b)

            #Add the agent to a random grid cell
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))
            self.grid.place_agent(b, (x, y))
            print("Farmer:",a.farmer_id,"Capital",a.capital, "location:", a.pos, "Area:", b.area,"Farm Location", b.pos)

    def step(self,i):
        '''Advance the model by one step.'''
        print("model step", i)
        self.schedule.step()


# **hdfs操作
import os
from hdfs import client

#**url：ip：端口
client = client.InsecureClient("http://yh001:50070", user="hadoop" ,root="/")

def upload(remote_dir="/pings/wordcount/", local_dir="D:/data/1/"):
    """上传本地文件到hdfs"""
    client.delete(remote_dir, True)
    client.makedirs(remote_dir)
    for file in os.listdir(local_dir):
        client.upload(remote_dir, local_dir + file)

if __name__ == "__main__":
    upload()
    print(client.list("/"))


def findPeakElement(nums):
        start, end = 0, len(nums) - 1

        minVal = float("-inf")

        while start <= end:
            mid = start + (end  - start) // 2

            # First or last element can be the peak as well
            # But in that case, the previous or next element won't be present in the list
            # So we can take previous and next as negative infinity
            prev = minVal if mid - 1 < 0 else nums[mid - 1]
            next = minVal if mid + 1 > len(nums) - 1 else nums[mid + 1]

            if nums[mid] > prev and nums[mid] > next: return mid

            # If mid element is not peak, then that means either the left side element is bigger
            # Or right side element is bigger
            # Whichever element is bigger among both, go towards that side
            if nums[mid - 1] > nums[mid]: end = mid - 1
            else: start = mid + 1

        return len(nums) - 1

nums = [1,2,1,3,5,6,4]

print("Index of peak element -> ", findPeakElement(nums))


import numpy as np

import torch
import torch.functional as F

def eval_metrics(output, target):
  output = (F.sigmoid(output) > 0.5).cpu().data.numpy()
  target = target.cpu().data.numpy()
  return np.linalg.norm(output - target)

def corr_dist(est, gth, xyz0, xyz1, weight=None, max_dist=1):
  xyz0_est = xyz0 @ est[:3, :3].t() + est[:3, 3]
  xyz0_gth = xyz0 @ gth[:3, :3].t() + gth[:3, 3]
  dists = torch.clamp(torch.sqrt(((xyz0_est - xyz0_gth).pow(2)).sum(1)), max=max_dist)
  if weight is not None:
    dists = weight * dists
  return dists.mean()

def pdist(A, B, dist_type='L2'):
  if dist_type == 'L2':
    D2 = torch.sum((A.unsqueeze(1) - B.unsqueeze(0)).pow(2), 2)
    return torch.sqrt(D2 + 1e-7)
  elif dist_type == 'SquareL2':
    return torch.sum((A.unsqueeze(1) - B.unsqueeze(0)).pow(2), 2)
  else:
    raise NotImplementedError('Not implemented')

def get_loss_fn(loss):
  if loss == 'corr_dist':
    return corr_dist
  else:
    raise ValueError(f'Loss {loss}, not defined')


from front_end_gui_script import print_console_gui
import os
import calendar
import pandas as pd
from datetime import datetime
from datetime import timedelta
from dateutil import relativedelta
import snscrape.modules.twitter as sntwitter

tweet_path = 'tweets'

def initiate_path():
    if not os.path.exists(tweet_path):
        os.mkdir(tweet_path)

def calculate_days_in_month(month, year):
    return calendar.monthrange(year, month)[1]

def calculate_number_of_months(start_date, end_date, date_format):
    start_date = datetime.strptime(str(start_date), date_format)
    end_date = datetime.strptime(str(end_date), date_format)
    r = relativedelta.relativedelta(end_date, start_date)
    return (r.years * 12) + r.months

def add_date_by_days(date, days, date_format):
    date = datetime.strptime(date, date_format)
    date = date + timedelta(days)
    return date.strftime(date_format)

def subtract_date_by_days(date, days, date_format):
    date = datetime.strptime(date, date_format)
    date = date - timedelta(days)
    return date.strftime(date_format)

def calculate_end_date(start_date, date_format):
    if date_format == '%m-%d-%Y':
        return str(start_date[0:2] + '-' + str(calculate_days_in_month(int(start_date[0:2]),\
                                                int(start_date[-4:]))) + '-' + start_date[-4:])
    elif date_format == '%d-%m-%Y':
        return str(str(calculate_days_in_month(int(start_date[3:5]), int(start_date[-4:])))\
                                               + '-' + start_date[3:5] + '-' + start_date[-4:])

def get_twitter_search_string(keyword, start_date, end_date):
     return str(keyword + ' lang:en since:' + str(start_date[-4:]) + '-' + str(start_date[-10:-8])\
                + '-' + str(start_date[-7:-5]) + ' until:' + str(end_date[-4:]) + '-'\
                + str(end_date[-10:-8]) + '-' + str(end_date[-7:-5]))

def get_file_name_string(keyword, end_date):
    end_date = subtract_date_by_days(end_date, 1, '%m-%d-%Y')
    return str(keyword + '_' + str(end_date[-10:-8]) + '-' + str(end_date[-7:-5]) +\
               '-' + str(end_date[-2:]) + '.csv')

def check_tweet_availability(keyword, start_date, end_date):
    try:
        for tweet in enumerate(sntwitter.TwitterSearchScraper\
                        (get_twitter_search_string(keyword, start_date, end_date)).get_items()):
            if tweet:
                return 1
            else:
                return 0
    except:
        print('\nSearch keyword has unsearchable characters, please replace them!\n', flush = True)
        return 0

def tweet_scraper(number_of_tweets_per_month, start_date, end_date, keyword):
    # Using TwitterSearchScraper to scrape data and append tweets to list
    if check_tweet_availability(keyword, start_date, end_date):
        initiate_path()
        final_date = end_date
        months = calculate_number_of_months(start_date, end_date, '%m-%d-%Y')
        for month_count in range(0, months + 1):
            # Creating list to append tweet data to
            tweets_list2 = []
            if not months == month_count:
                end_date = calculate_end_date(start_date, '%m-%d-%Y')
            else:
                end_date = final_date
            for i, tweet in enumerate(sntwitter.TwitterSearchScraper\
                        (get_twitter_search_string(keyword, start_date, end_date)).get_items()):
                if i > number_of_tweets_per_month:
                    break
                tweets_list2.append([tweet.date, tweet.id, tweet.content])
            # Creating a dataframe from the tweets list above
            tweets_df2 = pd.DataFrame(tweets_list2, columns=['Datetime', 'Tweet Id', 'Text'])
            file_name = os.path.join(tweet_path, get_file_name_string(keyword, end_date))
            tweets_df2.to_csv(file_name)
            start_date = add_date_by_days(end_date, 1, '%m-%d-%Y')
        return 0
    else:
        return -1

def main():
    # mm-dd-YYYY format
    start_date = '01-01-2020'
    end_date = '05-24-2021'
    keyword = 'coronavirus'
    number_of_tweets_per_month = 1000
    tweet_scraper(number_of_tweets_per_month, start_date, end_date, keyword)

if __name__ == '__main__':
    main()


N = int(input())
A = list(map(int, input().split()))

mem = [1] * (N+1)

for i in range(0, N):
    for j in range(0, i+1):

        if A[i] > A[j]:
            mem[i] = max(mem[i], mem[j]+1)

print(max(mem))


COMMON_FILES = (
    "common",
)
INIT_FILES = (
    "src/paladin/init.lua",
    "src/priest/init.lua",
)
CLASSES_FILES = (
    "classes",
)
SAVE_SYSTEM_FILES = (
    "libs/SaveSystem/init.lua",
    "libs/SaveSystem/modules",
    "libs/SaveSystem/userData.lua",
    "libs/SaveSystem/heroData.lua",
    "libs/SaveSystem/saveSystem.lua",
    "libs/SaveSystem/heroes.lua",
    "libs/SaveSystem/newHero.lua",
    "libs/SaveSystem/saveHero.lua",
    "libs/SaveSystem/loadHero.lua",
)
EQUIPMENT_SYSTEM_FILES = (
    "libs/EquipmentSystem",
)
BUFF_SYSTEM_FILES = (
    "libs/BuffSystem",
)
BATTLE_SYSTEM_FILES = (
    "libs/battleSystem.lua",
)
WRAPPER_FILES = (
    "libs/wrappers.lua",
)
HERO_SELECTOR_FILES = (
    "libs/HeroSelector/frames_desc.lua",
    "libs/HeroSelector/heroSelector.lua",
)
SOURCE_FILES = (
    "src/abilities.lua",
    "src/dummy",
    "src/enemies",
    "src/lord_marrowgar",
    "src/lady_deathwhisper",
    "src/paladin/spells",
    "src/priest/spells",
)

ALL_SOURCE_FILES = (
    *COMMON_FILES,
    *INIT_FILES,
    *CLASSES_FILES,
    *SAVE_SYSTEM_FILES,
    *EQUIPMENT_SYSTEM_FILES,
    *BUFF_SYSTEM_FILES,
    *BATTLE_SYSTEM_FILES,
    *WRAPPER_FILES,
    *HERO_SELECTOR_FILES,
    *SOURCE_FILES,
)