import os
import csv

def write_csv(file_name, output_path, data, header):

    if not os.path.exists(output_path):
        os.makedirs(output_path)

    with open(output_path + file_name, "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')

        # write header
        writer.writerow(header)

        # write data
        [writer.writerow(x) for x in data]

    return 0


import os
import logging

from more_executors import Executors

from .base import Phase

LOG = logging.getLogger("pubtools.pulp")

CHECKSUM_THREADS = int(os.getenv("PUBTOOLS_PULP_CHECKSUM_THREADS") or "4")

class LoadChecksums(Phase):
    """Phase for loading/calculating checksums of push items.

    Push items may be initially discovered either with checksum information
    (e.g. from Errata Tool) or without (e.g. files in a staging directory).

    In cases where a push item checksum is currently unknown, this phase
    will read the push item's file in order to calculate it. This is handled
    by a dedicated phase since it can be very slow for large content accessed
    via NFS.

    Input queue:
    - items which may or may not have checksum info.

    Output queue:
    - items which have checksums (where the push item type supports that).

    Side-effects:
    - sends updated item states to the Collect phase as soon as checksums
      are known.
    """

    # Outputs of this phase should update push items since this is the first
    # point during a push where we know what the items actually are (in terms
    # of the bytes being pushed...)
    UPDATES_PUSH_ITEMS = True

    def __init__(self, context, in_queue, **kwargs):
        super(LoadChecksums, self).__init__(
            context, in_queue=in_queue, name="Calculate checksums", **kwargs
        )

    def run(self):
        with Executors.thread_pool(
            max_workers=CHECKSUM_THREADS, name="checksummer"
        ) as exc:
            for item in self.iter_input():
                # Use a heuristic to try to hand off the item onto the next
                # phase as quickly as possible.
                #
                # - in general we use a thread pool to do calculations in parallel.
                #
                # - but if we probably already have sums, we don't want to put
                #   that item onto the back of a potentially long queue where it
                #   may have to wait a long time, when it could be passsed on
                #   immediately.
                #
                # Hence we handle some items synchronously and others not.

                LOG.debug(
                    "Calculating checksums (blocking: %s): %s",
                    item.blocking_checksums,
                    item.pushsource_item.name,
                )

                if not item.blocking_checksums:
                    # with_checksums (probably) won't block so just do
                    # it immediately, thus letting the next phase get hold
                    # of the item more quickly.
                    self.put_output(item.with_checksums())

                else:
                    # with_checksums (probably) will block so put it onto
                    # the thread pool's queue.
                    f = exc.submit(item.with_checksums)
                    self.put_future_output(f)


from collections import deque

N, K = map(int,input().split())

# 제거를 N번 pop, enque로 구현.

vector = deque(list(range(1,N+1)))

myword = '<'

for i in range(N-1):
    for j in range(K-1):
        temp = vector.popleft()
        vector.append(temp)
    temp = vector.popleft()
    myword += str(temp) +', '

myword += str(vector.popleft()) + '>'

print(myword)


import torch
import torch.nn as nn
import gpytorch
import numpy as np

class SpectralMixtureGPModel(gpytorch.models.ExactGP):
    """
    Gaussian process model with Spectral Mixture Kernel from Wilson et al. (2013).

    Used for univariate data. In our case, we (train_x, train_y) is a univariate
    time series.

    params:
    ------
        train_x (torch.Tensor): Tensor with the index of the time series
        train_y (torch.Tensor): Tensor with the values of the time series
        num_mixtures (int): Number of mixtures for the kernel.
        likelihood (gpytorch.likelihoods): Likelihood for the problem. For a
        real-valued time series, we use GaussianLikelihood().
    """
    def __init__(self, train_x, train_y, num_mixtures, likelihood):
        super(SpectralMixtureGPModel, self).__init__(train_x, train_y, likelihood)
        self.mean_module = gpytorch.means.ConstantMean()
        self.covar_module = gpytorch.kernels.SpectralMixtureKernel(num_mixtures=num_mixtures)
        self.covar_module.initialize_from_data_empspect(train_x, train_y)

    def forward(self, x):
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)

class GRUFeatureExtractor(nn.Module):
    def __init__(self, input_dim, hidden_dim, num_layers):
        super(GRUFeatureExtractor, self).__init__()
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.gru = nn.GRU(input_dim, hidden_dim, num_layers)

    def forward(self, x):
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
        out, _ = self.gru(x, h0)
        out = out.reshape(out.shape[0], -1)
        return out

class LSTMFeatureExtractor(nn.Module):
    def __init__(self, input_dim, hidden_dim, num_layers):
        super(LSTMFeatureExtractor, self).__init__()
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, bidirectional=False)

    def forward(self, x):
        h0 = torch.zeros(self.num_layers, x.size(1), self.hidden_dim)
        c0 = torch.zeros(self.num_layers, x.size(1), self.hidden_dim)
        out, _ = self.lstm(x, (h0, c0))
        out = out.reshape(out.shape[0], -1)
        return out

def create_sequences(x, sequence_length):
    """
    Creates a transformed dataset for the LSTM with a new sequence length.
    """
    x_seq, y_seq = [], []
    for i in range(len(x) -sequence_length):
        x_seq.append(x[i: i + sequence_length])
        y_seq.append(x[i+1: i + sequence_length + 1])
    x_seq = np.array(x_seq).reshape(-1, sequence_length)
    y_seq = np.array(y_seq).reshape(-1, sequence_length)
    return x_seq, y_seq

if __name__ == '__main__':
    # generate univariate data
    y = np.random.normal(0, 1, 120)
    sequence_length = 5

    test_x, test_y = create_sequences(y, sequence_length=5)
    print(test_x)
    print(test_y.shape)

    # convert to Tensor and reshape to (seq, batch, dim)
    y = torch.Tensor(torch.from_numpy(test_y).float())
    y = y.view([len(y), -1, 5])
    print(y.size())

    # test forward method
    model = LSTMFeatureExtractor(input_dim=5, hidden_dim=16, num_layers=2)
    yhat = model(y)
    print(yhat)


import json
import sys

import pm4py
from pm4py.util import xes_constants as xes

from constants import PATH

def get_all_event_attributes_from_log(log):
    """
    Get all events attributes from the log

    Parameters
    -------------
    log
        Log

    Returns
    -------------
    all_attributes
        All trace attributes from the log
    """
    all_attributes = set()
    for trace in log:
        for event in trace:
            all_attributes = all_attributes.union(set(event.keys()))
    if xes.DEFAULT_TRANSITION_KEY in all_attributes:
        all_attributes.remove(xes.DEFAULT_TRANSITION_KEY)
    return all_attributes

def get_all_event_attributes_values_from_log(log, attrName):
    """
    Get all events attributes from the log

    Parameters
    -------------
    log
        Log

    Returns
    -------------
    all_attributes
        All trace attributes from the log
    """
    all_attributes = set()
    for trace in log:
        for event in trace:
            sett = event.get(attrName)
            if sett:
                all_attributes = all_attributes.union([event[attrName]])
    if xes.DEFAULT_TRANSITION_KEY in all_attributes:
        all_attributes.remove(xes.DEFAULT_TRANSITION_KEY)
    return all_attributes

if __name__ == "__main__":
    file_name = sys.argv[1]
    log = pm4py.read_xes(PATH + "logs/" + file_name)

    event_attributes = get_all_event_attributes_from_log(log)
    filtered = [x for x in event_attributes if x != 'concept:name' and x != 'time:timestamp']

    res = {}
    for attr_name in filtered:
        values = get_all_event_attributes_values_from_log(log, attr_name)
        if any(isinstance(value, str) for value in values):
            res[attr_name] = 'literal'
        elif any(isinstance(value, int) or isinstance(value, float) for value in values):
            res[attr_name] = 'number'
        elif any(isinstance(value, bool) for value in values):
            res[attr_name] = 'boolean'

    print(json.dumps(res))


"""A extension for geojson."""
import warnings
from collections import namedtuple

from django_echarts.custom_maps import use_custom_map, custom_map_url

__all__ = ['use_geojson', 'geojson_url']

warnings.warn('The django_echarts.geojson is deprecated.Use django_echarts.custom_maps instead.', DeprecationWarning)

GeojsonItem = namedtuple('GeojsonItem', 'map_name url')

def use_geojson(chart_obj, map_name: str, url: str = None):
    """Register and use geojson map for a chart."""
    use_custom_map(chart_obj, map_name, url)

def geojson_url(geojson_name: str) -> str:
    """Get default url for a geojson file."""
    return custom_map_url(geojson_name)


import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Load the movie data
movies_df = pd.read_csv("movies.csv")

# Create a TF-IDF matrix for the movie descriptions
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(movies_df["plot"].values)

# Calculate the cosine similarity between all movies
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)

# Get the recommendations for a particular movie
movie_title = "The Shawshank Redemption"
movie_index = movies_df[movies_df["title"] == movie_title].index[0]

# Get the top 10 most similar movies
recommendations = []
for i in range(10):
    similar_movie_index = cosine_sim[movie_index].argsort()[-i - 1]
    similar_movie_title = movies_df.iloc[similar_movie_index]["title"]
    recommendations.append(similar_movie_title)

print("Recommendations for " + movie_title + ":")
print(recommendations)


"""Common functionalities for various data models"""
from common.utils.parent_child_nodes_handler import ParentChildNodesHandler

class CommonAPIHandler:
  """Class containing common functions used by various data models"""

  @classmethod
  def update_document(cls, collection, uuid, request_body):
    """Updates the document with given uuid"""
    existing_doc_object = collection.find_by_uuid(uuid)
    existing_doc_object_dict = existing_doc_object.get_fields()
    update_fields = [key for key in existing_doc_object_dict.keys()\
       if isinstance(existing_doc_object_dict[key], dict)]
    for field in update_fields:
      if request_body[field] is None:
        request_body[field] = existing_doc_object_dict[field]
      else:
        for key, val in request_body[field].items():
          if val is None:
            request_body[field][key] = \
              existing_doc_object_dict[field].get(key,[])
    ParentChildNodesHandler.compare_and_update_nodes_references(
        request_body, existing_doc_object_dict, collection)
    for key, value in request_body.items():
      if value is not None:
        setattr(existing_doc_object, key, value)
      existing_doc_object.update()

    updated_doc_fields = \
        existing_doc_object.get_fields(reformat_datetime=True)

    return updated_doc_fields

  @classmethod
  def update_and_create_version(cls, collection, uuid, request_body):
    """
      Creates a new version of the document for the given uuid
      and update references
    """
    existing_doc_object = collection.find_by_uuid(uuid)
    existing_doc_object_dict = existing_doc_object.get_fields()
    update_fields = [key for key in existing_doc_object_dict.keys()\
       if isinstance(existing_doc_object_dict[key], dict)]
    for field in update_fields:
      if request_body[field] is None:
        request_body[field] = existing_doc_object_dict[field]
      else:
        for key, val in request_body[field].items():
          if val is None:
            request_body[field][key] = \
              existing_doc_object_dict[field][key]
    # Creating a versioned doc
    versioned_doc = collection()
    versioned_doc = versioned_doc.from_dict(request_body)

    # Code to find the correct version number
    collection_manager = collection.collection
    collection_manager = collection_manager.filter(
        "root_version_uuid", "==",
        existing_doc_object.root_version_uuid)
    documents = collection_manager.order("-version").fetch(1)
    latest_document = [i.get_fields(reformat_datetime=True) for i in documents
                      ][0]
    versioned_doc.version = latest_document["version"] + 1
    versioned_doc.parent_version_uuid = uuid

    ParentChildNodesHandler.validate_parent_child_nodes_references(request_body)
    for key, value in request_body.items():
      if value is not None:
        setattr(versioned_doc, key, value)
    versioned_doc.uuid = ""
    versioned_doc.save()
    versioned_doc.uuid = versioned_doc.id
    versioned_doc.update()
    updated_doc_fields = versioned_doc.get_fields(reformat_datetime=True)
    ParentChildNodesHandler.update_child_references(
        updated_doc_fields, collection, operation="add")
    ParentChildNodesHandler.update_parent_references(
        updated_doc_fields, collection, operation="add")
    return updated_doc_fields

  @classmethod
  def create_copy(cls, collection, uuid):
    """Function to create COPY of a documnent"""
    doc = collection.find_by_uuid(uuid)
    doc_dict = doc.get_fields\
      (reformat_datetime=True)
    del doc_dict["uuid"]
    del doc_dict["created_time"]
    del doc_dict["last_modified_time"]
    if doc_dict.get("last_published_on") is not None:
      del doc_dict["last_published_on"]
    ParentChildNodesHandler.validate_parent_child_nodes_references(doc_dict)
    doc_dict["version"] = 1

    copy_doc = collection()
    copy_doc = copy_doc.from_dict(doc_dict)
    copy_doc.uuid = ""
    copy_doc = cls.check_item_is_locked(copy_doc)

    copy_doc.save()
    copy_doc.uuid = copy_doc.id
    copy_doc.root_version_uuid = \
      copy_doc.id
    copy_doc.update()
    copy_doc_fields = copy_doc.get_fields(reformat_datetime=True)
    ParentChildNodesHandler.update_child_references(
        copy_doc_fields, collection, operation="add")
    ParentChildNodesHandler.update_parent_references(
        copy_doc_fields, collection, operation="add")
    return copy_doc_fields

  @classmethod
  def check_item_is_locked(cls, item):
    """Function to assign is_locked flag to items
    in Learning Hierarchy upon creation"""
    item.is_locked = False
    if item.prerequisites:
      for prereq_level in item.prerequisites:
        if item.prerequisites[prereq_level]:
          item.is_locked = True
          break
    return item

  @classmethod
  def create_versioned_document(cls, collection, uuid, request_body):
    """
      Creates a new version of the document for the given uuid
      without updating the references
    """
    existing_doc_object = collection.find_by_uuid(uuid)
    existing_doc_object_dict = existing_doc_object.get_fields()

    update_fields = [key for key in existing_doc_object_dict.keys()\
       if isinstance(existing_doc_object_dict[key], dict)]
    for field in update_fields:
      if request_body.get(field) is None:
        request_body[field] = existing_doc_object_dict[field]
      else:
        for key, val in request_body[field].items():
          if val is None:
            request_body[field][key] = \
              existing_doc_object_dict[field][key]

    # Creating a versioned doc
    versioned_doc = collection()
    versioned_doc = versioned_doc.from_dict(existing_doc_object_dict)

    # Code to find the correct version number
    collection_manager = collection.collection
    collection_manager = collection_manager.filter(
        "root_version_uuid", "==",
        existing_doc_object.root_version_uuid)
    documents = collection_manager.order("-version").fetch(1)
    latest_document = [i.get_fields(reformat_datetime=True) for i in documents
                      ][0]
    versioned_doc.version = latest_document["version"] + 1
    versioned_doc.parent_version_uuid = uuid
    for key, value in request_body.items():
      if value is not None:
        setattr(versioned_doc, key, value)
    versioned_doc.save()
    versioned_doc.uuid = versioned_doc.id
    versioned_doc.is_implicit = True
    versioned_doc.update()
    updated_doc_fields = versioned_doc.get_fields(reformat_datetime=True)

    return updated_doc_fields

  @classmethod
  def remove_uuid_from_prerequisites(cls, collection, key, uuid):
    """
    This method removes the given 'uuid' from the given 'key' field in
    prerequisites of all the documents in the given 'collection'.
    """
    docs = collection.collection.fetch()
    for doc in docs:
      doc_dict = doc.to_dict()
      prerequisites = doc_dict.get("prerequisites", {})
      if prerequisites:
        key_field = prerequisites.get(key, [])
        if key_field and uuid in key_field:
          doc.prerequisites[key].remove(uuid)
          doc.update()


import os
import sys
import traceback
import codecs
import logging
import random
import time
import rdflib
import dateutil.parser

from optparse    import OptionParser
from nltools     import misc
from config      import RDF_PREFIXES

DEFAULT_OUTPUT     = 'bar.pl'
DEFAULT_LOGLEVEL   = logging.INFO
LEM_FN             = 'etc/lem.csv'
LPM_FN             = 'etc/lpm.csv'
RDF_SCHEMA_LABEL   = rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label')
LANGUAGES          = set([u'en', u'de'])
LEGAL_ENTITY_CHARS = set(u"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöùúûüý")

def mangle_prolog(n, start_uppercase=False):

    res = u''
    make_upper = start_uppercase # to enforce CamelCase

    for c in n:
        if not c.isalnum():
            make_upper = True
            continue
        if make_upper:
            c = c.upper()
            make_upper=False

        if c in LEGAL_ENTITY_CHARS:
            res += c
        else:
            res += u"U%d" % ord(c)
    return res

def mangle_url(s, do_exc=True):
    prefix = None
    for p, url in RDF_PREFIXES.items():
        if not s.startswith(url):
            continue
        n      = s[len(url):]
        prefix = p
        break

    if not prefix:
        if do_exc:
            raise Exception ('no prefix for %s found' % s)
        return None

    return prefix + mangle_prolog(n, start_uppercase=True)

def entity_label(s, label):

    prefix = None
    for p, url in RDF_PREFIXES.items():
        if not s.startswith(url):
            continue
        prefix = p
        break

    if not prefix:
        raise Exception ('no prefix for %s found' % s)

    l = prefix + mangle_prolog(label, start_uppercase=True)

    return l[:100]

def property2entity_mapper(p):

    up = unicode(p)

    if up.startswith('http://www.wikidata.org/prop/direct/'):
        return 'wdpd', rdflib.URIRef('http://www.wikidata.org/entity/' + p[36:])
    if up.startswith('http://www.wikidata.org/qualifier/'):
        return 'wdpq', rdflib.URIRef('http://www.wikidata.org/entity/' + p[34:])
    if up.startswith('http://www.wikidata.org/prop/statement/'):
        return 'wdps', rdflib.URIRef('http://www.wikidata.org/entity/' + p[39:])
    if up.startswith('http://www.wikidata.org/prop/'):
        return 'wdp', rdflib.URIRef('http://www.wikidata.org/entity/' + p[29:])
    return None, None

def property_label(p):

    global lpm, plm, g

    if p in plm:
        return plm[p]

    prefix, pe = property2entity_mapper(p)
    if not pe:

        l = mangle_url(p)

    else:

        triples = list(g.triples((pe, RDF_SCHEMA_LABEL, None)))

        l      = None
        for t in triples:

            s, p2, o = t

            if o.language != 'en':
                continue

            l = prefix + mangle_prolog(unicode(o), start_uppercase=True)

        if not l:
            return None

    # make unique

    label = l
    cnt = 1
    while label in lpm and lpm[label] != p:
        label = l + unicode(cnt)
        cnt += 1

    lpm[label] = p
    plm[p]     = label

    return label

#
# init, cmdline
#

misc.init_app('rdf2prolog')

parser = OptionParser("usage: %prog [options] foo.n3")

parser.add_option ("-v", "--verbose", action="store_true", dest="verbose",
                   help="verbose output")
parser.add_option ("-o", "--output", dest="outputfn", type = "string", default=DEFAULT_OUTPUT,
                   help="output file, default: %s" % DEFAULT_OUTPUT)

(options, args) = parser.parse_args()

if len(args) != 1:
    parser.print_usage()
    sys.exit(1)

if options.verbose:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

inputfn  = args[0]
outputfn = options.outputfn

#
# get everything
#

logging.info ('parsing %s ...' % inputfn)

g = rdflib.Graph()
g.parse(inputfn, format='n3')

logging.info ('parsing %s ... extracting triples ...' % inputfn)
triples = list(g)

logging.info ('parsing %s ... extracting triples ... got %d triples.' % (inputfn, len(triples)))

#
# entity labels
#

lem = {} # label -> entity
elm = {} # entity -> label

#
# read existing entity labels
#

if os.path.isfile(LEM_FN):

    with codecs.open(LEM_FN, 'r', 'utf8') as f:

        while True:

            line = f.readline()
            if not line:
                break

            line = line.strip()
            if len(line)==0:
                continue

            if 'Unlabeled' in line:
                logging.info ('ignoring line: %s' % line)
                continue

            if 'unlabeled' in line:
                logging.info ('ignoring line: %s' % line)
                continue

            parts = line.split(',')
            elu = mangle_prolog(parts[0])
            entity = rdflib.URIRef(u','.join(parts[1:]))

            if elu in lem:
                raise Exception (u'error while parsing %s: entity label %s is not unique!' % (LEM_FN, elu))

            lem[elu]    = entity
            elm[entity] = elu

#
# generate missing entity labels from rdfsLabels
#

for t in triples:

    s, p, o = t

    if s in elm:
        continue

    label_base = None

    # 1: see if we have an rdfsLabel

    for s2, p2, o2 in g.triples((s, RDF_SCHEMA_LABEL, None)):
        if not isinstance(o2, rdflib.Literal) or o2.language != 'en':
            continue
        label_base = unicode(o2)
        break

    if label_base:
        el = entity_label (s, label_base)
    else:
        el = mangle_url(unicode(s))

    # ensure label is unique

    elu = el

    cnt = 1
    while elu in lem and lem[elu] != s:
        elu = el + unicode(cnt)
        cnt += 1

    lem[elu] = s
    elm[s]   = elu

    #print s, elu

logging.debug ('have unique labels for %d entities' % len(lem))

#
# load existing property labels
#

lpm = {} # label    -> property
plm = {} # property -> label

if os.path.isfile(LPM_FN):
    with codecs.open(LPM_FN, 'r', 'utf8') as f:

        while True:

            line = f.readline()
            if not line:
                break

            line = line.strip()
            if len(line)==0:
                continue

            parts = line.split(',')
            label = parts[0]
            prop  = rdflib.URIRef(u','.join(parts[1:]))

            if label in lpm:
                raise Exception (u'error while parsing %s: entity label %s is not unique!' % (LEM_FN, elu))

            lpm[label] = prop
            plm[prop]  = label

def prolog_string_escape (o):

    s = unicode(o)
    # s = s.replace('\\',' ').replace ("'", "\\'")
    s = s.replace('\\',' ').replace ('"', '\\"')

    return s

#
# generate prolog, generate and cache property labels as we encounter them
#

cnt = 0

prolog_code = []
predicate_set = set()
for elu in lem:

    entity = lem[elu]

    cnt += 1

    triples = list(g.triples((entity, None, None)))

    if len(triples)==0:
        continue

    logging.info ('%5d/%5d generating prolog code for %s ...' % (cnt, len(lem), elu))

    # f.write(u'\n%% URI: %s\n\n' % unicode(entity))

    for s, p, o in triples:

        if not s in elm:
            continue
        el = elm[s]

        try:
            el.decode('ascii')
        except UnicodeDecodeError:
            el = u"'" + el + u"'"

        pl = property_label(p)
        if not pl:
            logging.debug (u'Skipping1: %s(%s, %s).\n' % (unicode(p), el, unicode(o)))
            continue

        try:

            if isinstance(o, rdflib.term.Literal):
                if o.datatype:

                    datatype = str(o.datatype)

                    if datatype == 'http://www.w3.org/2001/XMLSchema#decimal':
                        prolog_code.append(u"%s(%s, %s).\n" % (pl, el, unicode(o)))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.w3.org/2001/XMLSchema#float':
                        prolog_code.append(u"%s(%s, %s).\n" % (pl, el, unicode(o)))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.w3.org/2001/XMLSchema#integer':
                        prolog_code.append(u"%s(%s, %s).\n" % (pl, el, unicode(o)))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.w3.org/2001/XMLSchema#dateTime':
                        dt = dateutil.parser.parse(unicode(o))
                        prolog_code.append(u'%s(%s, "%s").\n' % (pl, el, dt.isoformat()))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.w3.org/2001/XMLSchema#date':
                        dt = dateutil.parser.parse(unicode(o))
                        prolog_code.append(u'%s(%s, "%s").\n' % (pl, el, dt.isoformat()))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.opengis.net/ont/geosparql#wktLiteral':
                        # FIXME
                        prolog_code.append(u'%s(%s, "%s").\n' % (pl, el, unicode(o)))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    elif datatype == 'http://www.w3.org/1998/Math/MathML':
                        # FIXME
                        continue

                    else:
                        raise Exception('unknown literal datatype %s (value: %s) .' % (datatype, unicode(o)))
                else:
                    if o.value is None:
                        prolog_code.append(u"%s(%s, []).\n" % (pl, el))
                        predicate_set.add(u'%s/2' % pl)
                        continue
                    if o.language:
                        if o.language in LANGUAGES:
                            prolog_code.append(u'%s(%s, %s, "%s").\n' % (pl, el, o.language, prolog_string_escape(o)))
                            predicate_set.add(u'%s/3' % pl)
                        continue

                    prolog_code.append(u'%s(%s, "%s").\n' % (pl, el, prolog_string_escape(o)))
                    predicate_set.add(u'%s/2' % pl)
                    continue

            elif isinstance (o, rdflib.term.URIRef):
                if o in elm:
                    ol = elm[o]
                else:
                    # ol = u"'" + unicode(o) + "'"
                    ol = mangle_url(str(o), do_exc=False)
                if not ol:
                    logging.debug (u'Skipping2: %s(%s, %s).\n' % (pl, el, unicode(o)))
                    continue

                try:
                    ol.decode('ascii')
                except UnicodeDecodeError:
                    ol = u"'" + ol + u"'"

                prolog_code.append(u"%s(%s, %s).\n" % (pl, el, ol))
                predicate_set.add(u'%s/2' % pl)
            else:
                raise Exception ('unknown term: %s (%s %s)' % (unicode(o), type(o), o.__class__))
        except:
            logging.error(u'Failed to convert %s: %s' % (unicode(o), traceback.format_exc()))

with codecs.open(outputfn, 'w', 'utf8') as f:

    f.write('%prolog\n')

    for p in sorted(predicate_set):
        f.write(u':- multifile %s.\n' % p)

    f.write('\n')

    for pc in sorted(prolog_code):
        f.write(pc)

logging.info (' %s written' % outputfn)

#
# dump out all property and entity labels to keep them the same in future runs
#

with codecs.open(LPM_FN, 'w', 'utf8') as f:
    for plu in sorted(lpm):
        if 'Unlabeled' in plu:
            continue
        if 'unlabeled' in plu:
            continue
        prop = lpm[plu]
        f.write(u'%s,%s\n' % (plu, prop))

logging.info (' %s written' % LPM_FN)

with codecs.open(LEM_FN, 'w', 'utf8') as f:
    for elu in sorted(lem):
        if 'Unlabeled' in elu:
            continue
        if 'unlabeled' in elu:
            continue
        entity = lem[elu]
        f.write(u'%s,%s\n' % (elu, unicode(entity)))

logging.info (' %s written' % LEM_FN)


from functools import reduce
from random import randrange
from itertools import repeat

# parametros

k = 3
maxit = 10

# declaracion de funciones

def deuclidea(x, y):
   return sum(map(lambda a, b: (float(a) - float(b)) ** 2,
                  x, y)) ** 0.5

def contar(l):
   p = {}
   for x in l:
      p.setdefault(x, 0)
      p[x] += 1
   return p

def classify(t):
   ds = [deuclidea(centroides[i][1], t)
         for i in range(len(centroides))]
   return min([(ds[i], centroides[i][0])
               for i in range(len(centroides))],
              key=lambda x: x[0])[1]

def nextCentr(l):
   if (l == []):
      return None
   else:
      if len(l)==1:
         return l[0][2]
      else:
         tot2 = list(zip(*[x[2] for x in l]))
         num = len(tot2[0])
         return list(map(lambda l: reduce(lambda a, b:
                                       float(a) + float(b), l)
                      / num, list(tot2)))

def kmeans(clase, k, maxit):
   filt = list(filter(lambda x: x[0] == x[1],
                    [(clasesTrain[i], clase, train[i])
                     for i in range(len(train))]))
   conj = [filt[i][2] for i in range(len(filt))]
   centr = [conj[randrange(len(conj))] for i in range(k)]
   anteriores = None
   for it in range(maxit):
      cercanos = [min(zip(*[list(map(deuclidea,
                                     repeat(ej, k),
                                     centr)), range(k)]))[1]
                  for ej in conj]
      centr2 = [nextCentr(list(filter(
         lambda x: x[0] == x[1],
         zip(*[list(repeat(c, len(conj))),
               cercanos, conj]))))
                for c in range(k)]
      if None in centr2: break
      if cercanos == anteriores: break
      anteriores = cercanos

   return [(clase, x) for x in filter(lambda x: x!=None, centr2)]

# carga del archivo
l = list(map(lambda l: (l.strip()).split(','),
             open('iris.data.txt', 'r').readlines()))

# construccion del training: 2 de cada 3
train = list(map(lambda x: x[1],
                 filter(lambda v: v[0] % 3 != 0, enumerate(l))))
nc = len(train[0])
clasesTrain = list(map(lambda x: x.pop(nc - 1), train))

# construccion del test: 1 de cada 3
test = list(map(lambda x: x[1],
                filter(lambda v: v[0] % 3 == 0, enumerate(l))))
clasesTest = list(map(lambda x: x.pop(nc - 1), test))

# Entrenamiento
clases = contar(clasesTrain)
centroides = reduce(lambda x, y: x + y,
                    [kmeans(c, k, maxit) for c in clases.keys()])

# Clasificacion
predicciones = list(map(classify, test))

# Numero de correctos
print('Prec.:',
      len(list(filter(lambda x: x[0] == x[1],
                      zip(*[predicciones, clasesTest]))))
      / len(test) * 100, '%')


# This file describes an instance of the problem. It has the following format:

# [number_of_symbols]

# [weight of symbol #1]

# [weight of symbol #2]

# ...

# For example, the third line of the file is "6852892," indicating that the weight of the second symbol of the alphabet is 6852892.  (We're using weights instead of frequencies, like in the "A More Complex Example" video.)

# Your task in this problem is to run the Huffman coding algorithm from lecture on this data set.

# Questions
# What is the maximum length of a codeword in the resulting Huffman code?
# What is the minimum length of a codeword in your Huffman code?

# 11.16.21 Tue
# Next step: read princeton algo4 ch5.5

# 11.17.21 Wed
# Read algo4; not very useful for this assignment;
# Tried to read the textbook; Focused on a smaller problem;
# Next step: think about the straightforward implementation of the "main loop"

# 11.18.21 Thu
# Need min/max depth of a tree
# Next step: work on the binary tree!
# worked out a version that JUST answers the questions

import sys
from tree import Tree

def mergeTree(T1,T2):
    T3 = Tree()
    T3.root.left  = T1.root
    T3.root.right = T2.root
    return T3

def huffman(freq):
    # Initialization
    F = {}
    for a in range(1,len(freq)):
        T = Tree()
        F[T] = freq[a]

    # Main loop
    while len(F) > 1:
        F_sorted = sorted(F.items(), key=lambda x: x[1])
        T1, pT1 = F_sorted[0][0], F_sorted[0][1]
        T2, pT2 = F_sorted[1][0], F_sorted[1][1]
        del F[T1]
        del F[T2]
        T3 = mergeTree(T1,T2)
        pT3 = pT1 + pT2
        F[T3] = pT3
    return list(F.keys())[0]

def readFreq(filename):
    with open(filename,'r') as f:
        lines = f.readlines()
        for j in range(len(lines)):
            lines[j] = int(lines[j].strip())
    # print(lines[:5])
    return lines

def main():
    print('greedy huffman.')
    print('read data from file first.')
    filename = sys.argv[1]
    freq = readFreq(filename)
    print(freq[:5])

    F = huffman(freq)
    # print(F)
    mindepth = F.minDepth(F.root)
    maxdepth = F.maxDepth(F.root)

    print(mindepth)
    print(maxdepth)

if __name__ == '__main__':
	main()


def encode(message: str, key: int) -> str:
    """
        :param message: wiadomość do zaszyfrowania
        :param key: klucz
        :return: zaszyfrowana wiadomość
        """
    encoded = ""

    for k in range(key):
        if k == key - 1:
            jump = (key - 1) * 2
        else:
            jump = (key - (k + 1)) * 2

        i = k

        while i < len(message):
            encoded += message[i]
            i += jump

    return encoded

message = "computer science"

encoded = encode(message, 3)

print(f"Encoded: {encoded}")


import time

import dolfinx
import dolfiny
import numpy
import pytest
import ufl
from mpi4py import MPI
from petsc4py import PETSc

N = 10
mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, N, N, N)

DG0 = dolfinx.fem.FunctionSpace(mesh, ("DP", 0))
DG1 = dolfinx.fem.FunctionSpace(mesh, ("DP", 1))
CG1 = dolfinx.fem.FunctionSpace(mesh, ("P", 1))
TCG1 = dolfinx.fem.TensorFunctionSpace(mesh, ("P", 1))
TDG0 = dolfinx.fem.TensorFunctionSpace(mesh, ("DP", 0))
TDG1s = dolfinx.fem.TensorFunctionSpace(mesh, ("DP", 1), symmetry=True)
TDG2s = dolfinx.fem.TensorFunctionSpace(mesh, ("DP", 2), symmetry=True)

CG2 = dolfinx.fem.FunctionSpace(mesh, ("P", 2))
VCG1 = dolfinx.fem.FunctionSpace(mesh, DG0.mesh.ufl_domain().ufl_coordinate_element())

f = dolfinx.fem.Function(TCG1)
f.vector.set(1.0)
f.vector.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD)

x = ufl.SpatialCoordinate(mesh)
expr1 = f[0, 0] * ufl.grad(ufl.grad(ufl.sinh(x[0]) + x[1] ** 3))

@pytest.mark.parametrize("V", [TCG1, TDG0, TDG1s, TDG2s])
def test_expr(V):

    # Interpolate
    h_interp = dolfinx.fem.Function(V)
    dolfiny.interpolation.interpolate(expr1, h_interp)

    # Project
    h_project = dolfinx.fem.Function(V)
    dolfiny.projection.project(expr1, h_project)

    # Compare
    h_project.vector.axpy(-1.0, h_interp.vector)
    h_project.vector.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD)

    assert h_project.vector.norm() < 0.15

def test_diff():
    f = dolfinx.fem.Function(CG1)
    f.vector.set(1.0)
    f.vector.ghostUpdate()

    x = ufl.SpatialCoordinate(mesh)
    expr = x[0] + x[1] + f

    h_project = dolfinx.fem.Function(CG1)
    dolfiny.projection.project(expr, h_project)

    h_interp = dolfinx.fem.Function(CG1)
    dolfiny.interpolation.interpolate(expr, h_interp)

    diff = dolfinx.fem.Function(CG1)
    dolfiny.interpolation.interpolate(h_interp - h_project, diff)

    assert diff.vector.norm(3) < 1.0e-3

def test_perf():
    N = 500
    mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, N, N)

    P1 = dolfinx.fem.FunctionSpace(mesh, ("P", 1))
    P2 = dolfinx.fem.FunctionSpace(mesh, ("P", 2))

    u1 = dolfinx.fem.Function(P1)
    u2 = dolfinx.fem.Function(P2)

    t0 = time.time()
    dolfiny.interpolation.interpolate(u1, u2)
    print("Cold", time.time() - t0)

    t0 = time.time()
    dolfiny.interpolation.interpolate(u1, u2)
    print("Hot", time.time() - t0)

def test_linear_combination():
    N = 100
    mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, N, N)

    P1 = dolfinx.fem.FunctionSpace(mesh, ("P", 1))

    u1 = dolfinx.fem.Function(P1)
    u2 = dolfinx.fem.Function(P1)
    u3 = dolfinx.fem.Function(P1)

    f = dolfinx.fem.Function(P1)
    g = dolfinx.fem.Function(P1)

    with u1.vector.localForm() as local:
        local.set(1.0)
    with u2.vector.localForm() as local:
        local.set(2.0)
    with u3.vector.localForm() as local:
        local.set(3.0)

    c1 = dolfinx.fem.Constant(mesh, 3.14)
    c2 = dolfinx.fem.Constant(mesh, 0.1)

    expr = (c1 + c2) * (2.0 * (3.0 * u1 + u2) - u3 / 3.0 + 4 * (u1 + c2 * u3))

    t0 = time.time()
    dolfiny.interpolation.interpolate(expr, f)
    print(f"Linear combination {time.time() - t0}")

    t0 = time.time()
    compiled_expression = dolfiny.interpolation.CompiledExpression(expr, g.function_space.ufl_element())
    dolfiny.interpolation.interpolate_compiled(compiled_expression, g)
    print(f"Compiled interpolation {time.time() - t0}")

    assert numpy.isclose((g.vector - f.vector).norm(), 0.0)


import mimetypes
from markdown_it import MarkdownIt
from flask import Flask, url_for, abort, render_template, Response
from pathlib import Path
from urllib.parse import urlparse
import html

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

app = Flask(__name__)

BASE_PATH = Path(__file__).parent

ARTICLES_PATH = BASE_PATH / 'articles'
IMAGES_PATH = BASE_PATH / 'static/images'

def highlighter(code, lang_name, lang_attrs):
    if not lang_name:
        return html.escape(code)

    lexer = get_lexer_by_name(lang_name, stripall=True)
    formatter = HtmlFormatter(nowrap=True)
    return highlight(code, lexer, formatter)

def render_img(self, tokens, idx, options, env):
    [token] = tokens

    src = token.attrs['src']
    alt_text = token.content
    title = token.attrs.get('title')

    src_parse = urlparse(src)
    alt_text = html.escape(alt_text, quote=True)

    if title:
        title_part = f'title="{html.escape(title, quote=True)}"'
    else:
        title_part = ""

    if not src_parse.netloc:
        filename = Path(src_parse.path).name
        src = url_for('article_image', filename=filename)
        src = html.escape(src, quote=True)
        return f'\n\n'

    src = html.escape(src, quote=True)
    return f'\n\n'

def render_html(path):
    """Render html content from markdown file
    """
    try:
        file = open(path, mode='r', encoding='UTF-8')
    except FileNotFoundError:
        return abort(404)

    with file:
        md_content = file.read()

    renderer = MarkdownIt("commonmark", {"highlight": highlighter})
    renderer.add_render_rule("image", render_img)
    return renderer.render(md_content)

@app.route('/')
def index():
    """Start page with list of articles."""
    concepts_path = ARTICLES_PATH / 'python_concepts.md'
    paths = sorted(ARTICLES_PATH.glob('*.md'))
    post_info = []

    for path in paths:
        with open(path, encoding='utf-8') as file:
            title = file.readline()
            if not title.startswith("#"):
                raise ValueError("Post must begin with a title.")

        slug = path.stem
        title = title.lstrip("# ").strip()
        post_info.append((slug, title))
        concepts = render_html(concepts_path)

    return render_template(
        'index.html', post_info=post_info, concepts=concepts
    )

@app.route('/<slug>/')
def post(slug):
    path = ARTICLES_PATH / f'{slug}.md'
    html_content = render_html(path)

    return render_template('post.html', content=html_content)

@app.route('/article_image/<filename>')
def article_image(filename):
    """Route to returns images saved in static/images"""
    img_path = IMAGES_PATH / filename
    (mimetype, encoding) = mimetypes.guess_type(filename)
    if mimetype:
        img_bytes = img_path.read_bytes()

        return Response(img_bytes, mimetype=mimetype)

    return None


from unittest.mock import Mock, patch

import pytest
from chainsail.common.spec import JobSpec
from chainsail.scheduler.config import GeneralNodeConfig, K8sNodeConfig, SchedulerConfig
from chainsail.scheduler.nodes.base import NodeStatus, NodeType

@pytest.fixture
def mock_scheduler_config():
    config = GeneralNodeConfig(
        image="foo:latest",
        cmd="bash",
        args=["-c", "'echo foo'"],
        ports=[8080],
        user_code_image="bar:earliest",
        httpstan_image="moo:sometag",
    )
    node_config = K8sNodeConfig(
        "fake-configmap-name",
        "xxxxxxxxxxxxx",
        "path/to/key.pem",
        "foo/controller.yaml",
        "foo/storage.yaml",
        "1600m",
        "5000000Ki",
    )
    scheduler_config = SchedulerConfig(
        controller=config,
        worker=config,
        node_type=NodeType.KUBERNETES_POD,
        node_config=node_config,
        results_url_expiry_time=42,
        remote_logging_config_path=None,
        results_endpoint_url="foo",
        results_access_key_id="id",
        results_secret_key="secret",
        results_bucket="results",
        results_dirname="results_dir",
    )
    return scheduler_config

@patch("chainsail.scheduler.config.K8sNodeConfig.create_node_driver")
def test_k8s_node_from_representation(mock_driver, mock_scheduler_config):
    from chainsail.common.spec import JobSpec
    from chainsail.scheduler.db import TblNodes
    from chainsail.scheduler.nodes.base import NodeStatus, NodeType
    from chainsail.scheduler.nodes.k8s_pod import K8sNode

    job_spec = JobSpec("gs://my-bucket/scripts")
    node_rep = TblNodes(
        id=1,
        job_id=1,
        name="dummy-1",
        node_type=NodeType.KUBERNETES_POD,
        entrypoint="echo 'hello world'",
        status=NodeStatus.RUNNING,
        address="127.0.0.1",
        ports="[8080]",
    )

    node = K8sNode.from_representation(job_spec, node_rep, mock_scheduler_config)
    # This method should bind node_rep to the new node
    assert node.representation

@patch("chainsail.scheduler.config.K8sNodeConfig.create_node_driver")
def test_k8s_node_from_config_with_job(mock_driver, mock_scheduler_config):
    from chainsail.common.spec import JobSpec
    from chainsail.scheduler.db import TblJobs
    from chainsail.scheduler.nodes.k8s_pod import K8sNode

    job_spec = JobSpec("gs://my-bucket/scripts")
    node = K8sNode.from_config("dummy-1", mock_scheduler_config, job_spec, job_rep=TblJobs(id=1))
    assert node.representation
    assert node.representation.job.id == 1

@patch("chainsail.scheduler.config.K8sNodeConfig.create_node_driver")
def test_k8s_node_from_representation_then_create(mock_driver, mock_scheduler_config):
    from chainsail.common.spec import JobSpec, PipDependencies
    from chainsail.scheduler.db import TblJobs, TblNodes
    from chainsail.scheduler.nodes.base import NodeStatus, NodeType
    from chainsail.scheduler.nodes.k8s_pod import K8sNode

    job_spec = JobSpec("gs://my-bucket/scripts", dependencies=[PipDependencies(["numpy"])])
    node_rep = TblNodes(
        id=1,
        job_id=1,
        name="new-node",
        node_type=NodeType.KUBERNETES_POD,
        entrypoint="echo 'hello world'",
        # This node has not been actually created yet
        status=NodeStatus.INITIALIZED,
        job=TblJobs(),
    )

    # Create the node object
    with patch("chainsail.scheduler.nodes.k8s_pod.monitor_deployment") as mock_monitor_deployment:
        node = K8sNode.from_representation(
            job_spec,
            node_rep,
            mock_scheduler_config,
        )
        node.refresh_status()
        (is_created, _) = node.create()

    mock_monitor_deployment.assert_called_once()
    assert is_created
    assert node.status == NodeStatus.RUNNING

@patch("chainsail.scheduler.config.K8sNodeConfig.create_node_driver")
def test_k8s_node_lifecycle(mock_driver, mock_scheduler_config):
    from chainsail.common.spec import JobSpec
    from chainsail.scheduler.db import TblJobs, TblNodes
    from chainsail.scheduler.nodes.base import NodeStatus
    from chainsail.scheduler.nodes.k8s_pod import K8sNode

    job_spec = JobSpec("gs://my-bucket/scripts")

    with patch("chainsail.scheduler.nodes.k8s_pod.monitor_deployment"):
        node_rep = TblNodes(
            id=1,
            job_id=1,
            name="new-node",
            node_type=NodeType.KUBERNETES_POD,
            job=TblJobs(id=3),
        )
        node = K8sNode(
            name="test",
            is_controller=True,
            config=mock_scheduler_config.controller,
            node_config=mock_scheduler_config.node_config,
            spec=job_spec,
            representation=node_rep,
        )

        statuses = [node.status]
        is_created, _ = node.create()
        statuses.append(node.status)
        is_restarted = node.restart()
        statuses.append(node.status)
        is_deleted = node.delete()
        statuses.append(node.status)

    # Check that all operations succeeded
    assert all([is_created, is_restarted, is_deleted])
    # If so, the following statuses should have been observed:
    assert statuses == [
        NodeStatus.INITIALIZED,
        NodeStatus.RUNNING,
        NodeStatus.RESTARTING,
        NodeStatus.EXITED,
    ]


# QBApp/urls.py
from django.urls import path
from django.urls import re_path
from QBApp import views

from django.views.generic.base import RedirectView

urlpatterns = [

    # URLs - Template pages classes --------------------------------------------
    path("", views.LoginView.as_view()),
    path("search/", views.HomeView.as_view()),
    path("search/qresults2/", views.QResults2View.as_view()),

    path("noresults/", views.NoResultsView.as_view()),
    path("error/", views.ErrorView.as_view()),
    re_path(r'^.*about/', views.AboutView.as_view()),
    # --------------------------------------------------------------------------

    # URLs - Caller classes ----------------------------------------------------
    path("search/qresults2/offboard/", views.OffboardCall.as_view()),
    path("search/qresults2/exportocsv/", views.ExportToCSVCall.as_view()),
    path("loginuser/", views.LoginUserCall.as_view()),
    re_path(r'^.*logout/', views.LogoutCall.as_view()),
    # --------------------------------------------------------------------------

    # Statics and other calls --------------------------------------------------
    path("favicon.ico", RedirectView.as_view(url="/static/favicon.ico")),

    # Whatever other url redirects to login page.
    # HINT: This hides the Django admin pages
    re_path(r'^.*$', views.RedirectCall.as_view())
    # --------------------------------------------------------------------------
]


import arcade

import settings

import os

import time

from chapter_1 import Chapter1View

class MenuView(arcade.View):
    def on_show(self):
        arcade.set_background_color(arcade.color.BLACK)
        self.background = settings.BACKGROUND
        self.switch = True
        self.count = 0
        self.background_music = settings.BACKGROUND_MUSIC
        self.ring = settings.RING
        arcade.play_sound(self.background_music)

    def on_draw(self):
        arcade.start_render()

        arcade.draw_texture_rectangle(settings.WIDTH // 2, settings.HEIGHT // 2,
                                      settings.WIDTH, settings.HEIGHT, self.background)

        if self.switch:
            arcade.draw_text("ENTER ", settings.WIDTH // 2, settings.HEIGHT // 4,
                            arcade.color.GOLD, 30, 0,  "center", 'Comic Sans', True, False,
                            "center", "center")
            self.count += 1
            if self.count >= 50:
                self.switch = False
                self.count = 0

        elif not self.switch:
            arcade.draw_text("ENTER ", settings.WIDTH // 2, settings.HEIGHT // 4,
                            arcade.color.GOLDENROD, 30, 0,  "center", 'Comic Sans', True, False,
                            "center", "center")
            self.count += 1
            if self.count >= 50:
                self.switch = True
                self.count = 0

    def on_key_press(self, key, modifiers):
        if key == arcade.key.ENTER:
            arcade.play_sound(self.ring)
            arcade.pause(0.6)
            if len(os.listdir("saves")) == 0:
                self.director.specific_view(Chapter1View)
            else:
                self.director.next_view()

if __name__ == "__main__":
    """This section of code will allow you to run your View
    independently from the main.py file and its Director.

    You can ignore this whole section. Keep it at the bottom
    of your code.

    It is advised you do not modify it unless you really know
    what you are doing.
    """
    from utils import FakeDirector
    window = arcade.Window(settings.WIDTH, settings.HEIGHT)
    my_view = MenuView()
    my_view.director = FakeDirector(close_on_next_view=True)
    window.show_view(my_view)
    arcade.run()


import torch
from torch.utils.data.dataset import Dataset as BaseDataset
import numpy as np

"""
Class, representing observed items by user
UserItemDataset takes as argument array-like element,
each element contains tuple (user_id, item_id)
By default, class will reindex user_ids and item_ids to match
GMF, MLP, NeuMF embeddings' vocablulary
Also, class will flood data with negative samples
All parameters can be tuned via config
"""
class UserItemDataset(BaseDataset):
    def __init__(self, data_dict, config):
        self.config = config
        self.data = data_dict['samples']
        if 'user_features' in data_dict:
            self.user_features = data['user_features']
        else:
            self.user_features = None

        if 'item_features' in data_dict:
            self.item_features = data['item_features']
        else:
            self.item_features = None

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        user, item, label = list(map(lambda x: torch.tensor(x), self.data[idx]))
        user, item = user.long(), item.long()
        sample = {}
        sample['user'] = user
        sample['item'] = item
        sample['label'] = label
        if self.user_features is not None:
            sample['user_features'] = self.user_features[user.item()]
        if self.item_features is not None:
            sample['item_features'] = self.item_features[item.item()]
        return sample

    """
    Data reindexing was moved to class, because if you create negative
    samples when init data, you can accidentally miss indicies or samples, which
    contains in test split
    So, you should use #reindex_data and #flood_negative, before train/test split.
    It will ensure, that no data was leaked and all users and items were mapped to
    new indicies
    Also, method returns both data and mappers, so reindexing user and item features
    indicies is user's responsibility, because features are too general for trying
    to do it with no information about its format.
    """
    @staticmethod
    def reindex_data(data_samples):
        user_mapper = {}
        item_mapper = {}
        reindexed_data = []
        for user, item in data_samples:
            uid = insert(user, user_mapper)
            iid = insert(item, item_mapper)
            reindexed_data.append((uid, iid))
        return (reindexed_data, user_mapper, item_mapper)

    @staticmethod
    def flood_negative(positive_data_samples, config):
        per_user = config.negatives_per_user
        #For fast search we need to create set of tuples like (user, item)
        positive_set = set(map(lambda x: (x[0], x[1]), positive_data_samples))
        #To iterate over each user once (and don't search in already created negative samples)
        user_set = set(map(lambda x: x[0], positive_data_samples))

        #Cause items have been already reindexed, MAX_ITEM_ID = len(set(ITEMS)) - 1
        item_next_idx = len(set(map(lambda x: x[1], positive_data_samples)))
        negative_samples = []
        for user in user_set:
            sample = set()
            while len(sample) != per_user:
                item_idx = np.random.randint(0, item_next_idx)
                pair = (user, item_idx)
                if pair not in sample and pair not in positive_set:
                    sample.add(pair)
            #Generate samples with zero labels
            negative_samples.extend(list(sample))
        return negative_samples

    @staticmethod
    def union_samples(positive, negative):
        data = []
        positive = list(map(lambda x: (*x, 1.0), positive))
        negative = list(map(lambda x: (*x, 0.0), negative))
        data.extend(positive)
        data.extend(negative)
        return data

def insert(idx, idx_dict):
    if idx not in idx_dict:
        new_idx = len(idx_dict)
        idx_dict[idx] = new_idx
    else:
        new_idx = idx_dict[idx]
    return new_idx

if __name__ == "__main__":

    from hparams.utils import Hparam
    from torch.utils.data.dataloader import DataLoader
    import sys

    config = Hparam(sys.argv[1]).dataset
    data = [[420, 606], [420, 101], [69, 101], [69, 202]]
    reindexed_data, user_mapper, item_mapper = UserItemDataset.reindex_data(data)
    negative_samples = UserItemDataset.flood_negative(reindexed_data, config)
    data = UserItemDataset.union_samples(reindexed_data, negative_samples)
    data_dict = { "samples" : data }

    dataset = UserItemDataset(data_dict, config)
    dataloader = DataLoader(dataset, batch_size=2, shuffle=True)

    print('converted user ids ', user_mapper)
    print('converted item ids ', item_mapper)
    # Ensure, that dataset supports batches
    for _, data in enumerate(dataloader, 0):
        print(data)


# 3. Hafta Ödev Cevapları
#1
def mukemmel_sayi_mi(num):
    counter = 0
    for i in range(1, num):
        if num % i == 0:
            counter += i
    return counter == num

#2
for i in range(1,1001):
    if mukemmel_sayi_mi(i):
        print(i)

#3
for i in range(1, 101):
    if i % 3 == 0:
        print(i)
    else:
        continue

#4
import sys
import random

altsinir = int(sys.argv[1])
ustsinir = int(sys.argv[2])

if altsinir > ustsinir:
    print("Alt sınırı üst sınırdan daha büyük girdiniz!")
    sys.exit()

rastgele_sayi = random.randint(altsinir, ustsinir)
deneme_sayisi = 0

while True:
    tahmin_edilen_sayi = int(input("Sayıyı giriniz: "))
    deneme_sayisi += 1
    if tahmin_edilen_sayi == rastgele_sayi:
        print("Doğru tahmin!")
        print("Sayı {} idi".format(tahmin_edilen_sayi))
        sys.exit()
    else:
        print("Yanlış tahmin!")


n,m = map(int,input().split())

l = list(map(int,input().split()))

num = sum(l)

start = max(l)
end = sum(l)
result = num

while start<=end:
    mid = (start+end) // 2
    if mid < max(l):
        start = mid + 1
        continue

    cnt,tmp =1,0

    for i in range(len(l)):
        if tmp + l[i] <= mid:
            tmp += l[i]
        else:
            tmp = l[i]
            cnt += 1

    if cnt <= m:
        end = mid - 1
        result = min(result,mid)
    else:
        start = mid + 1

print(result)


# -*- coding: utf-8 -*-
# This is a management command, rather than a migration script, for two primary reasons:
#   1. It makes no changes to database structure (e.g. AlterField), only database content.
#   2. It may need to be ran more than once, as it skips failed registrations.

from __future__ import unicode_literals
from datetime import timedelta
import logging

import django
django.setup()

from django.core.management.base import BaseCommand
from django.db import transaction

from osf.models import Registration, Retraction, Sanction
from scripts import utils as script_utils

logger = logging.getLogger(__name__)

def set_date_retracted(*args):
    registrations = (
        Registration.objects.filter(retraction__state=Sanction.APPROVED, retraction__date_retracted=None)
        .select_related('retraction')
        .prefetch_related('registered_from__logs')
        .prefetch_related('registered_from__guids')
    )
    total = registrations.count()
    logger.info('Migrating {} retractions.'.format(total))

    for registration in registrations:
        if not registration.registered_from:
            logger.warn('Skipping failed registration {}'.format(registration._id))
            continue
        retraction_logs = registration.registered_from.logs.filter(action='retraction_approved', params__retraction_id=registration.retraction._id)
        if retraction_logs.count() != 1 and retraction_logs.first().date - retraction_logs.last().date > timedelta(seconds=5):
            msg = (
                'There should be a retraction_approved log for retraction {} on node {}. No retraction_approved log found.'
                if retraction_logs.count() == 0
                else 'There should only be one retraction_approved log for retraction {} on node {}. Multiple logs found.'
            )
            raise Exception(msg.format(registration.retraction._id, registration.registered_from._id))
        date_retracted = retraction_logs[0].date
        logger.info(
            'Setting date_retracted for retraction {} to be {}, from retraction_approved node log {}.'.format(
                registration.retraction._id, date_retracted, retraction_logs[0]._id
            )
        )
        registration.retraction.date_retracted = date_retracted
        registration.retraction.save()

def unset_date_retracted(*args):
    retractions = Retraction.objects.filter(state=Sanction.APPROVED).exclude(date_retracted=None)
    logger.info('Migrating {} retractions.'.format(retractions.count()))

    for retraction in retractions:
        retraction.date_retracted = None
        retraction.save()

class Command(BaseCommand):
    """
    Backfill Retraction.date_retracted with `RETRACTION_APPROVED` log date.
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Run migration and roll back changes to db',
        )
        parser.add_argument(
            '--reverse',
            action='store_true',
            dest='reverse',
            help='Unsets date_retraction'
        )

    def handle(self, *args, **options):
        reverse = options.get('reverse', False)
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
        with transaction.atomic():
            if reverse:
                unset_date_retracted()
            else:
                set_date_retracted()
            if dry_run:
                raise RuntimeError('Dry run, transaction rolled back.')


import random
import time
import yaml
import multiprocessing as mp

import numpy as np

from .model import load_model
from .environment import prepare_env, make_env
from .connection import send_recv, accept_socket_connections, connect_socket_connection
#from .agents.SACNN120.wrapper import WrappedAgent as SACNN120
#from .agents.Hybrid373.wrapper import WrappedAgent as Hybrid373
#from .agents.Hybrid684.wrapper import WrappedAgent as Hybrid684
#from .agents.Hybrid700.wrapper import WrappedAgent as Hybrid700
#from .agents.Hybrid741.wrapper import WrappedAgent as Hybrid741
#from .agents.Hybrid829.wrapper import WrappedAgent as Hybrid829
#from .agents.Hybrid855.wrapper import WrappedAgent as Hybrid855
#from .agents.Hybrid978.wrapper import WrappedAgent as Hybrid978
#from .agents.HybridAllowShot893.wrapper import WrappedAgent as HybridAllowShot893
#from .agents.HybridAllowShot1017.wrapper import WrappedAgent as HybridAllowShot1017
#from .agents.Hybrid610Builtin.wrapper import WrappedAgent as Hybrid610Builtin
#from .agents.HybridAllowShot1175.wrapper import WrappedAgent as HybridAllowShot1175
#from .agents.StickyUPGO991.wrapper import WrappedAgent as StickyUPGO991
#from .agents.StickyUPGO1550.wrapper import WrappedAgent as StickyUPGO1550
#from .agents.ScoreReward1428.wrapper import WrappedAgent as ScoreReward1428
#from .agents.NewBig163.wrapper import WrappedAgent as NewBig163

io_match_port = 9876

class RandomAgent:
    def reset(self, env, show=False):
        pass

    def action(self, env, player, show=False):
        actions = env.legal_actions(player)
        return random.choice(actions)

class BuiltinAgent(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action(player)

class RuleBasedAgentA(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_A(player)

class RuleBasedAgentB(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_B(player)

class RuleBasedAgentC(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_C(player)

class RuleBasedAgentD(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_D(player)

class RuleBasedAgentE(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_E(player)

class RuleBasedAgentF(RandomAgent):
    def action(self, env, player, show=False):
        return env.rule_based_action_F(player)

class IdleAgent(RandomAgent):
    def action(self, env, player, show=False):
        return 14

class RightAgent(RandomAgent):
    def action(self, env, player, show=False):
        return 5

def softmax(p, actions):
    ep = np.exp(p)
    p = ep / ep.sum()
    mask = np.zeros_like(p)
    mask[actions] = 1
    p = (p + 1e-16) * mask
    p /= p.sum()
    return p

def view(env, player=None):
    if hasattr(env, 'view'):
        env.view(player=player)
    else:
        print(env)

def view_transition(env):
    if hasattr(env, 'view_transition'):
        env.view_transition()
    else:
        pass

def print_outputs(env, prob, v):
    if hasattr(env, 'print_outputs'):
        env.print_outputs(prob, v)
    else:
        print('v = %f' % v)
        print('p = %s' % (prob * 1000).astype(int))

class Agent:
    def __init__(self, planner):
        # planner might be a neural nets, or some game tree search
        self.planner = planner
        self.hidden = None

    def reset(self, env, show=False):
        self.hidden = self.planner.init_hidden()

    def action(self, env, player, show=False):
        p, v, _, self.hidden = self.planner.inference(env.observation(player), self.hidden)
        actions = env.legal_actions(player)
        if show:
            view(env, player=player)
            print_outputs(env, softmax(p, actions), v)
        ap_list = sorted([(a, p[a]) for a in actions], key=lambda x: -x[1])
        return ap_list[0][0]

class SoftAgent(Agent):
    def action(self, env, player, show=False):
        p, v, _, self.hidden = self.planner.inference(env.observation(player), self.hidden)
        actions = env.legal_actions(player)
        prob = softmax(p, actions)
        if show:
            view(env, player=player)
            print_outputs(env, prob, v)
        return random.choices(np.arange(len(p)), weights=prob)[0]

class IOAgentClient:
    def __init__(self, agent, env, conn, show=False):
        self.conn = conn
        self.agent = agent
        self.env = env
        self.show = show

    def run(self):
        while True:
            command, args = self.conn.recv()
            if command == 'quit':
                break
            elif command == 'outcome':
                print('outcome = %f' % args[0])
            elif hasattr(self.agent, command):
                ret = getattr(self.agent, command)(self.env, *args, show=self.show)
                if command == 'action':
                    ret = self.env.action2str(ret)
            else:
                ret = getattr(self.env, command)(*args)
                if command == 'play_info':
                    if self.show:
                        view_transition(self.env)
            self.conn.send(ret)

class IOAgent:
    def __init__(self, conn):
        self.conn = conn

    def reset(self, data):
        send_recv(self.conn, ('reset_info', [data]))
        return send_recv(self.conn, ('reset', []))

    def chance(self, data):
        return send_recv(self.conn, ('chance_info', [data]))

    def play(self, data):
        return send_recv(self.conn, ('play_info', [data]))

    def outcome(self, outcome):
        return send_recv(self.conn, ('outcome', [outcome]))

    def action(self, player):
        return send_recv(self.conn, ('action', [player]))

def exec_match(env, agents, show=False, game_args={}):
    ''' match with shared game environment '''
    if env.reset(game_args):
        return None
    for agent in agents.values():
        agent.reset(env, show=show)
    while not env.terminal():
        if env.chance():
            return None
        if env.terminal():
            break
        actions = [0] * len(agents)
        for p, agent in agents.items():
            actions[p] = agent.action(env, p, show=show)
        if env.plays(actions):
            return None
        if show:
            view_transition(env)
    outcome = env.outcome()
    if show:
        print('final outcome = %s' % outcome)
    return [np.sign(o) for o in outcome]

def exec_io_match(env, io_agents, show=False, game_args={}):
    ''' match with divided game environment '''
    if env.reset(game_args):
        return None
    info = env.diff_info()
    for agent in io_agents.values():
        agent.reset(info)
    while not env.terminal():
        if env.chance():
            return None
        if env.terminal():
            break
        actions = [0] * len(io_agents)
        for p, agent in io_agents.items():
            actions[p] = env.str2action(agent.action(p))
        if env.plays(actions):
            return None
        info = env.diff_info()
        for agent in io_agents.values():
            agent.play(info)
    outcome = env.outcome()
    for p, agent in io_agents.items():
        agent.outcome(outcome[p])
    return [np.sign(o) for o in outcome]

class Evaluator:
    def __init__(self, env, args):
        self.env = env
        self.args = args
        self.default_agent = BuiltinAgent()

    def execute(self, models, args):
        agents = {}
        opponent_name = ''
        for p, model in models.items():
            if model is None:
                agent_map = {
                    (IdleAgent, 'donothing'): 1,
                    (RuleBasedAgentB, 'rulebaseB'): 2,
                    (RuleBasedAgentC, 'rulebaseC'): 4,
                    #(RuleBasedAgentD, 'rulebaseD'): 2,
                    (RuleBasedAgentE, 'rulebaseE'): 1,
                    (BuiltinAgent, 'builtinAI'): 7,
                    #(SACNN120, 'SACNN180'): 2,
                    #(Hybrid373, 'Hybrid373'): 2,
                    #(Hybrid684, 'Hybrid684'): 1,
                    #(Hybrid700, 'Hybrid700'): 1,
                    #(Hybrid741, 'Hybrid741'): 2,
                    #(Hybrid829, 'Hybrid829'): 2,
                    #(Hybrid855, 'Hybrid855'): 2,
                    #(Hybrid978, 'Hybrid978'): 2,
                    #(HybridAllowShot893, 'HybridAllowShot893'): 2,
                    #(HybridAllowShot1017, 'HybridAllowShot1017'): 2,
                    #(Hybrid610Builtin, 'Hy610Built'): 2,
                    #(HybridAllowShot1175, 'HybridAllowShot1175'): 3,
                    #(StickyUPGO991, 'StickyUPGO991'): 1,
                    #(StickyUPGO1550, 'StickyUPGO1550'): 3,
                    #(ScoreReward1428, 'ScoreReward1428'): 4,
                    #(NewBig163, 'NewBig163'): 2,
                }
                def normalize(w):
                    s = sum(w)
                    return [p / s for p in w]
                opponent = random.choices(list(agent_map.keys()), k=1, weights=normalize(list(agent_map.values())))[0]
                agents[p] = opponent[0]()
                opponent_name = opponent[1]
            else:
                agents[p] = Agent(model)
        outcome = exec_match(self.env, agents, game_args=args)
        if outcome is None:
            print('None episode in evaluation!')
            return None
        else:
            outcome = outcome[args['player'][0]]
        return opponent_name, outcome

def wp_func(results):
    games = sum([v for k, v in results.items() if k is not None])
    win = sum([(k + 1) / 2 * v for k, v in results.items() if k is not None])
    if games == 0:
        return 0.0
    return win / games

def eval_process_mp_child(agents, env_args, index, in_queue, out_queue, seed, show=False):
    random.seed(seed + index)
    env = make_env({**env_args, 'id': index})
    while True:
        args = in_queue.get()
        if args is None:
            break
        g, agent_ids, pat_idx, game_args = args
        print('*** Game %d ***' % g)
        agent_map = {env.players()[p]: agents[ai] for p, ai in enumerate(agent_ids)}
        if isinstance(list(agent_map.values())[0], IOAgent):
            outcome = exec_io_match(env, agent_map, show=show, game_args=game_args)
        else:
            outcome = exec_match(env, agent_map, show=show, game_args=game_args)
        out_queue.put((pat_idx, agent_ids, outcome))
    out_queue.put(None)

def evaluate_mp(env_args, agents, args_patterns, num_process, num_games, seed):
    env = make_env(env_args)
    in_queue, out_queue = mp.Queue(), mp.Queue()
    args_cnt = 0
    total_results, result_map = [{} for _ in agents], [{} for _ in agents]
    print('total games = %d' % (len(args_patterns) * num_games))
    time.sleep(0.1)
    for pat_idx, args in args_patterns.items():
        for i in range(num_games):
            if len(agents) == 2:
                # When playing two player game,
                # the number of games with first or second player is equalized.
                first_agent = 0 if i < (num_games // 2) else 1
                tmp_pat_idx, agent_ids = (pat_idx + '-F', [0, 1]) if first_agent == 0 else (pat_idx + '-S', [1, 0])
            else:
                tmp_pat_idx, agent_ids = pat_idx, random.sample(list(range(len(agents))), len(agents))
            in_queue.put((args_cnt, agent_ids, tmp_pat_idx, args))
            for p in range(len(agents)):
                result_map[p][tmp_pat_idx] = {}
            args_cnt += 1

    io_mode = agents[0] is None
    if io_mode:  # network battle mode
        agents = io_match_acception(num_process, env_args, len(agents), io_match_port)
    else:
        agents = [agents] * num_process

    for i in range(num_process):
        in_queue.put(None)
        args = agents[i], env_args, i, in_queue, out_queue, seed
        if num_process > 1:
            mp.Process(target=eval_process_mp_child, args=args).start()
            if io_mode:
                for agent in agents[i]:
                    agent.conn.close()
        else:
            eval_process_mp_child(*args, show=True)

    finished_cnt = 0
    while finished_cnt < num_process:
        ret = out_queue.get()
        if ret is None:
            finished_cnt += 1
            continue
        pat_idx, agent_ids, outcome = ret
        if outcome is not None:
            for idx, p in enumerate(env.players()):
                agent_id = agent_ids[idx]
                oc = outcome[p]
                result_map[agent_id][pat_idx][oc] = result_map[agent_id][pat_idx].get(oc, 0) + 1
                total_results[agent_id][oc] = total_results[agent_id].get(oc, 0) + 1

    for p, r_map in enumerate(result_map):
        print('---agent %d---' % p)
        for pat_idx, results in r_map.items():
            print(pat_idx, {k: results[k] for k in sorted(results.keys(), reverse=True)}, wp_func(results))
        print('total', {k: total_results[p][k] for k in sorted(total_results[p].keys(), reverse=True)}, wp_func(total_results[p]))
    return total_results

def io_match_acception(n, env_args, num_agents, port):
    waiting_conns = []
    accepted_conns = []

    for conn in accept_socket_connections(port):
        if len(accepted_conns) >= n * num_agents:
            break
        waiting_conns.append(conn)

        if len(waiting_conns) == num_agents:
            conn = waiting_conns[0]
            accepted_conns.append(conn)
            waiting_conns = waiting_conns[1:]
            conn.send(env_args)  # send accpept with environment arguments

    agents_list = [
        [IOAgent(accepted_conns[i * num_agents + j]) for j in range(num_agents)]
        for i in range(n)
    ]

    return agents_list

def get_model(env, model_path):
    import torch
    from .model import DuelingNet as Model
    model = env.net()(env) if hasattr(env, 'net') else Model(env)
    model = load_model(model, model_path)
    model.eval()
    return model

def client_mp_child(env_args, model_path, conn, show):
    env = make_env(env_args)
    model = get_model(env, model_path)
    IOAgentClient(Agent(model), env, conn, show).run()

def eval_main(args, argv):
    env_args = args['env_args']
    prepare_env(env_args)
    env = make_env(env_args)

    model_path = argv[0]
    agent1 = Agent(get_model(env, model_path))

    opponent_agents = {
        'builtinAI': BuiltinAgent(),
        #'rulebaseD': RuleBasedAgentD(),
        'rulebaseC': RuleBasedAgentC(),
        'rulebaseB': RuleBasedAgentB()
    }

    num_games = int(argv[1]) if len(argv) >= 2 else 100
    num_process = int(argv[2]) if len(argv) >= 3 else 8

    print('%d process, %d games' % (num_process, num_games))

    seed = random.randrange(1e8)
    print('seed = %d' % seed)

    total_results_map = {}
    for name, opponent in opponent_agents.items():
        print('vs', name)
        agents = [agent1, opponent]
        total_results_map[name] = evaluate_mp(env_args, agents, {'detault': {}}, num_process, num_games, seed)

    for name, total_results in total_results_map.items():
        results = total_results[0]
        print(name, {k: results[k] for k in sorted(results.keys(), reverse=True)}, wp_func(results))

def eval_server_main(args, argv):
    env_args = args['env_args']
    prepare_env(env_args)
    env = make_env(env_args)

    num_games = int(argv[0]) if len(argv) >= 1 else 100
    num_process = int(argv[1]) if len(argv) >= 2 else 8

    print('%d process, %d games' % (num_process, num_games))

    seed = random.randrange(1e8)
    print('seed = %d' % seed)

    print('io-match server mode')
    evaluate_mp(env_args, [None] * len(env.players()), {'default': {}}, num_process, num_games, seed)

def eval_client_main(args, argv):
    print('io-match client mode')
    prepared = False
    while True:
        try:
            conn = connect_socket_connection(args['eval_args']['remote_host'], io_match_port)
            env_args = conn.recv()
        except EOFError:
            break

        if not prepared:
            prepare_env(env_args)
            prepared = True

        model_path = argv[0]
        mp.Process(target=client_mp_child, args=(env_args, model_path, conn, False)).start()
        conn.close()


"""
투 포인터..?, O(N log N)

왜?
    1. 널빤지를 겹치지 않게 웅덩이를 덮어야 함
    2. 그러기 위해선 겹치는 웅덩이를 하나로 합친 뒤 널빤지를 깔아야 함
    3. 웅덩이를 하나로 합치기 위해선 시작점과 끝점 등 두 개의 변수로 관리해야 함
    4. 따라서 물 웅덩이의 범위에 따라 시작점과 끝점을 관리하고 널빤지를 깔았음
"""
import sys

def solution():
    sys_input = sys.stdin.readline

    n, length = map(int, sys_input().split())
    holes = sorted([list(map(int, sys_input().split())) for _ in range(n)])

    min_count = 0  # 필요한 널빤지의 최소 개수
    begin, end = 0, 0
    for hole_begin, hole_end in holes:
        if end < hole_begin:  # 웅덩이 길이를 연장할 수 없다면 널빤지를 깔고 새로운 범위 찾기
            hole_length = end - begin  # 널빤지를 깔아야 할 웅덩이의 길이
            count = (hole_length + length - 1) // length  # 필요한 널빤지의 개수
            min_count += count  # 널빤지 개수 반영
            begin = max(hole_begin, begin + count * length)  # 현재 웅덩이의 시작점보다 마지막으로 깐 널빤지의 끝점이 더 길 수 있음
            end = hole_end
        else:  # 웅덩이 길이 연장
            end = max(end, hole_end)
    # 마지막으로 계산한 웅덩이가 있다면 계산해줌
    if begin < end:
        hole_length = end - begin
        min_count += (hole_length + length - 1) // length

    print(min_count)

solution()


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseList(self, head):
        if not head:
            return None
        return self.reverse(head, head, head.next)

    def reverse(self, head, first, target):
        if not target:
            return head
        first.next = target.next
        t = None
        if target.next:
            t = ListNode(target.next.val)
            t.next = target.next.next
        target.next = head
        return self.reverse(target, first, t)

a = [1, 2, 3, 4, 5]
b = [ListNode(1)]
for i in range(1, len(a)):
    b.append(ListNode(a[i]))
    b[i - 1].next = ListNode(a[i])

s = Solution()
print(s.reverseList(b[0]))


#!/usr/bin/env python3
# 2021 Leo Kaindl

"""
Main module of the pipeline. Imports the other package modules and serves as the interface
between them. The `--visualize` and `--view` entry points are in the :class:`phylo` module.
"""

import sys

from ab12phylo_cmd import cli, i_o, msa, blast, ml, phylo

def _main():
    # get command line arguments
    args = cli.parser(sys.argv[1:]).args

    if not args.finish:
        if args.add_xml:
            print('starting -px BLAST XML run', file=sys.stderr)
            blaster = blast.blast_build(args, None)
            blaster.start()
            # reading an XML requires no waiting
            blaster.join()
            # visualize MSA for inspection
            phylo.mview_msa(args)
            print('finished -px BLAST XML run', file=sys.stderr)
            exit(0)

        if args.prepare:
            print('starting -p1 prep run', file=sys.stderr)

        # read in files
        reader = i_o.reader(args)

        # write .FASTAs and source information
        writer = i_o.writer(args, reader)

        # build & trim MSAs
        aligner = msa.msa_build(args, reader.seq_counts)

        # run BLAST and parse results de-synced
        blaster = blast.blast_build(args, reader)
        blaster.start()

        if args.prepare:
            # wait for BLAST if necessary
            blaster.join()
            # visualize MSA for inspection
            phylo.mview_msa(args)
            print('finished -p1 prep run', file=sys.stderr)
            exit(0)

        # build trees with raxml-ng or iqtree2
        ml_threads = ml.ml_build(args)
        ml_threads.run()

        # wait for BLAST if necessary
        blaster.join()

        # visualize best tree
        phylo.tree_build(args)

    else:
        print('starting -p2 finishing run', file=sys.stderr)
        # build trees with raxml-ng or iqtree2
        ml_threads = ml.ml_build(args)
        ml_threads.run()

        # visualize best tree
        phylo.tree_build(args)

if __name__ == '__main__':
    _main()


import numpy as np

with open("coins.in") as f:
    i = 0
    a = []
    for line in f.readlines()[1:]:
        _k ,_m = [float(x) for x in line.split()]
        _k += 2
        _m += 1
        p = _m / _k
        q = 1 - p
        ml = p ** _m * q ** (_k - _m)
        a.append((i, _m / _k, ml))
        i += 1

    a.sort(key=lambda x: x[1])

    b = []
    for i in a:
        b.append(i[0])
    np.savetxt("coins.out", b, fmt='%d')


from typing import List

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        # Inicializa o vetor de pais para cada nó
        parents = [i for i in range(len(edges) + 1)]

        # Função para encontrar o pai de um nó usando Union-Find
        def find(x):
            if parents[x] == x:
                return x
            else:
                parents[x] = find(parents[x])
                return parents[x]

        # Função para unir dois conjuntos usando Union-Find
        def union(x, y):
            px, py = find(x), find(y)
            if px != py:
                parents[px] = py

        # Percorre as arestas e verifica se a adição de cada uma delas forma um ciclo
        for edge in edges:
            if find(edge[0]) == find(edge[1]):
                return edge
            else:
                union(edge[0], edge[1])

        # Se não houver ciclo, retorna a última aresta
        return edges[-1]


#!/usr/bin/env python

import wx

#from scipy import *

import os, cPickle, pdb, sys

import reusablepanels
from reusablepanels.rwkSingleFileChooser_v2 import rwkSingleFileChooser
from reusablepanels.rwkdirchooserpanel import rwkdirchooserpanel

#import pydocument
#reload(pydocument)

#import pypres
#reload(pypres)

import rwkmisc
#reload(rwkmisc)

import rwkos
#reload(rwkos)

import texpypanel
import latexpanel
import pyppanel
import fancyhdrpanel
import wltpanel

settingsname = 'pytexguisettings.pkl'

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title,
                          pos=(150, 150), size=(650, 725))
        # Create the menubar
        menuBar = wx.MenuBar()

        # and a menu
        menu = wx.Menu()

        # add an item to the menu, using \tKeyName automatically
        # creates an accelerator, the third param is some help text
        # that will show up in the statusbar
        menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit the application")

        # bind the menu event to an event handler
        self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)

        # and put the menu on the menubar
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        #create top level controls (i.e. those not on a notebook page)
        #create the main directory chooser
        self.topdirchooser = rwkdirchooserpanel(self, -1)
        #and the main exit button
        self.exitbutton = wx.Button(self, -1, "Exit")

        #create the notebook
        self.notebook = wx.Notebook(self, -1, style=0)

        #notebook panes
        self.fancyhdrpane = fancyhdrpanel.FancyHdrPanel(self.notebook, dircontrol=self.topdirchooser)
        self.texpypane = texpypanel.TexPyPanel(self.notebook, dircontrol=self.topdirchooser, fancyhdrpanel=self.fancyhdrpane)
        self.purelatexpane = latexpanel.LatexPanel(self.notebook, dircontrol=self.topdirchooser, settingsname='purelatexsettings.pkl')
        self.pyppane = pyppanel.PYPPanel(self.notebook, dircontrol=self.topdirchooser, fancyhdrpanel=self.fancyhdrpane)
        self.wltpane = wltpanel.WLTPanel(self.notebook, dircontrol=self.topdirchooser, fancyhdrpanel=self.fancyhdrpane)

        #create the sizer for the first pane
        grid_sizer = wx.FlexGridSizer(2, 1, 0, 0)

        #create widgets for pane one
        #self.panel = wx.Panel(self)
        #self.label_4 = wx.StaticText(self.notebook_pane_1, -1, "label_4")
        #self.button_1 = wx.Button(self.notebook_pane_1, -1, "button_1")

        #add the widgets to pane one's sizer
        #grid_sizer.Add(self.label_4, 0, 0, 0)
        #grid_sizer.Add(self.button_1, 0, 0, 0)

        #self.notebook_pane_1.SetSizer(grid_sizer)

        grid_sizer.AddGrowableCol(0)
        grid_sizer.AddGrowableRow(0)
        #Add pane one to the notebook
        self.notebook.AddPage(self.texpypane, "TexPy/TexMaxima")
        self.notebook.AddPage(self.pyppane, "PYP")
        self.notebook.AddPage(self.purelatexpane, "Pure LaTeX")
        self.notebook.AddPage(self.fancyhdrpane, "fancyhdr")
        self.notebook.AddPage(self.wltpane, "WLT")
        #create the sizer for the main frame
        mainsizer = wx.FlexGridSizer(3, 1, 0, 0)
        mainsizer.AddGrowableCol(0)
        mainsizer.AddGrowableRow(1)

        #add the controls to the main sizer
        mainsizer.Add(self.topdirchooser, 1, wx.EXPAND|wx.ALL, 5)
        mainsizer.Add(self.notebook, 1, wx.EXPAND, 5)
        mainsizer.Add(self.exitbutton, 1, wx.ALL|wx.ALIGN_RIGHT, 5)

        self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, self.exitbutton)

        self.startdir = os.getcwd()
        self.settingspath = os.path.join(self.startdir, settingsname)

        if self.startdir not in sys.path:
            sys.path.insert(0, self.startdir)

        self.SetSizer(mainsizer)
        self.savepanellist = [self.texpypane, self.purelatexpane, self.pyppane, self.fancyhdrpane, self.wltpane]
        #mainsizer.Fit(self)
        self.Layout()
        self.LoadSettings()

    def SaveSettings(self): # wxGlade: MyFrame.<event_handler>
        mydict = {}
#        for key, chooser in zip(self.pathlist, self.filechoosers):
#            curpath = chooser.GetPath()
#            mydict[key] = curpath
#        wlt = self.wltcheckbox.GetValue()
        topdir = self.topdirchooser.GetPath()
        mydict['topdir'] = topdir
        nbind = self.notebook.GetSelection()
        mydict['nbind'] = nbind
        mypkl = open(self.settingspath,'wb')
        #print('mydict='+str(mydict))
        cPickle.dump(mydict,mypkl)
        mypkl.close()
        #for key, val in mydict.iteritems():
        #    print str(key) + ':' + str(val)
        for panel in self.savepanellist:
            panel.SaveSettings()

    def LoadSettings(self): # wxGlade: MyFrame.<event_handler>
        if os.path.exists(self.settingspath):
            mypkl = open(self.settingspath,'rb')
            mydict = cPickle.load(mypkl)
            mypkl.close()
            #print('mydict='+str(mydict))
            if mydict.has_key('topdir'):
                self.topdirchooser.SetPath(mydict['topdir'])
            if mydict.has_key('nbind'):
                self.notebook.SetSelection(mydict['nbind'])
        else:
            self.topdirchooser.SetPath(os.getcwd())
        for panel in self.savepanellist:
            panel.LoadSettings()

    def OnTimeToClose(self, evt):
        """Event handler for the button click."""
        self.SaveSettings()
        self.Close()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, "PyTex Office Suite")
        self.SetTopWindow(frame)

        #print "Print statements go to this stdout window by default."

        frame.Show(True)
        return True

if __name__ == "__main__":
    app = MyApp(redirect=False)
    app.MainLoop()


from django.shortcuts import render, redirect
from django.http import HttpRequest, HttpResponse

from games.models import Game
from member.models import Member
from .models import TagItem, Tag

def tag(request: HttpRequest, game_id: int) -> HttpResponse:
    game = Game.objects.get(pk=game_id)
    member = request.user.member
    tag_items = game.tag_items.all()
    tags = Tag.objects.get_tags_of_game(game)
    context = {'member':member, 'game':game, 'tags':tags}
    return render(request, 'tags/tag.html', context)

def add(request: HttpRequest, game_id: int) -> HttpResponse:
    game = Game.objects.get(pk=game_id)
    member = request.user.member
    label = request.GET.get('tag')
    tag = Tag.objects.get_or_create(label=label)[0]
    tag_item = TagItem.create(tag, member, game)
    tag_item.save()
    return redirect('games:game', gameID=game_id)

def view_games_by_tag(request: HttpRequest, label: str) -> HttpResponse:
    tag = Tag.objects.get(label=label)
    games = Tag.objects.get_games_by_tag(tag)
    context = {'games': games}
    return render(request, 'tags/view_games_by_tag.html', context)

def view_all_tags(request: HttpRequest) -> HttpResponse:
    tags = Tag.objects.all()
    context = {'tags':tags}
    return render(request, 'tags/tags.html', context)


from bot.customtypes import DeckDict

options = {
    "daylength": {
        "true": "dayLength",
        "minmax": [3, 20],
        "allowed": "int"
    },
    "nightlength": {
        "true": "nightLength",
        "minmax": [3, 20],
        "allowed": "int"
    },
    "daystart": {
        "true": "dayStart",
        "allowed": "str",
        "options": ["informed","uninformed", "off"],
        "translate": {
            "uninformed": "dayStart",
            "off": "off",
            "informed": "dawnStart"
        }
    },
    "deadlock": {
        "true": "deadlockPreventionLimit",
        "translate": {
            "random": -1,
            "initiator": 5,
            "responder": 6,
            "meteor": -2
        },
        "allowed": "str",
        "options": ["random", "initiator", "responder", "meteor"]
    },
    "votelock": {
        "true": "disableVoteLock",
        "allowed": "bool",
    },
    "hidesetup": {
        "true": "hideSetup",
        "allowed": "bool"
    },
    "hostrole": {
        "true": "hostRoleSelection",
        "allowed": "bool"
    },
    "mustvote": {
        "true": "mustVote",
        "allowed": "bool"
    },
    "nonighttalk": {
        "true": "noNightTalk",
        "allowed": "bool"
    },
    "scaletimer": {
        "true": "scaleTimer",
        "allowed": "bool"
    },
    "reveal": {
        "true": "revealSetting",
        "allowed": "str",
        "options": ["on", "alignment", "off"],
        "translate": {
            "alignment": "alignmentReveal",
            "on": "allReveal",
            "off": "noReveal"
        }
    },
    "killpower": {
        "true": "twoKp",
        "allowed": "str",
        "options": ["yes", "no"],
        "translate": {
            "yes": "1",
            "no": "0"
        }
    },
    "majority":
        {
            "true": "majorityRule",
            "allowed": "str",
            "translate": {
                "simple": "51",
                "off": "-1",
                "2/3": "66",
                "3/4": "75"
            },
            "options": ["simple", "off", "2/3", "3/4"]
        }
}

str2bool ={
    "True": True,
    "False": False
}

class Setting:
    edits = DeckDict(options)

    def is_valid(self, option):
        return self.edits.get(option)

    def edit_option(self, option, newvalue) -> [None, dict, bool]:
        option = self.is_valid(option)
        if option is None:
            return
        if option['allowed'] == "str":
            if newvalue in option["options"]:
                if "translate" in option:
                    newvalue = option["translate"][newvalue]
            else:
                return False
        elif option["allowed"] == "bool":
            if newvalue.title() in ["True", "False"]:
                newvalue = str2bool[newvalue.title()]
            else:
                return False
        elif option['allowed'] == "int":
            try:
                newvalue = int(newvalue)
            except ValueError:
                return False
            if not option["minmax"][0] <= newvalue <= option["minmax"][1]:
                return False

        return {
            "type": "options",
            option["true"]: newvalue
        }


import re
import matplotlib.pyplot as plt
import argparse
import numpy as np
import os

def main_grid(flog):

    assert os.path.isfile(flog), 'The file at the path does not exist.'
    file = open(flog, 'r')
    top1 = []
    top5 = []
    for line in file:
        match = re.search('done, Batch', line)
        if match:
            value = re.findall('[0-9]+\.[0-9]+', line)
            if value is not None:
                top1.append(float(value[5]))
                top5.append(float(value[3]))
    file.close()
    print('#points = ', len(top1))

    x = np.linspace(0, len(top1), len(top1))
    plt.plot(x, top1, linestyle='-', label='top1')
    plt.plot(x, top5, linestyle='--', label='top5')

    plt.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Log extractor.')
    parser.add_argument('--path', type=str, help='The path of the file which need to be extracted.')

    args = parser.parse_args()

    path = args.path
    main_grid(path)


from django.shortcuts import render, redirect
from .forms import DjangoForm
from .models import Pustak

# Create your views here.
def addbook(request):
    if request.method == 'POST':
        form_data = DjangoForm(request.POST)
        if form_data.is_valid():
            title = request.POST['title']
            author = request.POST.get('author')
            edition = request.POST['edition']
            price = request.POST['price']
            Pustak.objects.create(title=title, author=author, edition=edition, price=price)
            return redirect('home')
    form = DjangoForm()
    return render(request, 'djangoForm/book.html', context={'forms': form})

def home(request):
    book_data = Pustak.objects.all()
    return render(request, 'djangoForm/base.html', context={'booklist': book_data})