# -*- coding: utf-8 -*-
"""
Created on Sat Feb  4 12:08:04 2023

@author: ba8641
"""
from amplpy import AMPL, modules
modules.load() # load all modules
ampl = AMPL() # instantiate AMPL object

################################################################
#ExaAMPLe
##################################################################
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os

def main():
    # You can install amplpy with "python -m pip install amplpy"
    from amplpy import AMPL

    # Create an AMPL instance
    ampl = AMPL()

    ampl.reset()

    ampl.read(r"C:\Users\BrunoAlvesMaciel\Dropbox\BrunoAlvesMaciel\RIT\Au-Project\Model\ABP.mod")

    #Treat Data
    vaccines.index.name = 'V'
    vaccines.columns = ['u']
    ampl.set_data(vaccines,"V")
    con.index = con['Market']
    con = con.drop('Market', axis = 1)
    con.columns = ['g', 'd']
    ampl.set_data(con,"M")

    #Create antigen table
    ampl.set_data(ant.drop('V1', axis=1),"A")
    k = pd.DataFrame(ant['V1'])
    k.index = ant['V1']
    #t = 0
    #for i in ant.index:
    #    ampl.set_data(k.drop('V1', axis=1)[t],"V1["+i+']')
    #    t+=1
    #st = ''
    original_stdout = sys.stdout
    with open('data.dat','w') as f:
        sys.stdout = f
        for a in range(len(ant)):
            st = 'set V1['+ ant.index[a] + '] := '
            for b in ant.iloc[a,0]:
                st+= str(b) + ' '
            st += ';'
            print(st)
        sys.stdout = original_stdout

    ampl.read_data('data.dat')
    ampl.get_parameter('r').set_values(rp.unstack())

    # Solve
    ampl.option["solver"] = "highs"
    ampl.solve()
    solve_result = ampl.get_value("solve_result")
    if solve_result != "solved":
        raise Exception("Failed to solve (solve_result: {})".format(solve_result))

    # Get objective entity by AMPL name
    tss = ampl.get_objective("TSS").value()
    # Print it
    print("Objective is:", tss)

    # Get the values of the variable Buy in a dataframe object
    X = ampl.get_variable("X").get_values().to_pandas()
    Y = ampl.get_variable("Y").get_values().to_pandas()
    # Print as pandas dataframe

try:
    main()
except Exception as e:
    print(e)
    raise


try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
try:
    with open('README.md', 'r') as fh:
        long_description = fh.read()
except:
    print('No README found')

config = {
    'description': 'My Project Name',
    'author': 'J. Michael Thurman',
    'url':'project_url',
    'download_url':'where to download project',
    'author_email':'jmthurman@cloudbrook.net',
    'version':'0.1',
    'install_requires': ['nose'],
    'packages': ['NAME'],
    'scripts': [],
    'name': 'projectName'
}

setup(**config)

# From setuptools documentation:
# import setuptools

# with open("README.md", "r") as fh:
#     long_description = fh.read()

# setuptools.setup(
#     name="example_pkg",
#     version="0.0.1",
#     author="Example Author",
#     author_email="author@example.com",
#     description="A small example package",
#     long_description=long_description,
#     long_description_content_type="text/markdown",
#     url="https://github.com/pypa/sampleproject",
#     packages=setuptools.find_packages(),
#     classifiers=(
#         "Programming Language :: Python :: 3",
#         "License :: OSI Approved :: MIT License",
#         "Operating System :: OS Independent",
#     ),
# )


l=int(input())
m=[int(i) for i in input().split(" ")]
n=[]
for i in range(l):
      p=m[ :i+1]
      if(sum(p)%2==0):
            n.append(str(sum(p)))
      else:
            n.append(str(p[i]))
print(*n,sep=" ")


import pytest
from CrimeDataAnalyzer import CrimeDataAnalyzer

query = (
    "SELECT "
    "primary_type, description, "
    "COUNTIF(year = 2015) AS arrests_2015, "
    "COUNTIF(year = 2016) AS arrests_2016, "
    "FORMAT('%3.2f',(COUNTIF(year = 2016) - COUNTIF(year = 2015)) / COUNTIF(year = 2015)*100) AS pct_change_2015_to_2016 "
    "FROM "
    "`bigquery-public-data.chicago_crime.crime` "
    "WHERE arrest = TRUE AND year IN (2015, 2016) "
    "GROUP BY primary_type, description "
    "HAVING COUNTIF(year = 2015) > 100 ORDER BY (COUNTIF(year = 2016) - COUNTIF(year = 2015)) / COUNTIF(year = 2015) DESC LIMIT 10"
)

crimeDataAnalyzer = CrimeDataAnalyzer('credentials.json', query)

def test_data_not_empty():
    data = crimeDataAnalyzer.import_data()
    assert not data.empty

def test_import_data():
    data = crimeDataAnalyzer.import_data()
    columns = data.columns
    assert columns[0] == 'primary_type'
    assert columns[1] == 'description'
    assert columns[2] == 'arrests_2015'
    assert columns[3] == 'arrests_2016'
    assert columns[4] == 'pct_change_2015_to_2016'

def test_min_and_max_pct_change():
    data = crimeDataAnalyzer.import_data()

    assert crimeDataAnalyzer.max_pct_change(data) == 45.14
    assert crimeDataAnalyzer.max_pct_change(data) != 60
    assert crimeDataAnalyzer.min_pct_change(data) == 4.27
    assert crimeDataAnalyzer.min_pct_change(data) != 8


from sqlalchemy import Column, Integer, JSON, String

from database import Base

class Games(Base):
    __tablename__ = "games_info"

    id = Column(Integer, primary_key=True, index=True)
    game_info = Column(JSON)
    hash_game = Column(String)


# 3-1 : 럭키 스트레이트

n = input() #입력받는 숫자 문자열
sum = 0

#가운데 인덱스 기준 왼쪽 숫자는 더함
for i in range(len(n)//2):
    sum += int(n[i])
#가운데 인덱스 기준 오른쪽 숫자는 뺌
for i in range(len(n)//2):
    sum -= int(n[i])

#sum의 값이 0이 나오면 럭키스트라이크현
if sum == 0:
    print('LUCKY')
else :
    print('READY')


import requests
import json
import random
import string
import datetime

# from django.utils.timezone import utc

url = "http://localhost:3000/ingest/"

levels = [
    "error",
    "trace",
    "info",
    "warning",
    "fatal",
]

# Function to generate random data
def generate_random_data():
    data = {
        "level": levels[random.randint(0, 4)],
        "message": "The message is: "
        + "".join(random.choices(string.ascii_letters + string.digits, k=15)),
        "resourceId": "server-"
        + "".join(random.choices(string.ascii_letters + string.digits, k=4)),
        "timestamp": (datetime.datetime.now()).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "traceId": "".join(random.choices(string.ascii_letters + string.digits, k=5)),
        "spanId": "span-"
        + "".join(random.choices(string.ascii_letters + string.digits, k=3)),
        "commit": "".join(random.choices(string.ascii_letters + string.digits, k=7)),
        "parentResourceId": "".join(
            random.choices(string.ascii_letters + string.digits, k=8)
        ),
    }
    # print(
    #     f"{data['level']=}\n {data['message']=}\n {data['resourceId']=}\n {data['timestamp']=}\n {data['traceId']=}\n {data['spanId']=}\n "
    # )
    return data

# Number of times to run the command
n = 12

for _ in range(n):
    # Generate random data
    random_data = generate_random_data()
    print(random_data)
    # Send the request
    response = requests.post(
        url, headers={"Content-Type": "application/json"}, data=json.dumps(random_data)
    )

    # Print the response
    print(response.text)


import logging
from threading import RLock

from sawtooth_validator.networking.dispatch import Handler
from sawtooth_validator.networking.dispatch import HandlerResult
from sawtooth_validator.networking.dispatch import HandlerStatus
from sawtooth_validator.journal.timed_cache import TimedCache
from sawtooth_validator.protobuf import network_pb2
from sawtooth_validator.protobuf import validator_pb2

LOGGER = logging.getLogger(__name__)

CACHE_KEEP_TIME = 300

class _LogGuard:
    def __init__(self):
        self.chain_head_not_yet_set = False

class Responder:
    def __init__(self,
                 completer,
                 cache_keep_time=300,
                 cache_purge_frequency=30):
        self.completer = completer
        self.pending_requests = TimedCache(cache_keep_time,
                                           cache_purge_frequency)
        self._lock = RLock()

    def check_for_block(self, block_id):
        # Ask Completer
        if block_id == "HEAD":
            block = self.completer.get_chain_head()
        else:
            block = self.completer.get_block(block_id)
        return block

    def check_for_batch(self, batch_id):
        batch = self.completer.get_batch(batch_id)
        return batch

    def check_for_batch_by_transaction(self, transaction_id):
        batch = self.completer.get_batch_by_transaction(transaction_id)
        return batch

    def already_requested(self, requested_id):
        with self._lock:
            if requested_id in self.pending_requests:
                return True
            return False

    def add_request(self, requested_id, connection_id):
        with self._lock:
            if requested_id in self.pending_requests:
                if connection_id not in self.pending_requests[requested_id]:
                    self.pending_requests[requested_id] += [connection_id]

            else:
                self.pending_requests[requested_id] = [connection_id]

    def get_request(self, requested_id):
        with self._lock:
            return self.pending_requests.get(requested_id)

    def remove_request(self, requested_id):
        with self._lock:
            if requested_id in self.pending_requests:
                del self.pending_requests[requested_id]

class BlockResponderHandler(Handler):
    def __init__(self, responder, gossip):
        self._responder = responder
        self._gossip = gossip
        self._seen_requests = TimedCache(CACHE_KEEP_TIME)
        self._log_guard = _LogGuard()

    def handle(self, connection_id, message_content):
        block_request_message = network_pb2.GossipBlockRequest()
        block_request_message.ParseFromString(message_content)
        if block_request_message.nonce in self._seen_requests:
            LOGGER.debug("Received repeat GossipBlockRequest from %s",
                         connection_id)

            return HandlerResult(HandlerStatus.DROP)

        block_id = block_request_message.block_id
        block = self._responder.check_for_block(block_id)
        if block is None:
            # No block found, broadcast original message to other peers
            # and add to pending requests
            if block_id == "HEAD":
                if not self._log_guard.chain_head_not_yet_set:
                    LOGGER.debug("No chain head available; cannot respond to "
                                 "block requests")
                    self._log_guard.chain_head_not_yet_set = True
            else:
                if not self._responder.already_requested(block_id):
                    if block_request_message.time_to_live > 0:
                        time_to_live = block_request_message.time_to_live
                        block_request_message.time_to_live = time_to_live - 1
                        self._gossip.broadcast(
                            block_request_message,
                            validator_pb2.Message.GOSSIP_BLOCK_REQUEST,
                            exclude=[connection_id])

                        self._seen_requests[block_request_message.nonce] = \
                            block_request_message.block_id

                        self._responder.add_request(block_id, connection_id)
                else:
                    LOGGER.debug("Block %s has already been requested",
                                 block_id)

                    self._responder.add_request(block_id, connection_id)
        else:
            LOGGER.debug("Responding to block requests: %s",
                         block.header_signature)

            block_response = network_pb2.GossipBlockResponse(
                content=block.SerializeToString())

            self._gossip.send(validator_pb2.Message.GOSSIP_BLOCK_RESPONSE,
                              block_response.SerializeToString(),
                              connection_id)

        return HandlerResult(HandlerStatus.PASS)

class ResponderBlockResponseHandler(Handler):
    def __init__(self, responder, gossip):
        self._responder = responder
        self._gossip = gossip

    def handle(self, connection_id, message_content):
        block, message_content = message_content

        open_request = self._responder.get_request(block.header_signature)

        if open_request is None:
            return HandlerResult(status=HandlerStatus.PASS)

        for connection in open_request:
            LOGGER.debug("Responding to block request: Send %s to %s",
                         block.header_signature,
                         connection)
            try:
                self._gossip.send(validator_pb2.Message.GOSSIP_BLOCK_RESPONSE,
                                  message_content,
                                  connection)
            except ValueError:
                LOGGER.debug("Can't send block response %s to closed "
                             "connection %s",
                             block.header_signature,
                             connection)

        self._responder.remove_request(block.header_signature)

        return HandlerResult(HandlerStatus.PASS)

class BatchByBatchIdResponderHandler(Handler):
    def __init__(self, responder, gossip):
        self._responder = responder
        self._gossip = gossip
        self._seen_requests = TimedCache(CACHE_KEEP_TIME)

    def handle(self, connection_id, message_content):
        batch_request_message = network_pb2.GossipBatchByBatchIdRequest()
        batch_request_message.ParseFromString(message_content)
        if batch_request_message.nonce in self._seen_requests:
            LOGGER.debug("Received repeat GossipBatchByBatchIdRequest from %s",
                         connection_id)
            return HandlerResult(HandlerStatus.DROP)

        batch = None
        batch = self._responder.check_for_batch(batch_request_message.id)

        if batch is None:
            # No batch found, broadcast original message to other peers
            # and add to pending requests
            if not self._responder.already_requested(batch_request_message.id):

                if batch_request_message.time_to_live > 0:
                    time_to_live = batch_request_message.time_to_live
                    batch_request_message.time_to_live = time_to_live - 1
                    self._gossip.broadcast(
                        batch_request_message,
                        validator_pb2.Message.GOSSIP_BATCH_BY_BATCH_ID_REQUEST,
                        exclude=[connection_id])

                    self._seen_requests[batch_request_message.nonce] = \
                        batch_request_message.id

                    self._responder.add_request(batch_request_message.id,
                                                connection_id)
            else:
                LOGGER.debug("Batch %s has already been requested",
                             batch_request_message.id)

                self._responder.add_request(batch_request_message.id,
                                            connection_id)
        else:
            LOGGER.debug("Responding to batch requests %s",
                         batch.header_signature)

            batch_response = network_pb2.GossipBatchResponse(
                content=batch.SerializeToString(),
            )

            self._gossip.send(validator_pb2.Message.GOSSIP_BATCH_RESPONSE,
                              batch_response.SerializeToString(),
                              connection_id)

        return HandlerResult(HandlerStatus.PASS)

class BatchByTransactionIdResponderHandler(Handler):
    def __init__(self, responder, gossip):
        self._responder = responder
        self._gossip = gossip
        self._seen_requests = TimedCache(CACHE_KEEP_TIME)

    def handle(self, connection_id, message_content):
        batch_request_message = network_pb2.GossipBatchByTransactionIdRequest()
        batch_request_message.ParseFromString(message_content)
        if batch_request_message.nonce in self._seen_requests:
            LOGGER.debug("Received repeat GossipBatchByTransactionIdRequest"
                         " from %s", connection_id)

            return HandlerResult(HandlerStatus.DROP)

        batch = None
        batches = []
        unfound_txn_ids = []
        not_requested = []
        for txn_id in batch_request_message.ids:
            batch = self._responder.check_for_batch_by_transaction(
                txn_id)

            # The txn_id was not found.
            if batch is None:
                unfound_txn_ids.append(txn_id)
                if not self._responder.already_requested(txn_id):
                    not_requested.append(txn_id)
                else:
                    LOGGER.debug("Batch containing Transaction %s has already "
                                 "been requested", txn_id)

            # Check to see if a previous txn was in the same batch.
            elif batch not in batches:
                batches.append(batch)

            batch = None

        if batches == [] and len(not_requested) == \
                len(batch_request_message.ids):

            if batch_request_message.time_to_live > 0:
                time_to_live = batch_request_message.time_to_live
                batch_request_message.time_to_live = time_to_live - 1
                self._gossip.broadcast(
                    batch_request_message,
                    validator_pb2.Message.
                    GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST,
                    exclude=[connection_id])

                self._seen_requests[batch_request_message.nonce] = \
                    batch_request_message.ids

                for txn_id in batch_request_message.ids:
                    self._responder.add_request(txn_id, connection_id)

        elif unfound_txn_ids != []:
            if not_requested != []:
                if batch_request_message.time_to_live > 0:
                    self._seen_requests[batch_request_message.nonce] = \
                        batch_request_message.ids
                    new_request = \
                        network_pb2.GossipBatchByTransactionIdRequest()
                    # only request batches we have not requested already
                    new_request.ids.extend(not_requested)
                    # Keep same nonce as original message
                    new_request.nonce = batch_request_message.nonce
                    time_to_live = batch_request_message.time_to_live
                    new_request.time_to_live = time_to_live - 1

                    self._gossip.broadcast(
                        new_request,
                        validator_pb2.Message.
                        GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST,
                        exclude=[connection_id])
                    # Add all requests to responder
                    for txn_id in unfound_txn_ids:
                        self._responder.add_request(txn_id, connection_id)
            else:
                # Add all requests to responder
                for txn_id in unfound_txn_ids:
                    self._responder.add_request(txn_id, connection_id)

        if batches != []:
            for batch in batches:
                LOGGER.debug("Responding to batch requests %s",
                             batch.header_signature)

                batch_response = network_pb2.GossipBatchResponse(
                    content=batch.SerializeToString(),
                )

                self._gossip.send(validator_pb2.Message.GOSSIP_BATCH_RESPONSE,
                                  batch_response.SerializeToString(),
                                  connection_id)

        return HandlerResult(HandlerStatus.PASS)

class ResponderBatchResponseHandler(Handler):
    def __init__(self, responder, gossip):
        self._responder = responder
        self._gossip = gossip

    def handle(self, connection_id, message_content):
        batch, message_content = message_content

        open_request = self._responder.get_request(batch.header_signature)

        if open_request is None:
            open_request = []

        requests_to_remove = [batch.header_signature]
        for txn in batch.transactions:
            requests_by_txn = self._responder.get_request(txn.header_signature)
            if requests_by_txn is not None:
                open_request += requests_by_txn
                requests_to_remove += [txn.header_signature]

        for connection in open_request:
            LOGGER.debug("Responding to batch requests: Send %s to %s",
                         batch.header_signature,
                         connection)
            try:
                self._gossip.send(validator_pb2.Message.GOSSIP_BATCH_RESPONSE,
                                  message_content,
                                  connection)
            except ValueError:
                LOGGER.debug("Can't send batch response %s to closed "
                             "connection %s",
                             batch.header_signature,
                             connection)

        for requested_id in requests_to_remove:
            self._responder.remove_request(requested_id)

        return HandlerResult(HandlerStatus.PASS)


import torch
import numpy as np
import affine
import geopandas as gpd
from torch.utils.data import DataLoader
import rasterio.features
import shapely.affinity
from shapely.geometry import Point
from datasets.avalanche_dataset_points import AvalancheDatasetPoints
from utils import data_utils, viz_utils, utils
from utils.lookup import TYP_2_INSTLABEL
import matplotlib.pyplot as plt
from matplotlib import patches

DEBUG = False

class AvalancheInstDataset(AvalancheDatasetPoints):
    """
    SLF Avalanche Dataset. Similar to AvalancheDatasetPoints but for instance segmentation

    :param root_dir: directory in which all data is located
    :param aval_file: shapefile name located in root_dir of the avalanches
    :param region_file: shapefile containing polygon specifying which area will be considered by the Dataset
    :param dem_path: file path of digital elevation model if it is to be used. Default: None
    :param tile_size: patch size to use for training
    :param bands: list of band indexes to read from optical images. Default None gets all
    :param certainty: Which avalanches to consider. Default: all, 1: exact, 2: estimated, 3: guessed
    :param batch_augm (int): whether to perform batch augmentation and how many samples to return
    :param means: list of means for each band in the optical imagery used for standardisation
    :param stds: list of standard deviations for each band in the optical imagery for standardisation
    :param random: whether extracted patches should be shifted randomly or centered on the avalanche
    :param hflip_p: probability of a horizontal flip
    :param rand_rot: max angle in degrees by which to rotate randomly
    :return pytorch dataset to be used with dataloader
    """

    def __getitem__(self, idx):
        """
        Get a sample from the dataset.
        :param idx: index
        :return: [image, rasterised avalanches] as list
        """
        p = self.sample_points.iloc[idx]

        # Get all avalanches in bounding box of possible samples
        bb = self.tile_size * self.pixel_w * 5 / 6
        avals = self.avalanches.cx[p.x - bb:p.x + bb, p.y - bb:p.y + bb]

        # get no of samples according to batch augmentation
        samples = []
        for sample in range(self.ba):
            px_offset = np.array(2 * [self.tile_size]) // 2
            rand_px_offset = np.zeros(2)
            if self.random:
                max_diff = self.tile_size // 3
                rand_px_offset = np.random.randint(-max_diff, max_diff, 2)
                px_offset += rand_px_offset
            vrt_offset = np.array([p.x - self.ulx, self.uly - p.y])
            vrt_offset = vrt_offset / self.pixel_w - px_offset

            image = data_utils.get_all_bands_as_numpy(self.vrt, vrt_offset, self.tile_size,
                                                      means=self.means, stds=self.stds, bands=self.bands)

            # augment brightness and contrast
            if self.random:
                image = self.rand_shift(image)
                image = self.rand_scale(image)

            # add DEM after changing brightness etc but before rotating and flipping
            if self.dem:
                dem_offset = np.array([p.x - self.dem_ulx, self.dem_uly - p.y])
                dem_offset = dem_offset / self.pixel_w - px_offset
                dem_image = data_utils.get_all_bands_as_numpy(self.dem, dem_offset, self.tile_size,
                                                              means=[2800], stds=[1000])
                if self.random:
                    dem_image = self.rand_shift_dem(dem_image)
                image = np.concatenate([image, dem_image], axis=2)

            # -- Apply transforms -----
            angle = self.rand_rotation.get_param()
            image = self.rand_rotation(image, angle)
            image = self.to_tensor(image)
            flip = self.rand_flip.get_param()
            image = self.rand_flip(image, flip)

            # -- Get avalanche instances -----
            rand_offset = rand_px_offset * self.pixel_w
            rand_offset[1] *= -1 # convert from pixel coords to geog. coords
            new_p = Point(np.array([p.x, p.y]) - rand_offset)
            patch_poly = new_p.buffer(self.pixel_w * self.tile_size / 2, cap_style=3)
            bb_patch = patch_poly.bounds
            if DEBUG:
                fig, ax = plt.subplots()
                avals.plot(ax=ax)
                gpd.GeoSeries(shapely.affinity.rotate(patch_poly, -angle, origin=new_p)).boundary.plot(ax=ax,color='red')
                ax.scatter(p.x, p.y, c='red', s=20 ** 2, marker='+')
                plt.show()
                plt.imshow(((image - image.min())/(image.max() - image.min())).permute(1,2,0))
                plt.show()

            masks = np.empty([0, self.tile_size, self.tile_size])
            boxes = np.empty([0, 4])
            labels = np.empty(0, dtype=np.int64)
            for index, aval in avals.iterrows():
                inter = aval.geometry.intersection(patch_poly)
                inter = inter.intersection(shapely.affinity.rotate(patch_poly, -angle, origin=new_p))
                # disregard if visible area is too small
                if inter.area < 400:
                    continue

                # apply same transform as to image
                inter = shapely.affinity.rotate(inter, angle, origin=new_p)
                if flip:
                    inter = shapely.affinity.scale(inter, -1, 1, origin=new_p)

                t = affine.Affine(1.5, 0, bb_patch[0], 0, -1.5, bb_patch[3])
                mask = rasterio.features.rasterize(((inter, 1),), 2 * [self.tile_size], transform=t, dtype=np.single)
                masks = np.append(masks, np.expand_dims(mask, axis=0), axis=0)

                # get bounding box and convert to image coordinates
                bb = ((np.array(inter.bounds) - np.tile(bb_patch[0:2], 2)) / self.pixel_w).round()
                bb = [bb[0], self.tile_size - bb[3], bb[2], self.tile_size - bb[1]]
                boxes = np.append(boxes, np.array(bb, ndmin=2), axis=0)

                labels = np.append(labels, TYP_2_INSTLABEL[aval['typ']])

                if DEBUG:
                    fig, ax = plt.subplots()
                    ax.imshow(mask)
                    rect = patches.Rectangle(bb[0:2], bb[2] - bb[0], bb[3] - bb[1],
                                             edgecolor='r', facecolor='none')
                    ax.add_patch(rect)
                    fig.show()

            targets = {'boxes': torch.from_numpy(boxes).float(),
                       'labels': torch.from_numpy(labels),
                       'masks': self.to_tensor(masks).permute(1, 2, 0)}

            samples.append((image, targets))

        return samples if self.ba > 1 else samples[0]

if __name__ == '__main__':
    # run test

    # home
    data_folder = '/home/patrick/ecovision/data/2018'
    ava_file = 'avalanches0118_endversion.shp'
    region_file = 'Small_test_area.shp'
    dem_path = None  # '/home/patrick/ecovision/data/2018/avalanches0118_endversion.tif'

    # pfpc
    # data_folder = '/home/pf/pfstud/bartonp/slf_avalanches/2018'
    # ava_file = 'avalanches0118_endversion.shp'
    # region_file = 'Val_area_2018.shp'
    # dem_path='/home/pf/pfstud/bartonp/dem_ch/swissalti3d_2017_ESPG2056.tif'
    import random
    random.seed(2)
    np.random.seed(2)
    my_dataset = AvalancheInstDataset(data_folder, ava_file, region_file, tile_size=512, dem_path=dem_path, bands=[1,2,3],
                                      random=True, batch_augm=1, hflip_p=0.5, rand_rot=180)
    dataloader = DataLoader(my_dataset, batch_size=1, shuffle=True, num_workers=0, collate_fn=utils.inst_collate_fn)

    for batch in iter(dataloader):
        fig = viz_utils.viz_aval_instances(*batch, dem=my_dataset.dem, fig_size=2)
        fig.show()
        input('Press key for another sample')


import csv

import matplotlib.pyplot as plt

def lineplotSummaryMD(x_data, y1_data, y2_data, y3_data, y4_data, x_label="", y_label="", title=""):
    _, ax = plt.subplots()
    ax.plot(x_data, y1_data, 'g', lw=4, label=('Теория'))
    ax.plot(x_data, y2_data, 'b--', lw=4, label=('Фиксированная 1'))
    ax.plot(x_data, y3_data, 'r--', lw=4, label=('exp(1)'))
    ax.plot(x_data, y4_data, 'k--', lw=4, label=('exp(1/2)+exp(1/2)'))
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)

def main():

    dataLambdaIn = []
    dataDTheor = []
    dataDFix = []
    dataDExp1 = []
    dataDExp05 = []

    data = []
    with open("D:\Pereezd\Labs\Научка\Model\sizeExp1\model.txt") as f:
        for line in f:
            data.append([float(x) for x in line.split()])

    dataX = []
    for line in data:
        dataX.append(line.pop(0))
        line.pop(0)
        line.pop(0)
        line.pop(0)
        if (dataX[-1] < 1.0):
            dataDExp1.append(line.pop(0))
            line.pop(0)

    data = []
    with open("D:\Pereezd\Labs\Научка\Model\sizeExp0505\model.txt") as f:
        for line in f:
            data.append([float(x) for x in line.split()])

    dataX = []
    for line in data:
        dataX.append(line.pop(0))
        line.pop(0)
        line.pop(0)
        line.pop(0)
        if (dataX[-1] < 1.0):
            dataDExp05.append(line.pop(0))
            line.pop(0)

    data = []
    with open("D:\Pereezd\Labs\Научка\Model\sizeFix\model.txt") as f:
        for line in f:
            data.append([float(x) for x in line.split()])

    dataX = []
    for line in data:
        dataX.append(line.pop(0))
        line.pop(0)
        line.pop(0)
        line.pop(0)
        if (dataX[-1] < 1.0):
            dataDFix.append(line.pop(0))
            line.pop(0)

    data = []
    with open("D:\Pereezd\Labs\Научка\Model\sizeTheor\model.txt") as f:
        for line in f:
            data.append([float(x) for x in line.split()])

    dataX = []
    for line in data:
        dataX.append(line.pop(0))
        line.pop(0)
        line.pop(0)
        line.pop(0)
        if (dataX[-1] < 1.0):
            dataDTheor.append(line.pop(0))
            line.pop(0)

    lineplotSummaryMD(dataLambdaIn, dataDTheor, dataDFix, dataDExp1, dataDExp05, chr(955), "D(" + chr(955) + ")",
                      "D(" + chr(955) + ")")
    plt.legend()
    plt.show()

if __name__ == '__main__':
    main()


# Import necessary libraries and modules
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS

# Create a Flask web application
app = Flask(__name__)

# Enable CORS for the app to allow cross-origin requests
CORS(app)

# Configure the SQLAlchemy database connection
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:turabi!123@localhost/studentreportsyedhusain'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize SQLAlchemy and Marshmallow
db = SQLAlchemy(app)
ma = Marshmallow(app)

# Define the Students model
class Students(db.Model):
    __tablename__ = 'students'
    StudentID = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.String(255))
    CreditsEarned = db.Column(db.Integer)

    def __init__(self, StudentID, Name, CreditsEarned):
        self.StudentID = StudentID
        self.Name = Name
        self.CreditsEarned = CreditsEarned

# Define the StudentSchema for serialization
class StudentSchema(ma.Schema):
    class Meta:
        fields = ('StudentID', 'Name', 'CreditsEarned')

# Initialize StudentSchema instances
student_schema = StudentSchema()
students_schema = StudentSchema(many=True)

# Define a route for the home page
@app.route("/")
def hello_world():
    return "Hello World"

# Route to list all students
@app.route('/listusers', methods=['GET'])
def listusers():
    all_students = Students.query.all()
    results = students_schema.dump(all_students)
    return jsonify(results)

# Route to get details of a specific student
@app.route('/userdetails/<int:StudentID>', methods=['GET'])
def userdetails(StudentID):
    student = Students.query.get(StudentID)
    return student_schema.jsonify(student)

# Route to update a student's information
@app.route('/userupdate/<int:StudentID>', methods=['PUT'])
def userupdate(StudentID):
    student = Students.query.get(StudentID)

    # Extract data from the request JSON
    StudentID = request.json['StudentID']
    Name = request.json['Name']
    CreditsEarned = request.json['CreditsEarned']

    # Update the student's information and commit to the database
    student.StudentID = StudentID
    student.Name = Name
    student.CreditsEarned = CreditsEarned
    db.session.commit()

    return student_schema.jsonify(student)

# Route to delete a student
@app.route('/userdelete/<int:StudentID>', methods=['DELETE'])
def userdelete(StudentID):
    student = Students.query.get(StudentID)
    db.session.delete(student)
    db.session.commit()
    return student_schema.jsonify(student)

# Route to add a new student
@app.route('/useradd', methods=['POST'])
def useradd():
    StudentID = request.json['StudentID']
    Name = request.json['Name']
    CreditsEarned = request.json['CreditsEarned']

    # Create a new student and add to the database
    students = Students(StudentID=StudentID, Name=Name, CreditsEarned=CreditsEarned)
    db.session.add(students)
    db.session.commit()

    return student_schema.jsonify(students)

# Define the Instructors model
class Instructors(db.Model):
    __tablename__ = 'instructors'
    InstructorID = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.String(255))
    Department = db.Column(db.String(255))

    def __init__(self, InstructorID, Name, Department):
        self.InstructorID = InstructorID
        self.Name = Name
        self.Department = Department

# Define the InstructorSchema for serialization
class InstructorSchema(ma.Schema):
    class Meta:
        fields = ('InstructorID', 'Name', 'Department')

# Initialize InstructorSchema instances
instructor_schema = InstructorSchema()
instructors_schema = InstructorSchema(many=True)

# Route to list all instructors
@app.route('/listinstructors', methods=['GET'])
def listinstructors():
    all_instructors = Instructors.query.all()
    results = instructors_schema.dump(all_instructors)
    return jsonify(results)

# Route to get details of a specific instructor
@app.route('/instructordetails/<int:InstructorID>', methods=['GET'])
def instructordetails(InstructorID):
    instructor = Instructors.query.get(InstructorID)
    return instructor_schema.jsonify(instructor)

# Route to update an instructor's information
@app.route('/instructorupdate/<int:InstructorID>', methods=['PUT'])
def instructorupdate(InstructorID):
    instructor = Instructors.query.get(InstructorID)

    # Extract data from the request JSON
    InstructorID = request.json['InstructorID']
    Name = request.json['Name']
    Department = request.json['Department']

    # Update the instructor's information and commit to the database
    instructor.InstructorID = InstructorID
    instructor.Name = Name
    instructor.Department = Department

    db.session.commit()
    return instructor_schema.jsonify(instructor)

# Route to delete an instructor
@app.route('/instructordelete/<int:InstructorID>', methods=['DELETE'])
def instructordelete(InstructorID):
    instructor = Instructors.query.get(InstructorID)
    db.session.delete(instructor)
    db.session.commit()
    return instructor_schema.jsonify(instructor)

# Route to add a new instructor
@app.route('/instructoradd', methods=['POST'])
def instructoradd():
    InstructorID = request.json['InstructorID']
    Name = request.json['Name']
    Department = request.json['Department']

    # Create a new instructor and add to the database
    instructor = Instructors(InstructorID=InstructorID, Name=Name, Department=Department)
    db.session.add(instructor)
    db.session.commit()

    return instructor_schema.jsonify(instructor)

# Define the Courses model with a foreign key to Instructors
class Courses(db.Model):
    __tablename__ = 'courses'
    CourseID = db.Column(db.Integer, primary_key=True)
    CourseTitle = db.Column(db.String(255))
    InstructorID = db.Column(db.Integer, db.ForeignKey('instructors.InstructorID'))

    def __init__(self, CourseID, CourseTitle, InstructorID):
        self.CourseID = CourseID
        self.CourseTitle = CourseTitle
        self.InstructorID = InstructorID

# Define the CourseSchema for serialization
class CourseSchema(ma.Schema):
    class Meta:
        fields = ('CourseID', 'CourseTitle', 'InstructorID')

# Initialize CourseSchema instances
course_schema = CourseSchema()
courses_schema = CourseSchema(many=True)

# Route to list all courses
@app.route('/listcourses', methods=['GET'])
def listcourses():
    all_courses = Courses.query.all()
    results = courses_schema.dump(all_courses)
    return jsonify(results)

# Route to get course details
@app.route('/coursedetails/<int:CourseID>', methods=['GET'])
def coursedetails(CourseID):
    course = Courses.query.get(CourseID)
    return course_schema.jsonify(course)

# Route to update course details
@app.route('/courseupdate/<int:CourseID>', methods=['PUT'])
def courseupdate(CourseID):
    course = Courses.query.get(CourseID)

    # Extract data from the request JSON
    CourseID = request.json['CourseID']
    CourseTitle = request.json['CourseTitle']
    InstructorID = request.json['InstructorID']

    # Update the course's information and commit to the database
    course.CourseID = CourseID
    course.CourseTitle = CourseTitle
    course.InstructorID = InstructorID

    db.session.commit()
    return course_schema.jsonify(course)

# Route to delete a course
@app.route('/coursedelete/<int:CourseID>', methods=['DELETE'])
def coursedelete(CourseID):
    course = Courses.query.get(CourseID)
    db.session.delete(course)
    db.session.commit()
    return course_schema.jsonify(course)

# Route to add a new course
@app.route('/courseadd', methods=['POST'])
def courseadd():
    CourseID = request.json['CourseID']
    CourseTitle = request.json['CourseTitle']
    InstructorID = request.json['InstructorID']

    # Create a new course and add to the database
    course = Courses(CourseID=CourseID, CourseTitle=CourseTitle, InstructorID=InstructorID)
    db.session.add(course)
    db.session.commit()

    return course_schema.jsonify(course)

# Define the Enrollments model
class Enrollments(db.Model):
    __tablename__ = 'enrollments'
    EnrollmentID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    StudentID = db.Column(db.Integer, db.ForeignKey('students.StudentID'))
    CourseID = db.Column(db.Integer, db.ForeignKey('courses.CourseID'))
    Grade = db.Column(db.Integer)

    def __init__(self, StudentID, CourseID, Grade):
        self.StudentID = StudentID
        self.CourseID = CourseID
        self.Grade = Grade

# Define the EnrollmentSchema for serialization
class EnrollmentSchema(ma.Schema):
    class Meta:
        fields = ('EnrollmentID', 'StudentID', 'CourseID', 'Grade')

# Initialize EnrollmentSchema instances
enrollment_schema = EnrollmentSchema()
enrollments_schema = EnrollmentSchema(many=True)

# Route to list all enrollments
@app.route('/enrollments', methods=['GET'])
def list_enrollments():
    all_enrollments = Enrollments.query.all()
    result = enrollments_schema.dump(all_enrollments)
    return jsonify(result)

# Route to get enrollment details
@app.route('/enrollmentdetails/<int:EnrollmentID>', methods=['GET'])
def enrollment_details(EnrollmentID):
    enrollment = Enrollments.query.get(EnrollmentID)
    return enrollment_schema.jsonify(enrollment)

# Route to add a new enrollment
@app.route('/enrollmentadd', methods=['POST'])
def enrollment_add():
    StudentID = request.json['StudentID']
    CourseID = request.json['CourseID']
    Grade = request.json['Grade']

    # Create a new enrollment and add to the database
    enrollment = Enrollments(StudentID=StudentID, CourseID=CourseID, Grade=Grade)
    db.session.add(enrollment)
    db.session.commit()

    return enrollment_schema.jsonify(enrollment)

# Route to update enrollment details
@app.route('/enrollmentupdate/<int:EnrollmentID>', methods=['PUT'])
def enrollment_update(EnrollmentID):
    enrollment = Enrollments.query.get(EnrollmentID)

    # Extract data from the request JSON
    StudentID = request.json['StudentID']
    CourseID = request.json['CourseID']
    Grade = request.json['Grade']

    # Update the enrollment details and commit to the database
    enrollment.StudentID = StudentID
    enrollment.CourseID = CourseID
    enrollment.Grade = Grade

    db.session.commit()
    return enrollment_schema.jsonify(enrollment)

# Route to delete an enrollment
@app.route('/enrollmentdelete/<int:EnrollmentID>', methods=['DELETE'])
def enrollment_delete(EnrollmentID):
    enrollment = Enrollments.query.get(EnrollmentID)
    db.session.delete(enrollment)
    db.session.commit()
    return enrollment_schema.jsonify(enrollment)

# Start the Flask application
if __name__ == '__main__':
    app.run(debug=True)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Gtlions Lai

from tornado import gen

from apps.common.statusconfig import code, statusconfig as sc
from apps.includes.api_bgp.service.actionbase.action_base import ActionBase

class DescribeProtectGroup(ActionBase):
    '''查看可用的防护组列表'''

    def __init__(self, params=None, application=None, *args, **kwargs):
        ActionBase.__init__(self)
        self.params = params
        self.application = application
        #self.application.logger.info(self.init_msg)

    @gen.coroutine
    def run(self):
        res = sc(code.Success)
        res.result = 'Success'

        sql = """SELECT protect_id AS "ProtectGroupID",protect_name AS "ProtectGroupName",max_bps_in/1000/1000/1000 AS "BlackHoleValue",
        b.bandtype_id as "BandwithType",rz.region_id as "Region",rz.zone_id AS "Zone"
        FROM t_protect p,t_bandtype b, (select r.region_id,z.zone_id from t_region r,t_zone z where r.id=z.region) rz
        where p.issys=False and p.status=True and p.bandtype=b.id"""
        if 'Region' in self.params:
            sql += " and rz.region_id='" + self.params['Region'] + "'"
        if 'Zone' in self.params:
            sql += " and rz.zone_id='" + self.params['Zone'] + "'"
        if 'BandwithType' in self.params:
            sql += " and b.bandtype_id='" + self.params['BandwithType'] + "'"

        sql = sql + ' order by "BandwithType","BlackHoleValue","ProtectGroupID"'
        data = self.application.dbcur.queryall_dict(sql)
        data_info = {}
        data_info['ProtectGroupInfo'] = data

        res.redata = data_info
        raise gen.Return(res)


import requests
from datetime import datetime

MY_LAT = 23.179190
MY_LONG = 75.784250

parameters = {
    "lat": MY_LAT,
    "lng": MY_LONG,
    "formatted": 0,
}

response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
sunrise = data["results"]["sunrise"].split("T")[1].split(":")[0]
sunset = data["results"]["sunset"].split("T")[1].split(":")[0]

print(sunrise)
print(sunset)

time_now = datetime.now()

print(time_now.hour)

033/Application Programming Interfaces (API)/Sunset_and_Sunrise_API.py


def gcd(a,b):
    if (a == 0):
        return b
    if (b == 0):
        return a

    if (a == b):
        return a

    if (a > b):
        return gcd(a-b, b)
    return gcd(a, b-a)

def SuperGCD(n):
    ans = 0

    for i in range(1,n+1):
        ans = ans + gcd(i,n)*2**i

    return ans

n = int(input())


import sqlalchemy as sa
from sqlalchemy.orm import exc

from quantum.db import model_base
from quantum.extensions import routerservicetype as rst

class RouterServiceTypeBinding(model_base.BASEV2):
    router_id = sa.Column(sa.String(36),
                          sa.ForeignKey('routers.id', ondelete="CASCADE"),
                          primary_key=True)
    service_type_id = sa.Column(sa.String(36),
                                sa.ForeignKey('servicetypes.id'),
                                nullable=False)

class RouterServiceTypeDbMixin(object):
    """Mixin class to add router service type."""

    def _process_create_router_service_type_id(self, context, router):
        with context.session.begin(subtransactions=True):
            db = RouterServiceTypeBinding(
                router_id=router['id'],
                service_type_id=router[rst.SERVICE_TYPE_ID])
            context.session.add(db)
        return self._make_router_service_type_id_dict(db)

    def _extend_router_service_type_id_dict(self, context, router):
        rsbind = self._get_router_service_type_id_binding(
            context, router['id'])
        if rsbind:
            router[rst.SERVICE_TYPE_ID] = rsbind['service_type_id']

    def _get_router_service_type_id_binding(self, context, router_id):
        query = self._model_query(context, RouterServiceTypeBinding)
        query = query.filter(
            RouterServiceTypeBinding.router_id == router_id)
        return query.first()

    def _make_router_service_type_id_dict(self, router_service_type):
        res = {'router_id': router_service_type['router_id'],
               'service_type_id': router_service_type[rst.SERVICE_TYPE_ID]}
        return self._fields(res, None)


import os
import sys
import argparse

def get_num(line):
    start = line.find('=')
    if start == -1:
        return 0
    else:
        try:
            return int(line[start+1:].strip())
        except:
            print(line)
            exit(1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Stats for preproc results')
    parser.add_argument( '--input', dest='input_dir', type=str
                       , help='input directory'
                       )
    parser.add_argument( '--format', dest='output_format', type=str
                       , help='output format, csv'
                       )
    parser.add_argument('--filter', dest='filter_non_zero', action='store_true')
    parser.add_argument('--no-filter', dest='filter_non_zero', action='store_false')
    parser.add_argument('--discard-full', dest='discard_full', action='store_true')
    parser.set_defaults(input_dir = './results/', output_format = 'csv', filter_non_zero = False, discard_full=False)
    args = parser.parse_args()

    # path, resol, raf, far
    stats = []
    for root, _, files in os.walk(args.input_dir, topdown=False):
        if args.discard_full:
            if 'mochi_full' in root:
                continue
        for name in files:
            path = os.path.join(root, name)
            print(path)
            resol = 0
            raf = 0
            far = 0
            with open(path, 'r') as f:
                for line in f:
                    if 'resol' in line:
                        resol += get_num(line)
                    elif 'raf' in line:
                        raf += get_num(line)
                    elif 'far' in line:
                        far += get_num(line)
            if args.filter_non_zero:
                if resol != 0 or raf != 0 or far != 0:
                    stats.append((path, resol, raf, far))
            else:
                stats.append((path, resol, raf, far))
    output_name = 'stats'
    if args.filter_non_zero:
        output_name += '-filter'
    if args.discard_full:
        output_name += '-no-full'
    if args.output_format == 'csv':
        with open('{}.csv'.format(output_name), 'w') as f:
            f.write('name, resol, raf, far\n')
            for stat in stats:
                f.write(', '.join(str(i) for i in stat) + '\n')


from setuptools import setup

# Imports content of requirements.txt into setuptools' install_requires
with open('deadset/requirements.txt') as f:
      requirements = f.read().splitlines()

# Imports content of README.md into setuptools' long_description
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
      long_description = f.read()

# sets setup up :P
setup(name='deadset',
      version='0.2',
      description="Deadset is a Python 3 module that implements expiration for Redis Keys items.",
      url='https://github.com/buanzo/deadset',
      author='Arturo "Buanzo" Busleiman',
      author_email='buanzo@buanzo.com.ar',
      packages=['deadset'],
      python_requires='>=3.6',
      install_requires=requirements,
      long_description=long_description,
      long_description_content_type='text/markdown',
      zip_safe=False)


import frappe
from erpnext.assets.doctype.asset_movement.asset_movement import AssetMovement

class transfer_asset_movement(AssetMovement):

    def on_submit(self):
        # frappe.msgprint('By')
        doc = self
        if doc.purpose == 'Transfer':
            for asst in doc.assets:
                frappe.db.set_value('Asset', asst.asset,
                                    {'custodian': asst.responsiblity,
                                    'location': asst.target_location},update_modified=False)

    def on_cancel(self):
        # frappe.msgprint('Hllo')
        doc = self
        if doc.purpose == 'Transfer':
            for asst in doc.assets:
                frappe.db.set_value('Asset', asst.asset,
                                    {'custodian': asst.from_employee,
                                    'location': asst.source_location},update_modified=False)


# post processing of simple corrosion results

import os
import numpy as np
import matplotlib as mpl
#mpl.use("pgf")
pgf_with_custom_preamble = {
    "figure.figsize": [3.54, 2.655],
    #"figure.subplot.bottom": 0.14,
    #"figure.subplot.top": 0.93,
    "font.family": "serif", # use serif/main font for text elements
    "font.size": 9, # use font size
    "text.usetex": True,    # use inline math for ticks
    #'text.latex.unicode': True,
    #"pgf.rcfonts": False,   # don't setup fonts from rc parameters
    #"pgf.preamble": [
        #r'\usepackage{fontspec}',         # load additional packages
        #]
}
mpl.rcParams.update(pgf_with_custom_preamble)
import matplotlib.pyplot as plt
plt.ion()
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from mpldatacursor import datacursor

from corrosion.simpleCorrosion import *
from pyre.distributions import Lognormal

def range(smp, percentile1, percentile2):
    return (np.percentile(smp, percentile1), np.percentile(smp, percentile2))

# copy codes from simpleCorrosionLHS
def main(component_type, service_time, icorr_mean, str_yr=None):
    np.random.seed(64)

    if str_yr is None or str_yr < FRP_DESIGN_YR:
        str_yr = 0
    # beam object
    if str_yr == 0:
        rcBeam = generateRcBeamForMC(component_type)
    else:
        frpBeam = generateFrpBeamForMC(component_type)
        frpBeamDesign = generateFrpBeamForDesign(component_type)
        # get initial_design_capacity
        if 'f' in component_type.lower() or 'd' in component_type.lower():
            initial_design_capacity = designFlexStrength(frpBeamDesign, np.array([0]))
        else:
            initial_design_capacity = designShearStrength(frpBeamDesign, np.array([0]))
    # initial variables
    if 'f' in component_type.lower():
        cover_mean = FLEX_COVER_MEAN
        cover_cov = FLEX_COVER_COV
        distance12 = FLEX_DISTANCE12
        region1_no = FLEX_REGION1_NO
        region2_no = FLEX_REGION2_NO
        ds1_mean = FLEX_DS1_MEAN
        ds2_mean = FLEX_DS2_MEAN
        ds1_cov = FLEX_DS1_COV
        ds2_cov = FLEX_DS2_COV
    elif 's' in component_type.lower():
        cover_mean = SHEAR_COVER_MEAN
        cover_cov = SHEAR_COVER_COV
        distance12 = SHEAR_DISTANCE12
        region1_no = SHEAR_REGION1_NO
        region2_no = SHEAR_REGION2_NO
        ds1_mean = SHEAR_DS1_MEAN
        ds2_mean = SHEAR_DS2_MEAN
        ds1_cov = SHEAR_DS1_COV
        ds2_cov = SHEAR_DS2_COV
    elif 'd' in component_type.lower():
        cover_mean = DECK_COVER_MEAN
        cover_cov = DECK_COVER_COV
        distance12 = DECK_DISTANCE12
        region1_no = DECK_REGION1_NO
        region2_no = DECK_REGION2_NO
        ds1_mean = DECK_DS1_MEAN
        ds2_mean = DECK_DS2_MEAN
        ds1_cov = DECK_DS1_COV
        ds2_cov = DECK_DS2_COV

    # percentage array for LHS
    cdf_lhs = np.linspace(0.5/N_LHS_SMP, 1.-0.5/N_LHS_SMP, num=N_LHS_SMP)
    # concrete cover
    concrete_cover = Lognormal('Xc', cover_mean, cover_mean*cover_cov)
    xc1_smp = concrete_cover.rv.ppf(cdf_lhs)
    xc1_smp = np.random.permutation(xc1_smp)
    xc2_smp = xc1_smp + distance12
    # diffusion coefficient
    diffusion_coefficient = Lognormal('Dc', DC_MEAN, DC_MEAN*DC_COV)
    dc_smp = diffusion_coefficient.rv.ppf(cdf_lhs)
    dc_smp = np.random.permutation(dc_smp)
    # surface chloride
    surface_chloride = Lognormal('C0', C0_MEAM, C0_MEAM*C0_COV)
    c0_smp = surface_chloride.rv.ppf(cdf_lhs)
    c0_smp = np.random.permutation(c0_smp)
    # critical chloride
    critical_chloride = Lognormal('Ccr', CCR_MEAN, CCR_MEAN*CCR_COV)
    ccr_smp = critical_chloride.rv.ppf(cdf_lhs)
    ccr_smp = np.random.permutation(ccr_smp)
    # corrosion initiation time
    ti1_smp = xc1_smp**2 / (4.*dc_smp) * (spc.erfinv((c0_smp-ccr_smp)/c0_smp))**(-2)
    ti2_smp = xc2_smp**2 / (4.*dc_smp) * (spc.erfinv((c0_smp-ccr_smp)/c0_smp))**(-2)
    # initial reinforcement
    rebar_region1 = Lognormal('ds1', ds1_mean, ds1_cov)
    ds1_smp = rebar_region1.rv.ppf(cdf_lhs)
    ds1_smp = np.random.permutation(ds1_smp)
    rebar_region2 = Lognormal('ds2', ds2_mean, ds2_cov)
    ds2_smp = rebar_region2.rv.ppf(cdf_lhs)
    ds2_smp = np.random.permutation(ds2_smp)
    resistance_mean = []
    resistance_cov = []
    resistance_smp = []
    # corrosion rate
    corrosion_current = Lognormal('icorr', icorr_mean, icorr_mean*ICORR_COV)
    icorr_smp = corrosion_current.rv.ppf(cdf_lhs)
    icorr_smp = np.random.permutation(icorr_smp)
    corrosion_rate = icorr_smp * 0.0232
    if service_time[0] != 0:
        service_time = np.insert(service_time, 0, 0)
    for indx,t in enumerate(service_time+str_yr):
        # time after corrosion
        t_corrosion1 = t+str_yr - ti1_smp
        t_corrosion1[t_corrosion1<0] = 0
        t_corrosion2 = t+str_yr - ti2_smp
        t_corrosion2[t_corrosion2<0] = 0
        # residual reinforcement
        ds1t_smp = ds1_smp - t_corrosion1*corrosion_rate
        ds1t_smp[ds1t_smp<0] = 0
        ds2t_smp = ds2_smp - t_corrosion2*corrosion_rate
        ds2t_smp[ds2t_smp<0] = 0
        Ast_smp = np.pi/4 * (ds1t_smp**2*region1_no + ds2t_smp**2*region2_no)
        if str_yr == 0:
            rcBeam.Ast = Ast_smp
            rcBeam.Asvt = Ast_smp
            if 'f' in component_type.lower() or 'd' in component_type.lower():
                rsmp = rcBeam.flexCapacity()
            else:
                rsmp = rcBeam.shearCapacity()
            cost = 0
        elif 'f' in component_type.lower():
            #initial_design_capacity = 1.25*M_DCDW_NOM + 1.75*(M_LLIM_NOM+M_DESIGN_LANE)*LDF_FLEX
            frpBeamDesign.ds = np.array([np.mean(ds1t_smp)])
            frpBeamDesign.Ast = np.array([np.mean(Ast_smp)])
            frpBeam.ds = ds1t_smp
            frpBeam.Ast = Ast_smp
            if t == str_yr:
                # design FRP strengthening
                design_frp = lambda tfrp: designFlexStrength(frpBeamDesign,
                    tfrp) - initial_design_capacity
                tfrp, infodict, ier, mesg = fsolve(design_frp, 0.11, full_output=True)
                if tfrp[0]<0:
                    tfrp = 0.0
                elif tfrp[0]>MAX_LAYER * 0.166:
                    tfrp = MAX_LAYER * 0.166
                else:
                    tfrp = tfrp[0]
                cost = GIRDER_NUM*tfrp*BFRP_NOM*(SPAN_NOM-2*PLATE2SUPPORT_NOM)*FRP_UNIT_PRICE
                frpBeam.tfrp = tfrp * np.ones(N_LHS_SMP)
            rsmp = frpBeam.flexCapacity()
        elif 's' in component_type.lower():
            #initial_design_capacity = 1.25*V_DCDW_NOM + 1.75*(V_LLIM_NOM+V_DESIGN_LANE)*LDF_SHEAR
            frpBeamDesign.dsv = np.array([np.mean(ds1t_smp)])
            frpBeamDesign.Asvt = np.array([np.mean(Ast_smp)])
            frpBeam.dsv = ds1t_smp
            frpBeam.Asvt = Ast_smp
            if t == str_yr:
                # design FRP strengthening
                design_frp = lambda tfrpv: designShearStrength(frpBeamDesign,
                    tfrpv) - initial_design_capacity
                tfrpv, infodict, ier, mesg = fsolve(design_frp, 0.001, full_output=True)
                if tfrpv[0]<0:
                    tfrpv = 0.0
                elif tfrpv[0]>MAX_LAYER * 0.166:
                    tfrpv = MAX_LAYER * 0.166
                else:
                    tfrpv = tfrpv[0]
                cost = GIRDER_NUM*tfrpv*WFRPV_NOM*(BEAM_HEIGHT_NOM*2+WEB_WIDTH_NOM)*\
                    (SPAN_NOM/3.*2/SFRPV_NOM)*FRP_UNIT_PRICE
                frpBeam.tfrpv = tfrpv * np.ones(N_LHS_SMP)
            rsmp = frpBeam.shearCapacity()
        elif 'd' in component_type.lower():
            #initial_design_capacity = 1.25*M_DCDW_DECK_NOM + 1.75*(1.2*M_LLIM_DECK_NOM)
            frpBeamDesign.bfrp = frpBeamDesign.b/FRP_DECK_RATIO
            frpBeam.bfrp = frpBeam.b/FRP_DECK_RATIO
            frpBeamDesign.ds = np.array([np.mean(ds1t_smp)])
            frpBeamDesign.Ast = np.array([np.mean(Ast_smp)])
            frpBeam.ds = ds1t_smp
            frpBeam.Ast = Ast_smp
            if t == str_yr:
                # design FRP strengthening
                design_frp = lambda tfrp: designFlexStrength(frpBeamDesign,
                    tfrp) - initial_design_capacity
                tfrp, infodict, ier, mesg = fsolve(design_frp, 0.11, full_output=True)
                if tfrp[0]<0:
                    tfrp = 0.0
                elif tfrp[0]>MAX_LAYER * 0.166:
                    tfrp = MAX_LAYER * 0.166
                else:
                    tfrp = tfrp[0]
                cost = (GIRDER_NUM-1)*tfrp*(SPAN_NOM/FRP_DECK_RATIO)*\
                    (SPAN_DECK_NOM-2*PLATE2SUPPORT_DECK_NOM)*FRP_UNIT_PRICE
                frpBeam.tfrp = tfrp * np.ones(N_LHS_SMP)
            rsmp = frpBeam.flexCapacity()

        rmean = np.mean(rsmp)
        rstd = np.std(rsmp)
        rcov = rstd/rmean
        resistance_mean.append(rmean)
        resistance_cov.append(rcov)
        resistance_smp.append(rsmp)

    return ti1_smp, np.array(resistance_smp), np.array(resistance_mean), np.array(resistance_cov)

if __name__ == '__main__':
    service_time = np.arange(START_AGE+TIME_INTERVAL,END_AGE+TIME_INTERVAL,TIME_INTERVAL)
    if not os.path.isfile('./data/deterioration_bbb.npz'):
        # flexural data
        flex_ti1_smp, resistance_rc, flex_mean, flex_cov = main('flexure', service_time, 1)
        dummy, resistance_frp, dummy, dummy = main('flexure', service_time, 1, 30)
        # shear data
        shear_ti1_smp, dummy, shear_mean, shear_cov = main('shear', service_time, 1)
        # deck data
        deck_ti1_smp, dummy, deck_mean, deck_cov = main('deck', service_time, 1)
    else:
        deterioration = np.load('./data/deterioration_bbb.npz')
        flex_ti1_smp = deterioration['flex_ti1_smp']
        resistance_rc = deterioration['resistance_rc']
        flex_mean = deterioration['flex_mean']
        flex_cov = deterioration['flex_cov']
        resistance_frp = deterioration['resistance_frp']
        shear_ti1_smp = deterioration['shear_ti1_smp']
        shear_mean = deterioration['shear_mean']
        shear_cov = deterioration['shear_cov']
        deck_ti1_smp = deterioration['deck_ti1_smp']
        deck_mean = deterioration['deck_mean']
        deck_cov = deterioration['deck_cov']

    plt.close('all')
    #plt.rc('font', family='serif', size=12)

    # corrosion initiation
    num_bins = 100
    plt.figure()
    plt.hist(flex_ti1_smp, bins=num_bins, # range=range(flex_ti1_smp, 0,100),
            normed=True, color='blue', histtype='step', label='Flexure (girder)')
    plt.hist(shear_ti1_smp, bins=num_bins, # range=range(shear_ti1_smp, 0,100),
            normed=True, color='red', histtype='step', label='Shear (girder)')
    plt.hist(deck_ti1_smp, bins=num_bins, # range=range(deck_ti1_smp, 0,100),
            normed=True, color='green', histtype='step', label='Deck')
    plt.xlim((0, 60))
    plt.xlabel('Time (year)')
    plt.ylabel('PDF')
    annotate_text = u'{label}'
    datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    # resistance histogram
    num_bins = 20
    plt.figure()
    resistance_rc_mean = np.mean(resistance_rc[0])
    resistance_rc_std = np.std(resistance_rc[0])
    lognormal_rc = Lognormal('rc', resistance_rc_mean, resistance_rc_std).rv
    resistance_frp_mean = np.mean(resistance_frp[0])
    resistance_frp_std = np.std(resistance_frp[0])
    lognormal_frp = Lognormal('frp', resistance_frp_mean, resistance_frp_std).rv
    plt.hist(resistance_rc[0], bins=num_bins, color='blue', facecolor='none',
            ls='solid', normed=True)
    plt.hist(resistance_frp[0], bins=num_bins, color='red', facecolor='none',
            ls='dashed', normed=True)
    plt.ylim((0,0.002))
    #ax = plt.gca()
    #ax.annotate('initial strength', xy=(1981, 5.e-4), xytext=(2387, 7.29e-4),
            #arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k', shrinkB=0))
    #ax.annotate('after strengthening', xy=(2079,9.6e-4), xytext=(2387, 1.2e-3),
            #arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k', shrinkB=0))
    xlims = plt.xlim()
    xticks = np.linspace(xlims[0], xlims[1], 500)
    plt.plot(xticks, lognormal_rc.pdf(xticks), 'b', label='Initial strength')
    plt.plot(xticks, lognormal_frp.pdf(xticks), 'r', label='After strengthening')
    plt.xlabel('Flexural strength of bridge girders (kN-m)')
    plt.ylabel('PDF')
    annotate_text = u'{label}'
    datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    # resistance history
    f, (ax1, ax2) = plt.subplots(2, sharex=True)
    # MC reults
    ax1.plot(service_time, flex_mean[1:]/flex_mean[0], 'b-', label='Flexure (girder)' )
    ax1.plot(service_time, shear_mean[1:]/shear_mean[0], 'r-', label='Shear (girder)' )
    ax1.plot(service_time, deck_mean[1:]/deck_mean[0], 'g-', label='Deck' )
    ax2.plot(service_time, flex_cov[1:], 'b--', label='Flexure (girder)' )
    ax2.plot(service_time, shear_cov[1:], 'r--', label='Shear (girder)' )
    ax2.plot(service_time, deck_cov[1:], 'g--', label='Deck' )
    # figure settings
    ax2.set_xlabel('Time (year)')
    #ax1.set_ylabel('strengh mean (kN-m)')
    #ax2.set_ylabel('strength COV')
    f.text(0.03, 0.5, r'Normalized resistance', ha='center', va='center', rotation='vertical')
    ax1.annotate('Mean values', xy=(5, 0.8), bbox=dict(boxstyle="round", fc="w"))
    ax2.annotate('Coefficient of variation', xy=(5, 0.145), bbox=dict(boxstyle="round", fc="w"))
    ax1.set_ylim((0.75, 1.001))
    #majorFormatter = FormatStrFormatter('%.2e')
    #ax1.yaxis.set_major_formatter(majorFormatter)
    #ax2.yaxis.set_major_formatter(majorFormatter)
    #ax1.annotate('mean (kN-m)', xy=(50.8, 1578), xytext=(19, 1521),
            #arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k', shrinkB=0))
    #ax2.annotate('COV', xy=(50.4, 0.136), xytext=(20, 0.1369),
            #arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k', shrinkB=0))
    #ax1.legend(loc='lower left', prop={'size':12})
    #ax2.legend(loc='lower right', prop={'size':12})
    datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    #plt.show()


import numpy as np
from lib.utils import *
import glob

# hyper parameters
label_path = "../dataset/yolov2_fruits_dataset/labels/"
n_anchors = 5
loss_convergence = 1e-5
image_width = 416
image_height = 416
grid_width = 13
grid_height = 13

boxes = []
label_files = glob.glob("%s/*" % label_path)
for label_file in label_files:
    with open(label_file, "r") as f:
        label, x, y, w, h = f.read().strip().split(" ")
        boxes.append(Box(0, 0, float(w), float(h)))

# initial centroids
centroid_indices = np.random.choice(len(boxes), n_anchors)
centroids = []
for centroid_index in centroid_indices:
    centroids.append(boxes[centroid_index])

# do k-means
def do_kmeans(n_anchors, boxes, centroids):
    loss = 0
    groups = []
    new_centroids = []
    for i in range(n_anchors):
        groups.append([])
        new_centroids.append(Box(0, 0, 0, 0))

    for box in boxes:
        min_distance = 1
        group_index = 0
        for centroid_index, centroid in enumerate(centroids):
            distance = (1 - box_iou(box, centroid))
            if distance < min_distance:
                min_distance = distance
                group_index = centroid_index
        groups[group_index].append(box)
        loss += min_distance
        new_centroids[group_index].w += box.w
        new_centroids[group_index].h += box.h

    for i in range(n_anchors):
        new_centroids[i].w /= len(groups[i])
        new_centroids[i].h /= len(groups[i])

    return new_centroids, groups, loss

# iterate k-means
new_centroids, groups, old_loss = do_kmeans(n_anchors, boxes, centroids)
while(True):
    new_centroids, groups, loss = do_kmeans(n_anchors, boxes, new_centroids)
    print("loss = %f" % loss)
    if abs(old_loss - loss) < loss_convergence:
        break
    old_loss = loss

# print result
for centroid in centroids:
    print(centroid.w * grid_width, centroid.h * grid_height)


""" Shows more complex execution usage"""
from enum import Enum

import dearpygui.core as c
import dearpygui.simple as s

class Direction(str, Enum):
    """
    An enum to indicate which of the 5 line types should be rendered
    """

    up = "up"
    down = "down"
    left = "left"
    right = "right"
    center = "center"

class Number:
    """
    Class for creating a single 'digital' number display
    """

    def __init__(self, color=None):
        self.name = "Canvas"
        if not color:
            self.color = [120, 255, 120]
        else:
            self.color = color

    def clear(self):
        """
        Clears the canvas drawing
        """
        c.clear_drawing(self.name)

    def draw_item(
        self,
        x_offset=0,
        y_offset=0,
        direction: Direction = Direction.left,
        tag: str = None,
    ):
        """
        Creates a line in the number box in the digital clock format
        :param x_offset: x translation magnitude, as x gets larger, the line shifts right
        :param y_offset: y translation magnitude, as y increases the line shifts down
        :param direction: Which type of line to render
        :param tag: string to tag the line with
        :return: drawn polygon on self.canvas
        """
        if tag is None:
            tag = str(direction.value)
        translate = lambda coords: [
            coords[0] + x_offset,
            coords[1] + y_offset,
        ]

        if direction == Direction.left:
            position = [
                (0.0, 0.0),
                (20.0, 20.0),
                (20.0, 60.0),
                (0.0, 80.0),
            ]
        elif direction == Direction.up:
            position = [
                (0.0, 0.0),
                (20.0, 20.0),
                (60.0, 20.0),
                (80.0, 0.0),
            ]
        elif direction == Direction.down:
            position = [
                (80.0, 20.0),
                (60.0, 0.0),
                (20.0, 0.0),
                (0.0, 20.0),
            ]
        elif direction == Direction.right:
            position = [
                (20.0, 0.0),
                (0.0, 20.0),
                (0.0, 60.0),
                (20.0, 80.0),
            ]
        else:
            position = [
                (0.0, 10.0),
                (10.0, 0.0),
                (50.0, 0.0),
                (60.0, 10.0),
                (50.0, 20.0),
                (10.0, 20.0),
                (0.0, 10.0),
            ]

        c.draw_polygon(
            self.name,
            points=list(map(translate, position)),
            color=[255, 255, 255, 0],
            fill=self.color,
            tag=tag,
        )

    def execute(self, *_args):
        """
        Our execution callback again
        :param _args: catching sender/data
        :return: executed command
        """
        command = c.get_value("command##input")
        exec(command)

    def run(self):
        """
        A very basic stand-aloen run method to show what this looks like by default
        :return: General number display example
        """

        window_args = dict(
            autosize=False,
            height=200,
            width=200,
            x_pos=0,
            y_pos=0,
        )
        with s.window("Drawing", **window_args):
            c.add_drawing(
                self.name, width=90, height=150
            )

        with s.window(
            "command##window",
            autosize=True,
            y_pos=200,
            x_pos=0,
        ):
            c.add_input_text(
                name="command##input",
                width=600,
                height=300,
                multiline=True,
                on_enter=True,
                callback=self.execute,
            )

        c.start_dearpygui()

if __name__ == "__main__":
    num = Number()
    num.run()


import json
import pandas as pd

df = pd.read_csv('data/all-seasons.csv')
dict_groupedByEpisode = []

# Quelle: https://stackoverflow.com/questions/35969611/csv-to-nested-json

# gibt an welche Datentypen aus der Excel ausgelesenw werden sollen dadurch, dass Keys angebeben werden
def get_nested_rec(key, grp):
    rec = {'Season': key[0], 'Episode': key[1], 'Character': key[2]}
    for field in ['Line']:
        rec[field] = list(grp[field].unique())
    return rec

# Funktion sagt wie die Daten groupert werden sollen und gibt ein Dict zurück, das nach Episoden groupiert ist
def get_formatted_corpus():
    for key, grp in df.groupby(['Season', 'Episode', 'Character']):
        rec = get_nested_rec(key, grp)
        dict_groupedByEpisode.append(rec)
    return dict_groupedByEpisode

dict_groupedByEpisode = get_formatted_corpus()

dict_groupedByEpisode = dict(data=dict_groupedByEpisode)
# print(json.dumps(dict_groupedByEpisode, indent=4))

with open('data/dataByEpisode.json', 'w') as fp:
    json.dump(dict_groupedByEpisode, fp, indent=4)

####################################

dict_groupedBySeason = []

# gibt an welche Datentypen aus der Excel ausgelesenw werden sollen dadurch, dass Keys angebeben werden
def get_nested_rec1(key, grp):
    rec = {'Season': key[0], 'Character': key[1]}
    for field in ['Episode', 'Line']:
        rec[field] = list(grp[field].unique())
    return rec

# Funktion sagt wie die Daten groupert werden sollen und gibt ein Dict zurück, das nach Season groupiert ist
def get_formatted_corpus1():
    for key, grp in df.groupby(['Season', 'Character']):
        rec = get_nested_rec1(key, grp)
        dict_groupedBySeason.append(rec)
    return dict_groupedBySeason

dict_groupedBySeason = get_formatted_corpus1()
dict_groupedBySeason = dict(data=dict_groupedBySeason)
# print(json.dumps(dict_groupedBySeason, indent=4))

with open('data/dataBySeason.json', 'w') as fp:
    json.dump(dict_groupedBySeason, fp, indent=4)

###########################

dict_groupedByCharacter = []

# gibt an welche Datentypen aus der Excel ausgelesenw werden sollen dadurch, dass Keys angebeben werden
def get_nested_rec2(key, grp):
    rec = {'Character': key[0]}
    for field in ['Character', 'Line']:
        rec[field] = list(grp[field].unique())
    return rec

# Funktion sagt wie die Daten groupert werden sollen und gibt ein Dict zurück, das nach Charackter groupiert ist
def get_formatted_corpus2():
    for key, grp in df.groupby(['Character']):
        rec = get_nested_rec2(key, grp)
        dict_groupedByCharacter.append(rec)
    return dict_groupedByCharacter

dict_groupedByCharacter = get_formatted_corpus2()
dict_groupedByCharacter = dict(data=dict_groupedByCharacter)
# print(json.dumps(dict_groupedByCharacter, indent=4))

with open('data/dataByCharacter.json', 'w') as fp:
    json.dump(dict_groupedByCharacter, fp, indent=4)


# coding: utf-8

# In[ ]:

def coulombic_efficiency(alpha,Ku,N_C):
    import scipy.constants as sc
    pi = sc.pi
    eta_C = ((1-alpha)/Ku)**(1/8)*pi*N_C/(1+2*pi*N_C**(1/4))
    return eta_C


'''
Proof of concept to download files quickly from AIS from command line.
It only took about 30 seconds to get a 1GB sized file from AIS to our
DeepNote storage.
'''

import time
from datetime import timedelta
import subprocess
import datetime
import sys

data_source = "https://coast.noaa.gov/htdata/CMSP/AISDataHandler/2022/"

print('Data source:', data_source)
print('Started download:',
      datetime.datetime.now() - timedelta(hours=7), '\n')

start = time.time()

destination_path = "./data/"
filename = sys.argv[1]

s1 = time.time()
destination = destination_path + filename

print('Downloading "{}" to "{}"'.format(filename, destination))
subprocess.run(["curl", "-o", destination, data_source + filename])

print('  Unzipping...')
subprocess.run(["unzip", destination, "-d", destination_path])

print('  Deleting...')
subprocess.run(["rm", destination])

e1 = time.time()
print('  Elapsed:', str(timedelta(seconds=e1 - s1)))

end = time.time()

print("\nTotal time elapsed:", str(timedelta(seconds=end - start)))
print('Done downloading:', datetime.datetime.now() - timedelta(hours=7))


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs

class ZhihuPipeline(object):
    def process_item(self, item, spider):
        return item

import json

class JsonWriterPipeline(object):

    def __init__(self):
        self.file = codecs.open('items.json', 'w', encoding="utf-8")

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item

import pymongo

from scrapy.conf import settings
from scrapy.exceptions import DropItem

class MongoDBPipeline(object):

    def __init__(self, collection_name, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.collection_name = collection_name

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            collection_name= crawler.settings.get('MONGO_COLLECTION'),
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'circle')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
        self.collection = self.db[self.collection_name]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        matching_item = self.collection.find_one({
            'atoken': item['atoken']
        })
        if matching_item is not None:
            raise DropItem("Duplicate item found: %s" % item['atoken'])
        else:
            self.collection.insert(dict(item))
        return item


import json
import sys

if __name__ == "__main__":

	NNode = sys.argv[1]
	FileName = sys.argv[2]
	sheetName = sys.argv[3]
	NDay = int(sys.argv[4])

	import xlrd
	wb = xlrd.open_workbook('../Data/Solar/'+ FileName+ '.xlsx', on_demand = True)
	# Loads only current sheets to memory
	ws = wb.sheet_by_name(sheetName)
	SolarData = [[ws.cell(24*j + i + 1, 3).value for i in range(24)] for j in range(NDay)]

	f = open('../../ERCOTGridComponent/SyntheticBusConstructionMethod/src/'+str(NNode)+'BusData.json','r')
	data = json.load(f)
	SolarScenarioDatabyCluster = []
	TotalSolarCapacity = 0

	for n,NodeData in enumerate(data):
		#print('NodeData[weightdict]:', NodeData['weightdict'])
		for key,val in enumerate(NodeData['weightdict']):
			#print('key val:', key, val)
			for k,v in val.items():
				#print('k v:', k, v)
				if k == 'Solar Photovoltaic':
					#print('v:', k, v)
					TotalSolarCapacity += v

	print('TotalSolarCapacity:', TotalSolarCapacity)

	for n,NodeData in enumerate(data):
		for key,val in enumerate(NodeData['weightdict']):
			for k,v in val.items():
				if k == 'Solar Photovoltaic':
					#print('checking:', k, v)
					SolarSharebyBus = [[round(SolarData[j][i]*(v/TotalSolarCapacity),2) for i in range(24)] for j in range(NDay)]
					#print('SolarSharebyBus: ', SolarSharebyBus)
					SolarScenarioDatabyCluster.append({NodeData['bus']:SolarSharebyBus})

	#print('SolarScenarioDatabyCluster:' , SolarScenarioDatabyCluster)
	f = open(FileName +  '.NB' + str(NNode) +'.json','w')
	json.dump(SolarScenarioDatabyCluster, f)
	f.close()


#!/usr/bin/env python3

import requests
from random import random

from bs4 import BeautifulSoup

def insultgenerator(sender, receiver):

	# Name of the player sending an insult
	sname = sender['name']
	# Name of the insult's victim
	rname = receiver['name']

	# Get a random number to randomize behaviour of insult button
	rnd = random()

	# If the insulting player is done, this message might be displayed
	if sender['finished'] and rnd < 0.7:
		insulttext = 'Why don\'t you shut up, %s, you have no reason to complain!' % (sname)
	# There is a 20% chance that no random words are included in the message
	elif rnd < 0.2:
		if rnd < 0.1:
			insulttext = '%s blames %s for their poor performance.' % (sname, rname)
		else:
			insulttext = '%s is fuming about this!' % (sname)
	elif rnd <  0.7:
		# Get adjectives and nouns from APIs, use one adjetive to search for a related noun
		adjectives_api = 'https://insult.mattbas.org/api/adjective'
		adj1 = requests.get(adjectives_api).text
		adj2 = requests.get(adjectives_api).text
		adj3 = requests.get(adjectives_api).text

		noun_api = 'http://api.datamuse.com/words?max=1&rel_jja=' + adj3
		noun = requests.get(noun_api).json()[0]['word']

		# Further special cases for not having cards yet, having received a penalty for late UNO, or being the king
		if not sender['has_received_initial_cards'] and rnd < 0.6:
			insulttext = 'Even before his game has started, %s feels the need to call %s a %s, %s, %s...' % (sname, rname, adj2, adj3, noun)
		elif sender['penalty'] > 0:
			insulttext = 'Being a %s %s, %s is unable to say "UNO" fast enough...' % (adj3, noun, sname)
		elif sender['king']:
			insulttext = 'By royal decree, the crown declares %s a %s, %s %s!' % (rname, adj1, adj2, noun)
		else:
			# Standard insult
			insulttext = '%s just called %s a %s, %s %s!' % (sname, rname, adj1, adj2, noun)
	elif rnd < 0.8:
		insult_api = 'https://www.rappad.co/api/battles/random_insult'
		insult = requests.get(insult_api).json()

		insulttext = '%s yells at %s: %s' % (sname, rname, insult["insult"])

	else:
		insult_api = 'https://www.kassoon.com/dnd/vicious-mockery-insult-generator/'
		insult = requests.get(insult_api).text
		soup = BeautifulSoup(insult, 'html.parser')

		insulttext = soup.body.find_all('p')[3].contents[0]

	return insulttext


#######################################################################
#             Computational and differential Geometry                 #
#                         Second Homework                             #
#                 Andres Felipe Florian Quitian                       #
#######################################################################

import numpy as np
import pandas as pd
from scipy.spatial import Voronoi, voronoi_plot_2d
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from scipy.spatial.distance import euclidean, cdist
import matplotlib.path as mplPath
import matplotlib.pyplot as plt

class FlightOperations:

    """ Class FlightOperations that represents a set of airports
        and its corresponding Voronoi Diagram

        Attributes: - Coordinates: Longitude and Latitude for each airport
                    - Altitude: Airport altitude
                    - Cities: Cities where the airports are located
                    - Names: Airport names
                    - x_coord: Points in the x-axis for the borders (map)
                    - y_coord: Points in the y-axis fot the borders (map)
                    - vor: Voronoi Diagram of the coordinates
    """

    def __init__(self, borders, airports):

        """ Constructor: Class atributes initialization

            Arguments: - borders: str. Name of the file storing
                                       the borders data (map)
                       - airports: str. Name of the file storing
                                        the airports data
        """

        airp_file = pd.read_csv(airports, sep=r'\s+',
                                names=['Latitude', 'Longitude', 'Altitude',
                                       'City', 'Departament', 'Name'])

        self.coordinates = np.array([[airp_file['Longitude'][i],
                                      airp_file['Latitude'][i]]
                                    for i in range(len(airp_file))])

        self.altitude = airp_file['Altitude']
        self.cities = airp_file['City']
        self.names = airp_file['Name']
        self.vor = Voronoi(self.coordinates)

        bor_file = pd.read_csv(borders, sep=r'\s+',
                               names=['Latitude', 'Longitude'])

        self.x_coord = np.array([bor_file['Longitude'][i]
                                for i in range(len(bor_file))])
        self.y_coord = np.array([bor_file['Latitude'][i]
                                for i in range(len(bor_file))])

    def _area(self, region):

        """ Private method that calculates the area of a given region
            of the Voronoi Diagram

            Input: - region: list that represents the region
                             for the Voronoi Subdivision
            Output: float. Area of the region; or Infinite Area if -1 in region
        """

        if -1 in region:
            return "Infinite Area"
        vertices = [self.vor.vertices[i].tolist() for i in region]
        area = 0
        for i in range(len(vertices)):
            if i == len(vertices)-1:
                x = vertices[0][1]*vertices[i][0]
                x -= vertices[0][0]*vertices[i][1]
            else:
                x = vertices[i][0]*vertices[i+1][1]
                x -= vertices[i][1]*vertices[i+1][0]
            area += x
        return abs(area)/2

    def _inside_outside(self, poly, vertex):

        """ Private method that verifies if a vertex is in a polygon

            Input: - poly: list with the vertices of the polygon
            Output True or False. vertex in or out the polygon
        """

        poly_path = mplPath.Path(np.array(poly))
        return poly_path.contains_point(vertex)

    def _sort(self, x_coords, y_coords):

        """ Private method that sort in counterclockwise order
            the given coordinates

            Input: - x_coords: array with the coordinates in x
                   - y_coords: array with the coordinates in y
            Output: x_new, y_new coordinates sorted
        """

        x_0 = np.mean(x_coords)
        y_0 = np.mean(y_coords)

        r = np.sqrt((x_coords-x_0)**2 + (y_coords-y_0)**2)

        points_angles = np.where((y_coords-y_0) > 0,
                                 np.arccos((x_coords-x_0)/r),
                                 2*np.pi-np.arccos((x_coords-x_0)/r))

        sort_ = np.argsort(points_angles)

        new_x = x_coords[sort_]
        new_y = y_coords[sort_]

        return new_x, new_y

    def plot_vor_airports(self):

        """ Method that plots the Voronoi subdivision and the borders """

        fig = voronoi_plot_2d(self.vor, show_vertices=False, line_alpha=0.8)

        plt.plot(self.x_coord, self.y_coord, 'k')

        plt.title('Voronoi Map')
        plt.xlabel('Longitude (degrees)')
        plt.ylabel('Latitude (degrees)')
        plt.show()

    def max_min_areas(self, plot=False):

        """ Method that returns the airports where is reported the max
            and min area in the subdivision for region with finite areas

            Input(optional): - plot: boolean for plotting
            Output: (str, str). The airports with min and max coverage
                                area respectively
        """

        regions = self.vor.regions
        min_index = max_index = 0
        point_reg = self.vor.point_region
        max_area = min_area = self._area(regions[point_reg[0]])
        for i in range(1, len(point_reg)):
            region = regions[point_reg[i]]
            if region != []:
                new_area = self._area(region)
            else:
                new_area = "Infinite Area"
            if new_area != "Infinite Area":
                if new_area > max_area:
                    max_area = new_area
                    max_index = i
                if new_area < min_area:
                    min_area = new_area
                    min_index = i
        min_airport = self.names[min_index]
        max_airport = self.names[max_index]

        if plot:
            fig = voronoi_plot_2d(self.vor, show_vertices=False,
                                  line_alpha=0.8)
            plt.plot(self.x_coord, self.y_coord, 'k')

            vertex_1 = self.coordinates[min_index]
            vertex_2 = self.coordinates[max_index]
            min_region = regions[point_reg[min_index]]
            max_region = regions[point_reg[max_index]]
            min_ver = [self.vor.vertices[i] for i in min_region]
            max_ver = [self.vor.vertices[i] for i in max_region]

            plt.fill(*zip(*min_ver), color='#f5cba7')
            plt.fill(*zip(*max_ver), color='#f5cba7')

            plt.plot(vertex_1[0], vertex_1[1], marker='*',
                     c='green', label='Min Area: ' + min_airport)
            plt.plot(vertex_2[0], vertex_2[1], marker='*',
                     c='yellow', label='Max Area: ' + max_airport)

            fig.legend(loc='lower right')
            plt.title('Maximum and minimun areas')
            plt.xlabel('Longitude (degrees)')
            plt.ylabel('Latitude (degrees)')
            plt.show()

        return min_airport, max_airport

    def build_airport(self, plot=False):

        """ Method that returns the center and radius of the
            largest circle centered within the convex hull and
            enclosing none of the already existing airports

            Input(optional): - plot: boolean for plotting
            Output: (list, float). list with the coordinates
                                   of center and its radius
        """

        vertices = self.vor.vertices
        point_reg = self.vor.point_region
        regions = self.vor.regions
        index = -1
        max_dis = -1
        max_vertex = []
        borders = [(self.x_coord[i], self.y_coord[i])
                   for i in range(len(self.x_coord))]

        edges = self.vor.ridge_vertices
        inf_edges = []
        for j in range(len(edges)):
            if -1 in edges[j]:
                index = self.vor.ridge_points[j]
                inf_edges.append([self.vor.points[index[0]],
                                  self.vor.points[index[1]]])

        vertices_hull = []
        for ver in inf_edges:
            coord_1 = ver[0].tolist()
            coord_2 = ver[1].tolist()
            if coord_1 not in vertices_hull:
                vertices_hull.append(coord_1)
            if coord_2 not in vertices_hull:
                vertices_hull.append(coord_2)

        x = np.array([i[0] for i in vertices_hull])
        y = np.array([i[1] for i in vertices_hull])
        x, y = self._sort(x, y)
        hull = [(x[i], y[i]) for i in range(len(x))]

        for i in range(len(vertices)):
            vertex = vertices[i].tolist()
            check_1 = self._inside_outside(hull, vertex)
            check_2 = self._inside_outside(borders, vertex)
            if check_1 and check_2:
                for j, r in enumerate(regions):
                    if i in r:
                        index = self.vor.point_region.tolist().index(j)
                        pos = self.vor.points[index]
                        dis = euclidean(vertex, pos)
                        if dis > max_dis:
                            max_dis = dis
                            max_vertex = vertex
        center = max_vertex[0], max_vertex[1]

        if plot:

            fig, ax = plt.subplots()

            ax.plot(x, y, c='red')
            ax.plot([x[len(x)-1], x[0]], [y[len(x)-1], y[0]], c='red')

            voronoi_plot_2d(self.vor, ax=ax, show_vertices=False,
                            line_alpha=0.8)

            ax.plot(self.x_coord, self.y_coord, 'k')
            ax.plot(max_vertex[0], max_vertex[1], marker='*',
                    c='green', label='Center of largest circle')

            circle = plt.Circle(center, max_dis,
                                fill=True, color='purple')
            ax.add_patch(circle)

            fig.legend(loc='lower right')
            plt.title('Build New Airport')
            plt.xlabel('Longitude (degrees)')
            plt.ylabel('Latitude (degrees)')
            plt.show()

        return center, max_dis

    def most_less_crowded(self, plot=False):

        """ Method that returns the airports with most and least neighbors
            respectively

            Input(optional): - plot: boolean for plotting
            Output: (str, str). The airports with least and
                                most neighbors respectively
        """

        total_airports = len(self.coordinates)
        edges = self.vor.ridge_points
        neighbors = total_airports*[0]
        for i in edges:
            neighbors[i[0]] += 1
            neighbors[i[1]] += 1
        min_index = neighbors.index((min(neighbors)))
        max_index = neighbors.index((max(neighbors)))
        most_airport = self.names[max_index]
        least_airport = self.names[min_index]

        if plot:
            fig = voronoi_plot_2d(self.vor, show_vertices=False,
                                  line_alpha=0.8)

            plt.plot(self.x_coord, self.y_coord, 'k')

            vertex_1 = self.coordinates[min_index]
            vertex_2 = self.coordinates[max_index]
            point_reg = self.vor.point_region
            min_region = self.vor.regions[point_reg[min_index]]
            max_region = self.vor.regions[point_reg[max_index]]
            min_ver = [self.vor.vertices[i] for i in min_region]
            max_ver = [self.vor.vertices[i] for i in max_region]

            plt.fill(*zip(*min_ver), color='#f5cba7')
            plt.fill(*zip(*max_ver), color='#f5cba7')

            plt.plot(vertex_1[0], vertex_1[1], marker='*', c='green',
                     label='Most Crowded Airport: ' + most_airport)
            plt.plot(vertex_2[0], vertex_2[1], marker='*', c='yellow',
                     label='Least Crowded Airport: ' + least_airport)

            fig.legend(loc='lower right')
            plt.title('Most and least Crowded Airports')
            plt.xlabel('Longitude (degrees)')
            plt.ylabel('Latitude (degrees)')
            plt.show()

        return least_airport, most_airport

    def merge_airport(self, plot=False):

        """ Method that returns the airports that may be
            deleted and the position of the new airport

            Input(optional): - plot: boolean for plotting
            Output: (str, str, array). The airports that may be deleted,
                                       the coordinates of the mean between them
        """

        points = self.coordinates.tolist()
        min_dis = euclidean(points[0], points[1])
        coords = points[0], points[1]
        for i in range(len(points)):
            x = points[i]
            for j in range(i+1, len(points)):
                y = points[j]
                new_dis = euclidean(x, y)
                if new_dis < min_dis:
                    min_dis = new_dis
                    coords = x, y
        coor_1 = points.index(coords[0])
        coor_2 = points.index(coords[1])
        airport_1 = self.names[coor_1]
        airport_2 = self.names[coor_2]
        pos = np.mean(np.array([coords[0], coords[1]]), axis=0)

        if plot:
            fig = voronoi_plot_2d(self.vor, show_vertices=False,
                                  line_alpha=0.8)

            plt.plot(self.x_coord, self.y_coord, 'k')

            vertex_1 = self.coordinates[coor_1]
            vertex_2 = self.coordinates[coor_2]

            plt.plot(vertex_1[0], vertex_1[1], marker='*', c='green',
                     label=airport_1 + ' out')
            plt.plot(vertex_2[0], vertex_2[1], marker='*', c='yellow',
                     label=airport_2 + ' out')
            plt.plot(pos[0], pos[1], marker='*', c='red',
                     label='New Airport')

            fig.legend(loc='lower right')
            plt.title('Merge Airport')
            plt.xlabel('Longitude (degrees)')
            plt.ylabel('Latitude (degrees)')
            plt.show()

        return airport_1, airport_2, pos


'''Use the file from gutenberg to read and
count the words and then store the answer in a new file
like this
a   12
to  123
hi  45
this 343
Make this a one or more function program
'''
from string import punctuation

def question1_solver(read_file_path,save_file_path='results.txt'):
    # read the file and store in a variable
    file = open(read_file_path, encoding='utf-8')  # read
    content = file.read()
    file.close()

    # remove every punctuations
    for punc in punctuation:
        content = content.replace(punc,'')

    # make every thing lowercase and split file in words
    words = content.casefold().split()
    print(f"total words => {len(words)}")

    # create a empty file
    with open(save_file_path,'w') as file2: # create
        # counting the words
        for word in set(words):
            count = words.count(word)          # counting words
            file2.write(f'{word}\t{count}\n')  # storing in file
    # the end

question1_solver('franki.txt')


#!flask/bin/python3

from flask import Flask, jsonify
from flask import make_response
from flask import request
from flask import abort

app = Flask(__name__)

tasks = [
    {
        'id' : 1,
        'title': u'Buy groceries',
        'desription': u'Milk,stuff',
        'done': False
    }
    ,
    {
        'id' : 2,
        'title': u'Buy groceries',
        'desription': u'Milk,stuff',
        'done': False
    }
]

@app.route('/')
def index():
    return "hello, internet"

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task':task[0]})

@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == "__main__":
    app.run(debug=True)


import bnlearn as bn
from pgmpy.factors.discrete import TabularCPD

alarm_clock = TabularCPD(variable='alarm_clock', variable_card=2, values=[[0.01], [0.99]])
traffic = TabularCPD(variable='traffic', variable_card=2, values=[[0.38], [0.62]])

oversleep = TabularCPD(variable='oversleep', variable_card=2,
                  values=[[0.12, 0.81],
                          [0.88, 0.19]],
                  evidence=['alarm_clock'], evidence_card=[2])

on_time = TabularCPD(variable='on_time', variable_card=2,
                   values=[[0.02, 0.42, 0.73, 0.95],
                           [0.98, 0.58, 0.27, 0.05]],
                   evidence=['oversleep', 'traffic'],
                   evidence_card=[2, 2])

edges = [('alarm_clock', 'oversleep'),
         ('oversleep', 'on_time'),
         ('traffic', 'on_time')]

DAG = bn.make_DAG(edges)
DAG = bn.make_DAG(DAG, CPD=[alarm_clock, traffic, on_time, oversleep])

bn.print_CPD(DAG)

bn.inference.fit(DAG, variables=['on_time'], evidence={})
bn.inference.fit(DAG, variables=['oversleep'], evidence={})