import __builtin__
import etcd
import maps
import mock
from mock import patch
import pytest

from tendrl.commons.flows.exceptions import FlowExecutionFailedError
from tendrl.commons.objects.node.flows.stop_services import \
    StopServices
import tendrl.commons.objects.node_context as node
from tendrl.commons.objects.service import Service
from tendrl.commons import TendrlNS
from tendrl.commons.utils import cmd_utils
from tendrl.commons.utils import etcd_utils
from tendrl.commons.utils import log_utils as logger

def read(*args, **kwargs):
    if args:
        if args[0] == "nodes/Test_node/Os":
            raise etcd.EtcdKeyNotFound
    else:
        return None

def service_success(param):
    return None, '', 0

def service_failed(param):
    return '', 'error', 0

def service_info(*args, **kwargs):
    return {"exists": True, "running": True, "error": []}

def service_error(*args, **kwargs):
    return {"exists": True,
            "running": False,
            "error": ["permission issue"]
            }

def mock_log(*args, **kwargs):
    pass

@patch.object(etcd, "Client")
@patch.object(etcd.Client, "read")
@patch.object(node.NodeContext, '_get_node_id')
@patch.object(etcd_utils, 'read')
def init(patch_etcd_utils_read,
         patch_get_node_id,
         patch_read,
         patch_client):
    patch_get_node_id.return_value = 1
    patch_read.return_value = etcd.Client()
    patch_client.return_value = etcd.Client()
    setattr(__builtin__, "NS", maps.NamedDict())
    setattr(NS, "_int", maps.NamedDict())
    NS._int.etcd_kwargs = {
        'port': 1,
        'host': 2,
        'allow_reconnect': True}
    NS._int.client = etcd.Client(**NS._int.etcd_kwargs)
    NS._int.wclient = etcd.Client(**NS._int.etcd_kwargs)
    NS["config"] = maps.NamedDict()
    NS.config["data"] = maps.NamedDict()
    NS.config.data['tags'] = "test"
    NS.config.data['logging_socket_path'] = "test"
    NS.publisher_id = "node_context"
    NS.config.data['etcd_port'] = 8085
    NS.config.data['etcd_connection'] = "Test Connection"
    patch_etcd_utils_read.return_value = maps.NamedDict(
        value='{"status": "UP",'
              '"pkey": "tendrl-node-test",'
              '"node_id": "test_node_id",'
              '"ipv4_addr": "test_ip",'
              '"tags": "[\\"my_tag\\"]",'
              '"sync_status": "done",'
              '"locked_by": "fd",'
              '"fqdn": "tendrl-node-test",'
              '"last_sync": "date"}')
    tendrlNS = TendrlNS()
    return tendrlNS

def test_constructor():
    init()
    StopServices()

@mock.patch(
    'tendrl.commons.event.Event.__init__',
    mock.Mock(return_value=None)
)
@mock.patch(
    'tendrl.commons.message.Message.__init__',
    mock.Mock(return_value=None)
)
def test_run():
    init()
    obj = StopServices()
    assert obj.parameters is not None
    obj.parameters = maps.NamedDict()
    obj.parameters['job_id'] = "sample_uuid"
    obj.parameters['flow_id'] = "sample_uuid_1"
    obj.parameters["Services[]"] = ["TestService"]
    with patch.object(logger, 'log', mock_log):
        with patch.object(cmd_utils.Command, 'run', service_success):
            with patch.object(Service, 'get_service_info', service_info):
                ret_val = obj.run()
                assert ret_val is True
    with patch.object(logger, 'log', mock_log):
        with patch.object(cmd_utils.Command, 'run', service_failed):
            with patch.object(Service, 'get_service_info', service_error):
                with pytest.raises(FlowExecutionFailedError):
                    obj.run()


"""Task 6: Extend the Region"""
import rasterio
from rasterio.transform import from_origin
from rasterio.merge import merge
from rasterio import plot
import numpy as np

# function to create new raster
# adjusted/based on: Bryce Frank 18-04-18 https://gis.stackexchange.com/questions/279953/numpy-array-to-gtiff-using-rasterio-without-source-raster
def new_raster(min_x, max_y, max_easting, min_northing, out_raster):
    pixel_size = 5
    dif_x_cell = int((max_easting - min_x)/5)
    dif_y_cell = int((max_y - min_northing)/5)
    arr = np.zeros((dif_y_cell, dif_x_cell))  # raster value set to 0 because raster extension should be at sea level
    transform = from_origin(min_x, max_y, pixel_size, pixel_size)
    extension = rasterio.open(out_raster, 'w', driver='GTiff',
                                height=arr.shape[0], width=arr.shape[1],
                                count=1, dtype=str(arr.dtype),
                                crs='+init=epsg:27700',
                                transform=transform)
    extension.write(arr, 1)
    extension.close()

# find extend of new raster
min_easting, min_northing, max_easting, max_northing = 430000, 80000, 465000, 95000 # storing box extent
min_from_edge = 5000
elev_min_easting, elev_min_northing, elev_max_easting, elev_max_northing = min_easting - min_from_edge , min_northing - min_from_edge, max_easting + min_from_edge, max_northing + min_from_edge # coordinates of elevation raster
ext_min_easting, ext_min_northing, ext_max_easting, ext_max_northing = elev_min_easting - min_from_edge, elev_min_northing- min_from_edge, elev_max_easting + min_from_edge, elev_max_northing + min_from_edge # max outer coordinates of extended raster

# create new raster
new_raster(ext_min_easting, elev_min_northing, ext_max_easting, ext_min_northing,'extension_a.tif') # raster a: extent below elevation raster
new_raster(ext_min_easting, elev_max_northing, elev_min_easting, elev_min_northing,'extension_b.tif') # raster b: extent left to elevation raster
new_raster(ext_min_easting, ext_max_northing, ext_max_easting, elev_max_northing, 'extension_c.tif') # raster c: extent above elevation raster
new_raster(elev_max_easting, elev_max_northing, ext_max_easting, elev_min_northing, 'extension_d.tif') # raster d: extent right to elevation raster

# merge new rasters
# source https://rasterio.readthedocs.io/en/latest/api/rasterio.merge.html
extension_a = rasterio.open('extension_a.tif')
extension_b = rasterio.open('extension_b.tif')
extension_c = rasterio.open('extension_c.tif')
extension_d = rasterio.open('extension_d.tif')
elevation = rasterio.open('sz.asc')

extension_raster = [extension_a, extension_b, extension_c, extension_d, elevation] # list of extension rasters

extension_merged, out_trans = merge(extension_raster) # merge extension rasters

rasterio.open('extension_merged.tif', 'w', driver='GTiff',
                                height=extension_merged.shape[0], width=extension_merged.shape[1],
                                count=1, dtype=str(extension_merged.dtype),
                                crs='+init=epsg:27700',
                                transform=out_trans) # write merged extension raster
extension = rasterio.open('extension_merged.tif')
rasterio.plot.show(extension)

# test if user is on the isle of wight
# adjusted from https://automating-gis-processes.github.io/CSC18/lessons/L4/point-in-polygon.html

#island = gpd.GeoDataFrame.from_file('isle_of_wight.shp')

#if (island.contains(user_location)).bool():
#    location = 'on land'
#else:
#    location = 'in the sea'
#    print ('you are not on the island')
#    exit()  # stop application if user input not on land


from math import sqrt, log10

class WelfordRunningVariance(object):
    """
    Python implentation of Welford's running variance algorithm
    http://www.johndcook.com/standard_deviation.html
    """
    def __init__(self):
        self._count = 0
        self._mean = None
        self._last_mean = None
        self._max = None
        self._min = None
        self._sum = None

        self._s = None
        self._last_s = None

    def send(self, value):
        self._count += 1

        if self._count == 1:
            self._mean = value
            self._max = value
            self._min = value
            self._sum = value
            self._last_mean = value
            self._last_s = 0.0

        else:
            self._mean = self._last_mean + (value - self._last_mean)/self._count
            self._s = self._last_s + (value - self._last_mean) * (value - self._mean)

            self._sum += value
            # check & update max/min values if necessary
            if value > self._max:
                self._max = value
            if value < self._min:
                self._min = value

            # prepare for next iteration
            self._last_mean = self._mean
            self._last_s = self._s

    def next(self):
        """
        Mimmicing generator function
        """
        return self._mean

    def count(self):
        return self._count

    def mean(self):
        return self._mean

    def max(self):
        return self._max

    def min(self):
        return self._min

    def sum(self):
        return self._sum

    def var(self):
        result = 0
        if self._count >= 2:
            result = self._s/(self._count - 1)
        return result

    def stddev(self):
        return sqrt(self.var())

class WelfordRunningVariancedB(object):
    """
    Python implentation of Welford's running variance algorithm (for dB calc)
    http://www.johndcook.com/standard_deviation.html
    """
    def __init__(self):
        self._count = 0
        self._mean = None
        self._last_mean = None

        self._s = None
        self._last_s = None

    def send(self, v):
        value =  10**(v/10.0)
        self._count += 1

        if self._count == 1:
            self._mean = value
            self._last_mean = value
            self._last_s = 0.0
        else:
            self._mean = self._last_mean + (value - self._last_mean)/self._count
            self._s = self._last_s + (value - self._last_mean) * (value - self._mean)

            # prepare for next iteration
            self._last_mean = self._mean
            self._last_s = self._s

    def mean_db(self, as_db=False):
        result = self._mean
        if as_db:
            result =  10 * log10(result)
        return result

    def count(self):
        return self._count

    def var_db(self, as_db=False):
        result = 0
        if self._count >= 2:
            result = self._s/(self._count - 1)

        if as_db:
            result =  10 * log10(result)

        return result

    def next(self):
        """
        Mimmicing generator function
        """
        return self._mean

    def stddev_db(self):
        lin_stdev = sqrt(self.var_db())
        db_stdev =   10 * log10(lin_stdev)
        return db_stdev #WARNING -- this value doesn't seem to make sense


import argparse
import os
import mrcfile as mf
import glob
import numpy as np
from scipy.ndimage.interpolation import rotate
from math import radians

# Relion
def resize(orig_structure_path, dest_structure_path, new_box_size):
    if not os.path.exists(orig_structure_path):
        print('Cannot open %s!' % orig_structure_path)
        return
    if os.path.exists(dest_structure_path):
        return

    with mf.open(orig_structure_path) as f:
        xsize, ysize, zsize = int(f.header['nx']), int(f.header['ny']), int(f.header['nz'])

        if xsize != ysize or xsize != zsize or ysize != zsize:
            return

        xangpix = float(f.voxel_size.x)
        rescale_xangpix = xangpix * xsize / new_box_size
        cmd = 'relion_image_handler --i %s --o %s --new_box %d --angpix %.3f --rescale_angpix %.3f' % (orig_structure_path, dest_structure_path, new_box_size, xangpix, rescale_xangpix)
        os.system(cmd)

def create_projections(orig_structure_path, dest_projs_path, num):
    if not os.path.exists(orig_structure_path):
        print('Cannot open %s!' % orig_structure_path)
        return
    if os.path.exists(dest_projs_path):
        return

    cmd = 'relion_project --i %s --o %s --nr_uniform %d' % (orig_structure_path, dest_projs_path, num)
    os.system(cmd)

# EMAN2
def normalize2d(orig_projs_path, dest_projs_path):
    if not os.path.exists(orig_projs_path):
        print('Cannot open %s!' % orig_projs_path)
        return
    if os.path.exists(dest_projs_path):
        return

    cmd = 'e2proc2d.py %s %s --process normalize.edgemean' % (orig_projs_path, dest_projs_path)
    os.system(cmd)

def normalize3d(orig_stru_path, dest_stru_path):
    if not os.path.exists(orig_stru_path):
        print('Cannot open %s!' %orig_stru_path)
        return
    if os.path.exists(dest_stru_path):
        return

    cmd = 'e2proc3d.py %s %s --process normalize.edgemean' % (orig_stru_path, dest_stru_path)
    os.system(cmd)

# Read/Write Mrc
def read_mrc(path):
    with mf.open(path) as f:
        return f.data

def write_mrc(path, data, overwrite = True):
    with mf.new(path, overwrite = overwrite) as f:
        f.set_data(data)

# Transformation
def random_angles(min_angle = 0, max_angle = 360):
    return [np.random.randint(min_angle, max_angle) for _ in range(3)]

def rotate_3d(data, x, y, z):
    dz = rotate(data, z, mode = 'nearest', axes = (0, 1), reshape = False)
    dy = rotate(dz, y, mode = 'nearest', axes = (0, 2), reshape = False)
    dx = rotate(dy, x, mode = 'nearest', axes = (1, 2), reshape = False)
    return dx

# Directory ops
def find_and_unzip_mapgz(mapgz_dir):
    cmd = 'gzip -d %s' % mapgz_dir
    os.system(cmd)

def convert_map_to_mrc(map_dir, mrc_dir):
    if not os.path.exists(map_dir):
        print('Cannot open %s!' % map_dir)
    if os.path.exists(mrc_dir):
        return

    with mf.new(mrc_dir) as mrc_file:
        with mf.open(map_dir) as map_file:
            mrc_file.set_data(map_file.data)
            mrc_file.set_extended_header(map_file.extended_header)
            mrc_file.voxel_size = map_file.voxel_size
            mrc_file.header['nxstart'] = map_file.header['nxstart']
            mrc_file.header['nystart'] = map_file.header['nystart']
            mrc_file.header['nzstart'] = map_file.header['nzstart']

def search_by_re(root_dir, re):
    return glob.glob(root_dir + re)

def split_file_path(path):
    file_dir, file_name = os.path.split(path)
    file_prefix, file_postfix = os.path.splitext(file_name)
    return file_dir, file_prefix, file_postfix

if __name__ == '__main__':
    # Steps for preprocessing:
    # 1. Unzip map.gz files
    # 2. Convert .map to .mrc
    # 3. Resize 3d structure files to 64x64x64
    # 4. Normalize 3d structure files
    # 5. (Optional) Rotate 3d structure files
    # 6. Create projections

    root_dir = '../../dataset/testSet/'
    norm_mrc_re = 'EMD-????/*_64_norm.mrc'
    norm_mrcs = sorted(search_by_re(root_dir, norm_mrc_re))

    for mp in norm_mrcs:
        create_projections(mp, mp[:-4] + '_24projs', 24)

    # Rotate
    for mp in norm_mrcs:
       fdir, fprefix, _ = split_file_path(mp)
       data = read_mrc(mp)
       for idx in range(2):
           rot_x, rot_y, rot_z = random_angles(30, 150)
           if np.random.rand() < 0.5:
               rot_x = -rot_x
           if np.random.rand() < 0.5:
               rot_y = -rot_y
           if np.random.rand() < 0.5:
               rot_z = -rot_z
           rot_mrc = rotate_3d(data, rot_x, rot_y, rot_z)
           model_type = fdir.split('/')[-1] + '_%d' % idx
           new_dir = root_dir + model_type + '/'

           if not os.path.exists(new_dir):
               os.makedirs(new_dir)
           mrc_name = model_type + '_64_norm.mrc'
           proj_name = model_type + '_64_norm_projs'
           write_mrc(new_dir + mrc_name, rot_mrc)
           create_projections(new_dir + mrc_name, new_dir + proj_name, 24)


from unittest import TestCase
from podm import JsonObject, Property

class TestObject(JsonObject):
    field1 = Property(default=1)
    field2 = Property(default=True)
    field3 = Property(default=False)
    field4 = Property(default=dict)
    field5 = Property(default=lambda: [1, 2, 3])

class TestDefaults(TestCase):
    def test_default_int(self):
        obj = TestObject()
        self.assertEqual(1, obj.field1)

    def test_default_bool_true(self):
        obj = TestObject()
        self.assertTrue(obj.field2)

    def test_default_bool_false(self):
        obj = TestObject()
        self.assertFalse(obj.field3)

    def test_default_dict(self):
        obj = TestObject()
        self.assertEqual({}, obj.field4)

    def test_default_list_factory(self):
        obj = TestObject()
        self.assertEqual([1, 2, 3], obj.field5)

    def test_constructors(self):
        obj = TestObject(field1=2, field2=False, field3=True, field4={"a": 1}, field5=[4, 5, 6])
        self.assertEqual(2, obj.field1)
        self.assertFalse(obj.field2)
        self.assertTrue(obj.field3)
        self.assertEqual({"a": 1}, obj.field4)
        self.assertEqual([4, 5, 6], obj.field5)


from flask import Flask, render_template
import sqlite3

app = Flask(__name__)

def get_data():
    conn = sqlite3.connect("air_quality_data.db")
    cur = conn.cursor()
    cur.execute("SELECT * FROM measurements")
    data = cur.fetchall()
    conn.close()
    return data

@app.route("/")
def index():
    data = get_data()
    return render_template("index.html", data=data)

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


# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/product-of-array-except-self/

Two dps, pre-product and after-product
"""

class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        dp1 = [1] * n
        dp2 = [1] * n
        for i in range(1, n):
            dp1[i] = dp1[i - 1] * nums[i - 1]
        for i in range(n - 2, -1, -1):
            dp2[i] = dp2[i + 1] * nums[i + 1]

        res = []
        for i in range(n):
            res.append(dp1[i] * dp2[i])
        return res


# $language = "Python3"
# $interface = "1.0"

import os
import sys
from ciscoconfparse import CiscoConfParse

# Avoids errors in IDE's that can't detect the crt variable:
global crt

# Adds script directory to PYTHONPATH,
# so we can import local modules when running common_tasks from SecureCRT
script_dir = None
if 'crt' in globals():
    script_dir, script_name = os.path.split(crt.ScriptFullName)
if script_dir not in sys.path:
    sys.path.append(script_dir)
else:
    script_dir, script_name = os.path.split(os.path.realpath(__file__))

# Local import
import runners
from crt_automation.sessions import CrtSession

# Main function and script logic here:
def main():
    scrt = CrtSession(crt)
    # Discover OS:
    scrt.active_session.start_cisco_session()
    # Validate script is compatible with OS:
    scrt.active_session.validate_os(["IOS", "XE", "NXOS", "ASA", "WAAS"])
    # Make runner easier to type:
    nos = scrt.active_session.runner

    nos.response_timeout = 5  # 5 seconds

    # Get a reference to the tab that was active when this script was launched.
    initial_tab = crt.GetScriptTab()

    # Activate each tab in order from left to right, and issue the command in
    # each "connected" tab...
    skipped_tabs = ""
    for i in range(1, crt.GetTabCount() + 1):
        tab = crt.GetTab(i)
        tab.Activate()
        # Skip tabs that aren't connected
        if tab.Session.Connected == True:
            nos.current_tab = tab
            nos.set_prompt()
        else:
            if skipped_tabs == "":
                skipped_tabs = str(i)
            else:
                skipped_tabs = skipped_tabs + "," + str(i)

        # Now, activate the original tab on which the script was started
        initial_tab.Activate()

        # Determine if there were any skipped tabs, and prepare a message for
        # displaying at the end.
        if skipped_tabs != "":
            skipped_tabs = "\n\n\The following tabs did not receive the command because\n\
    they were not connected at the time:\n\t" + skipped_tabs

    return

main()


"""
    Create character feature dataset for STM
"""

import os
import json
import pandas as pd
from collections import Counter
from tqdm import tqdm
import re
from character_annotator import CharacterAnnotator

import pdb

class FandomDatasetCreator():

    def __init__(self, fandom, json_features_dirpath, outpath):
        self.fandom = fandom
        self.json_features_dirpath = json_features_dirpath
        self.outpath = outpath
        self.character_annotator = CharacterAnnotator(fandom)

    def annotate_relationship_types(self):
        """ Annotate relationship types in self.data """
        # Load fic metadata
        metadata_fpath = f'/data/fanfiction_ao3/{self.fandom}/complete_en_1k-50k/metadata.csv'
        metadata = pd.read_csv(metadata_fpath)

        merged = pd.merge(self.data, metadata, on=['fic_id'])
        char_in_rel = []
        char_in_rel_type = []
        for char, rel in zip(merged['character_original'], merged['relationship']):
            x, y = self.character_annotator.char_in_relationship(char, rel)
            char_in_rel.append(x)
            char_in_rel_type.append(y)
        #merged['character_in_relationship'], merged['character_in_relationship_type'] = list(zip(*[self.character_annotator.char_in_relationship(tup[0], tup[1]) for tup in zip(merged['character_original'], merged['relationship'])]))
        merged['character_in_relationship'] = char_in_rel
        merged['character_in_relationship_type'] = char_in_rel_type
        #print(merged['character_in_relationship'].sum())
        merged['character_in_relationship_type'].value_counts()
        #merged.drop(columns=['char_in_relationship'], inplace=True)
        self.data = merged

    def assemble_dataset(self):
        # Aggregate character features from JSONs
        header = ['fic_id', 'character_original', 'character_canonical', 'character_gender', 'character_features']
        outlines = []
        self.character_annotator.character_name_parts() # to exclude in features
        print("Loading character genders...")
        character_gender = self.character_annotator.character_gendermap()
        print("Assembling character features...")
        #for fname in tqdm(os.listdir(self.json_features_dirpath), ncols=50):
        #    fic_id = fname.split('.')[0]
        #    with open(os.path.join(self.json_features_dirpath, fname)) as f:
        #        char_features = json.load(f)
        #    for char in char_features:
        #        canonical_char = self.character_annotator.canonicalize(char)
        #        if not canonical_char in character_gender: continue
        #        gender = character_gender[canonical_char]
        #        feats = ' '.join([feat for feat in char_features[char] if not feat in self.character_annotator.character_name_parts])
        #        if len(feats) < 1: continue
        #        outlines.append([fic_id, char, canonical_char, gender, feats])
        #self.data = pd.DataFrame(outlines, columns=header)
        #self.data.to_csv(self.outpath, index=False)
        self.data = pd.read_csv(self.outpath)

        # Annotate fic relationship type
        print("Annotating relationship types...")
        self.annotate_relationship_types()

        # Save out
        self.data.to_csv(self.outpath, index=False)
        print(f"Saved assembled character feature data from {len(self.data['fic_id'].unique())} fics")

def main():
    fandoms = [
        'harrypotter',
        'supernatural'
    ]
    data = {} # character features, to be merged

    for fandom in fandoms:
        print(f"Building or loading dataset from {fandom}...")
        json_features_dirpath = f'/data/fanfiction_ao3/{fandom}/complete_en_1k-50k/output_old/char_features'
        output_path = f'/data/fanfiction_ao3/{fandom}/complete_en_1k-50k/output/character_features.csv'
        if os.path.exists(output_path):
            print("\tAlready exists")
            data[fandom] = pd.read_csv(output_path)
        else:
            # Load character features JSON files, merge with gender, output CSV
            creator = FandomDatasetCreator(fandom_name, json_features_dirpath, output_path)
            creator.assemble_dataset()
            data[fandom] = creator.data

    print("Merging datasets...")
    merged = pd.concat([data[fandom] for fandom in fandoms], keys=fandoms, names=['fandom_dataset', 'old_index'])
    merged.reset_index(inplace=True, level='fandom_dataset')
    merged_outpath = f'/data/fanfiction_ao3/character_features_{len(fandoms)}fandoms.csv'
    merged.to_csv(merged_outpath, index=False)
    print(f"\tSaved to {merged_outpath}")

if __name__ == '__main__':
    main()


#!/usr/bin/python3
import re
"""
Parse a log file in a given format.
Part 1: Based on date and time get a count of total messages
"""
def log_parse1(filename):
    dates_dic = {}
    with open(filename, 'r') as content:
        lines = content.readlines()
        for line in lines:
            tokens = re.split(" ", line, maxsplit=3)
            key = tokens[0] + " " + tokens[1] + " " + tokens[2][:5]
            if key in dates_dic:
                dates_dic[key] += 1
            else:
                dates_dic[key] = 1

    # returning for using in the next function
    return dates_dic

"""
Part 2: The idea is to make a dictionary of processes, where name of the process
will be key and its value will be a dictionary of dates where each unique date
will be a key and its value will be the count i.e. the number of times each date
is repeating.
"""
def log_parse2(filename):
    process_dic = {}
    with open(filename, 'r') as content:
        lines = content.readlines()
        for line in lines:
            tokens = re.split(" ", line, maxsplit=4)
            # from tokens take out process
            key = tokens[4].split()[0]
            date_time = tokens[0] + " " + tokens[1] + " " + tokens[2][:5]
            if key in process_dic:
                # get value of the key
                value = process_dic[key]
                # check if date_time is added or its a new date_time
                if date_time in value:
                    value[date_time] += 1
                else:
                    value[date_time] = 1
            else:
                # initialize a dictionary with new date_ti,e entry
                process_dic[key] = {date_time:1}

    """
    for the first printing part, use the first dictionary with dates as keys
    and values as count.
    for second part, iterate on the process_dic and get each each process count
    based on dates
    """
    dates_dic = log_parse1(filename)

    # prints the first title line
    msg = "timestamp,totalmessages,"
    for key in process_dic.keys():
        msg += key + ","
    print(msg[:-1])

    dates_dic = sorted(dates_dic.items(), key=lambda x:x[0])
    for date in dates_dic:
        msg = date[0] + "," + str(date[1]) + ","
        for key,val in process_dic.items():
            # get dictionary of date_time and find the date and its count
            if date[0] in process_dic[key]:
                msg += str(process_dic[key][date[0]]) + ","
            else:
                # if no date in the dictionary, put 0
                msg += "0,"
        print(msg[:-1])

if __name__ == "__main__":
    log_parse2('log')

"""
output:
timestamp,totalmessages,CRON,kernel
Jun 2 10:01,9,3,6
Jun 2 10:02,3,3,0
Jun 2 10:03,3,3,0
"""


# Descriptors in Python are objects that define how attribute access works for an instance of a class. Decorators, on the other hand, are functions that take another function as input and extend or modify its behavior. In Python, it is possible to use descriptors as decorators to modify the behavior of a class attribute.

# To use a descriptor as a decorator, we can define the descriptor object, and then apply it to a class attribute using the @ syntax. For example, let's say we have a descriptor called UpperCase, which ensures that a string attribute is always in upper case. Here's how we can use it as a decorator:

class PositiveNumber:
    def __get__(self, instance, owner):
        return instance._value

    def __set__(self, instance, value):
        if value < 0:
            raise ValueError("Value must be positive")
        instance._value = value

class MyClass:
    def __init__(self, value):
        self._value  = value

    my_number = PositiveNumber()

my_instance = MyClass(5)
print(my_instance.my_number)
try:
    my_instance.my_number = 5 # should raise a ValueError
except ValueError as e:
    print(e)


import os
import torch
from torch.utils.data import Dataset
import pickle
import json
import numpy as np

class LakhMidiDataset(Dataset):

    def __init__(self, transform=None, std_dev_masks=None, dmin=-14., dmax=14.):
        self.subdirectories = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
        self.metadata_folder = "db_metadata"
        self.database_folder = "lakh"
        self.current_dir = os.getcwd()
        self.encoded_dir = "/storage/local/ssd/zigakleine-workspace"
        # self.encoded_dir = os.getcwd()
        self.all_lakh_metadata = []
        self.transform = transform

        self.dmin = dmin
        self.dmax = dmax

        for subdir_name in self.subdirectories:
            current_metadata_filename = "lakh_2908_" + subdir_name + ".pkl"
            current_lakh_metadata_abs_path = os.path.join(self.current_dir, self.metadata_folder, self.database_folder,
                                                          current_metadata_filename)

            metadata = pickle.load(open(current_lakh_metadata_abs_path, "rb"))
            for song in metadata:
                if metadata[song]["encodable"]:
                    for i in range(metadata[song]["num_sequences"]):
                        sequence = {"url": metadata[song]["encoded_song_path"], "index": i}
                        self.all_lakh_metadata.append(sequence)

    def __getitem__(self, index):
        enc_seq_rel_path = self.all_lakh_metadata[index]["url"]
        enc_seq_abs_path = os.path.join(self.encoded_dir, enc_seq_rel_path)

        enc_seq = pickle.load(open(enc_seq_abs_path, "rb"))
        enc_seq = enc_seq[self.all_lakh_metadata[index]["index"]]

        if self.transform:
            enc_seq = self.transform(enc_seq, -14., 14.)

        enc_seq_tracks = np.split(enc_seq, 4, axis=0)
        enc_seq_hstacked = np.hstack(enc_seq_tracks)

        return enc_seq_hstacked, -1

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


class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        m = len(grid[0])
        dp = []
        inf = 1 << 30
        for _ in range(2):
            dp.append([inf] * m)

        now = 0
        dp[now][0] = 0

        for i in range(n):
            for j in range(m):
                prev = min(dp[now][j], dp[1 - now][j - 1] if j > 0 else inf)
                dp[1 - now][j] = (prev + grid[i][j]) if prev != inf else inf
            now = 1 - now

        return dp[now][-1]

if __name__ == '__main__':
    s = Solution()
    print(s.minPathSum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))


import sys
from skimage.transform.radon_transform import convert_to_float
sys.path.append('/content/drive/MyDrive/FSBD')
from utils.config import conf
sys.path.append('/content/drive/MyDrive/FSBD/data')

import util
from cutout import Cutout
from tr_dataset import TrBboxDataset

import torch as t
from skimage import transform as sktsf
from torchvision import transforms as tvtsf
from torch.utils.data import DataLoader
import torch
import torchvision.transforms as T
from random import randint
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image,ImageDraw
import cv2

def inverse_normalize(img):
  if conf.caffe_pretrain:
      img = img + (np.array([122.7717, 115.9465, 102.9801]).reshape(3, 1, 1))
      return img[::-1, :, :]
  # approximate un-normalize for visualize
  return (img * 0.225 + 0.45).clip(min=0, max=1) * 255

def pytorch_normalze(img):

  normalize = tvtsf.Normalize(mean=[0.485, 0.456, 0.406],
                              std=[0.229, 0.224, 0.225])
  img = normalize(t.from_numpy(img))
  return img.numpy()

def caffe_normalize(img):

  img = img[[2, 1, 0], :, :]  # RGB-BGR
  img = img * 255
  mean = np.array([122.7717, 115.9465, 102.9801]).reshape(3, 1, 1)
  img = (img - mean).astype(np.float32, copy=True)
  return img

def preprocess(img, min_size=600, max_size=1000):

  C, H, W = img.shape
  scale1 = min_size / min(H, W)
  scale2 = max_size / max(H, W)
  scale = min(scale1, scale2)
  img = img / 255.
  img = sktsf.resize(img, (C, H * scale, W * scale), mode='reflect',anti_aliasing=False)
  # both the longer and shorter should be less than
  # max_size and min_size
  if conf.caffe_pretrain:
      normalize = caffe_normalize
  else:
      normalize = pytorch_normalze
  return normalize(img)

class Transform(object):

  def __init__(self, min_size=600, max_size=1000):
    self.min_size = min_size
    self.max_size = max_size

  def __call__(self, in_data):
    img, bbox, label = in_data
    _, H, W = img.shape
    img = preprocess(img, self.min_size, self.max_size)
    _, o_H, o_W = img.shape
    scale = o_H / H
    bbox = util.resize_bbox(bbox, (H, W), (o_H, o_W))

    # horizontally flip
    img, params = util.random_flip(
        img, x_random=True, return_param=True)
    bbox = util.flip_bbox(
        bbox, (o_H, o_W), x_flip=params['x_flip'])

    return img, bbox, label, scale

class Dataset:

  def __init__(self, split = 'beta'):
    self.db = TrBboxDataset( split = split)
    self.tsf = Transform(conf.min_size, conf.max_size)

  def __getitem__(self, idx):
    ori_img, bbox, label, fname = self.db.__getitem__(idx)

    img, bbox, label, scale = self.tsf((ori_img, bbox, label))

    return img.copy(), bbox.copy(), label.copy(), scale, fname

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

class TestDataset:
  def __init__(self,split = 'beta'):
      self.db = TrBboxDataset(split = split)

  def __getitem__(self, idx):
      ori_img, bbox, label, fname = self.db.__getitem__(idx)
      img = preprocess(ori_img)
      return img, ori_img.shape[1:], bbox, label, fname

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

class CDDataset:

  def __init__(self, split = 'beta', transforms = False):
    self.db = TrBboxDataset(split = split)
    self.tsf = Transform(conf.min_size, conf.max_size)
    self.transforms = transforms

  def __getitem__(self, idx):
    ori_img, bbox, label, fname = self.db.__getitem__(idx)

    img, bbox, label, scale = self.tsf((ori_img, bbox, label))

    if self.transforms:

      if randint(0, 1000) % 2 == 1 or True :

        img = img.transpose((1,2,0))
        objtotensor = T.ToTensor()
        objgaus = T.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5))
        objjit = T.ColorJitter(brightness=.5, hue=.3)
        objco = Cutout(1,8)
        img = objtotensor(img.copy())
        img = objgaus(img)
        img = objjit(img)

        img = objco(img)

        img = img.numpy()

    return img.copy(), bbox.copy(), label.copy(), scale, fname

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

class FSBDDataset2x:

  def __init__(self, split = 'beta'):
    self.db = TrBboxDataset( split = split)
    self.tsf = Transform(conf.min_size, conf.max_size)

  def __getitem__(self, idx):
    real_idx = idx//2
    ori_img, bbox, label, fname = self.db.__getitem__(real_idx)

    img, bbox, label, scale = self.tsf((ori_img, bbox, label))

    img = img.transpose((1,2,0))
    objtotensor = T.ToTensor()
    objgaus = T.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5))
    objjit = T.ColorJitter(brightness=.5, hue=.3)
    objco = Cutout(1,8)
    img = objtotensor(img.copy())

    if idx % 2 != 0 :
      img = objgaus(img)
      img = objjit(img)
      img = objco(img)

    img = img.numpy()

    return img.copy(), bbox.copy(), label.copy(), scale, fname

  def __len__(self):
    return (len(self.db)*2)

class FSBDDataset4x:

  def __init__(self, split = 'beta'):
    self.db = TrBboxDataset( split = split)
    self.tsf = Transform(conf.min_size, conf.max_size)

  def __getitem__(self, idx):
    real_idx = idx//4
    ori_img, bbox, label, fname = self.db.__getitem__(real_idx)

    img, bbox, label, scale = self.tsf((ori_img, bbox, label))

    img = img.transpose((1,2,0))
    objtotensor = T.ToTensor()
    objgaus = T.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5))
    objjit = T.ColorJitter(brightness=.5, hue=.3)
    objco = Cutout(1,8)
    img = objtotensor(img.copy())

    if idx % 4 != 0 :
      img = objgaus(img)
      img = objjit(img)
      img = objco(img)

    img = img.numpy()

    return img.copy(), bbox.copy(), label.copy(), scale, fname

  def __len__(self):
    return (len(self.db)*4)

if __name__ == '__main__':

  print("Inside dataset")

  conf.data_dir = conf.ten_shot_tn
  conf.image_path = conf.ten_shot_image
  conf.annot_path = conf.ten_shot_annot

  db = FSBDDataset2x(split='beta')
  print(db.__len__())

  for ii in range(db.__len__()):
    db.__getitem__(ii)

  img,bbox,label,scale,fname = db.__getitem__(0)
  print("Displaying img shape : ",img.shape)

  img = img.transpose((1,2,0))

  fig, ax = plt.subplots()

  for bb in bbox:
    h = bb[2]-bb[0]
    w = bb[3]-bb[1]
    rect = patches.Rectangle((bb[1], bb[0]), w, h, linewidth=1, edgecolor='r', facecolor='none')
    ax.add_patch(rect)

  plt.imshow(img)
  plt.savefig('abc.png')


import requests
import re
from grepgithub import Hits, fetch_grep_app
import time
import random
from crawlab import save_item
from datetime import datetime

SOURCEGRAPH = "Sourcegraph"
GREPAPP = "Grep.app"

def extract_onion_addresses(text):
    onion_address_pattern = re.compile(r'[a-z2-7]{55}d\.onion')
    matches = re.findall(onion_address_pattern, text)
    return set(matches)

def search_sourcegraph(domain_name):
    headers =   {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'}
    url = f"https://sourcegraph.com/search/stream?q=context%3Aglobal%20{domain_name}%20count%3A2000%20fork%3Ayes%20&v=V3&t=standard&sm=0&dl=0&dk=html&dc=1&display=1500&cm=t"
    response = requests.get(url, headers=headers)
    addresses = extract_onion_addresses(response.text)
    onions = {}
    for address in addresses:
        onions[address] = "Sourcegraph"
    return onions

def search_grepapp(domain_name):
    next_page, hits, count = fetch_grep_app(page=1, query="d.onion")

    while next_page and next_page < 101:    # Does not paginate after 100
        time.sleep(random.uniform(1, 2))
        next_page, page_hits, _ = fetch_grep_app(page=next_page, query="d.onion")
        hits.merge(page_hits)
    print()

    onion_addresses = {}
    for repo, path_data in hits.hits.items():
        for path, lines in path_data.items():
            for line_num, line in lines.items():
                for address in extract_onion_addresses(line):
                    if address not in onion_addresses.keys():
                        onion_addresses[address] = set()
                    onion_addresses[address].add(repo)

    onions = {}
    for onion, repos in onion_addresses.items():
        repos = list(repos)
        repos_string = repos[0]
        if len(repos) > 1:
            for repo in repos[1:]:
                repos_string =  repos_string + ', ' + repo
        repos_string = 'Grep.app (' + repos_string + ')'
        onions[onion] = repos_string

    return onions

for source in [GREPAPP, SOURCEGRAPH]:

    print(f"Discovering onions in {source} ...\n")

    if source == SOURCEGRAPH:
        addresses = search_sourcegraph("d.onion")
    elif source == GREPAPP:
        addresses = search_grepapp("d.onion")

    for onion, advertiser in addresses.items():
        print(onion, advertiser)
        today = datetime.today().timestamp()
        save_item({
            'advertiser': advertiser,
            'onion': onion,
            'timestamp': today
        })

    print()
    print(f"Discovered [{len(addresses)}] in {source}!!!\n")

    print()
    print("#####################################################")
    print()


import sys
import os
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtGui import QDesktopServices
from typing import List, cast

from QD.Event import CallFunctionEvent
from QD.FlameProfiler import pyqtSlot
from QD.Math.Vector import Vector
from QD.Scene.Selection import Selection
from QD.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
from QD.Operations.GroupedOperation import GroupedOperation
from QD.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
from QD.Operations.TranslateOperation import TranslateOperation
from QD.Resources import Resources

import qidi.QIDIApplication
from qidi.Operations.SetParentOperation import SetParentOperation
from qidi.MultiplyObjectsJob import MultiplyObjectsJob
from qidi.Settings.SetObjectExtruderOperation import SetObjectExtruderOperation
from qidi.Settings.ExtruderManager import ExtruderManager

from qidi.Operations.SetBuildPlateNumberOperation import SetBuildPlateNumberOperation

from QD.Logger import Logger
from QD.Scene.SceneNode import SceneNode

class QIDIActions(QObject):
    def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)

    @pyqtSlot()
    def openDocumentation(self) -> None:
        # Starting a web browser from a signal handler connected to a menu will crash on windows.
        # So instead, defer the call to the next run of the event loop, since that does work.
        # Note that weirdly enough, only signal handlers that open a web browser fail like that.
        event = CallFunctionEvent(self._openUrl, [QUrl("https://qidi.com/en/resources/manuals/software")], {})
        qidi.QIDIApplication.QIDIApplication.getInstance().functionEvent(event)

    @pyqtSlot()
    def openBugReportPage(self) -> None:
        event = CallFunctionEvent(self._openUrl, [QUrl("https://github.com/QIDI/QIDI/issues/new/choose")], {})
        qidi.QIDIApplication.QIDIApplication.getInstance().functionEvent(event)

    @pyqtSlot()
    def factorySetting(self):
        Resources.factoryReset()
        #sys.exit(1)
        os._exit(0)

    @pyqtSlot()
    def homeCamera(self) -> None:
        """Reset camera position and direction to default"""

        scene = qidi.QIDIApplication.QIDIApplication.getInstance().getController().getScene()
        camera = scene.getActiveCamera()
        if camera:
            diagonal_size = qidi.QIDIApplication.QIDIApplication.getInstance().getBuildVolume().getDiagonalSize()
            camera.setPosition(Vector(-80, 250, 700) * diagonal_size / 375)
            camera.setPerspective(True)
            camera.lookAt(Vector(0, 0, 0))

    @pyqtSlot()
    def centerSelection(self) -> None:
        """Center all objects in the selection"""

        operation = GroupedOperation()
        for node in Selection.getAllSelectedObjects():
            current_node = node
            parent_node = current_node.getParent()
            while parent_node and parent_node.callDecoration("isGroup"):
                current_node = parent_node
                parent_node = current_node.getParent()

            #   This was formerly done with SetTransformOperation but because of
            #   unpredictable matrix deconstruction it was possible that mirrors
            #   could manifest as rotations. Centering is therefore done by
            #   moving the node to negative whatever its position is:
            center_operation = TranslateOperation(current_node, -current_node._position)
            operation.addOperation(center_operation)
        operation.push()

    @pyqtSlot(int,int,bool)
    def multiplySelection(self, count: int,spacing: int,checked:bool) -> None:
        """Multiply all objects in the selection

        :param count: The number of times to multiply the selection.
        """
        min_offset = qidi.QIDIApplication.QIDIApplication.getInstance().getBuildVolume().getEdgeDisallowedSize() + 2  # Allow for some rounding errors
        job = MultiplyObjectsJob(Selection.getAllSelectedObjects(), count,spacing,checked, min_offset = max(min_offset, 8))
        job.start()

    @pyqtSlot()
    def deleteSelection(self) -> None:
        """Delete all selected objects."""

        if not qidi.QIDIApplication.QIDIApplication.getInstance().getController().getToolsEnabled():
            return

        removed_group_nodes = [] #type: List[SceneNode]
        op = GroupedOperation()
        nodes = Selection.getAllSelectedObjects()
        for node in nodes:
            op.addOperation(RemoveSceneNodeOperation(node))
            group_node = node.getParent()
            if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
                remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
                if len(remaining_nodes_in_group) == 1:
                    removed_group_nodes.append(group_node)
                    op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
                    op.addOperation(RemoveSceneNodeOperation(group_node))

            # Reset the print information
            qidi.QIDIApplication.QIDIApplication.getInstance().getController().getScene().sceneChanged.emit(node)

        op.push()

    @pyqtSlot(str)
    def setExtruderForSelection(self, extruder_id: str) -> None:
        """Set the extruder that should be used to print the selection.

        :param extruder_id: The ID of the extruder stack to use for the selected objects.
        """

        operation = GroupedOperation()

        nodes_to_change = []
        for node in Selection.getAllSelectedObjects():
            # If the node is a group, apply the active extruder to all children of the group.
            if node.callDecoration("isGroup"):
                for grouped_node in BreadthFirstIterator(node): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
                    if grouped_node.callDecoration("getActiveExtruder") == extruder_id:
                        continue

                    if grouped_node.callDecoration("isGroup"):
                        continue

                    nodes_to_change.append(grouped_node)
                continue

            # Do not change any nodes that already have the right extruder set.
            if node.callDecoration("getActiveExtruder") == extruder_id:
                continue

            nodes_to_change.append(node)

        if not nodes_to_change:
            # If there are no changes to make, we still need to reset the selected extruders.
            # This is a workaround for checked menu items being deselected while still being
            # selected.
            ExtruderManager.getInstance().resetSelectedObjectExtruders()
            return

        for node in nodes_to_change:
            operation.addOperation(SetObjectExtruderOperation(node, extruder_id))
        operation.push()

    @pyqtSlot(int)
    def setBuildPlateForSelection(self, build_plate_nr: int) -> None:
        Logger.log("d", "Setting build plate number... %d" % build_plate_nr)
        operation = GroupedOperation()

        root = qidi.QIDIApplication.QIDIApplication.getInstance().getController().getScene().getRoot()

        nodes_to_change = []  # type: List[SceneNode]
        for node in Selection.getAllSelectedObjects():
            parent_node = node  # Find the parent node to change instead
            while parent_node.getParent() != root:
                parent_node = cast(SceneNode, parent_node.getParent())

            for single_node in BreadthFirstIterator(parent_node):  # type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
                nodes_to_change.append(single_node)

        if not nodes_to_change:
            Logger.log("d", "Nothing to change.")
            return

        for node in nodes_to_change:
            operation.addOperation(SetBuildPlateNumberOperation(node, build_plate_nr))
        operation.push()

        Selection.clear()

    def _openUrl(self, url: QUrl) -> None:
        QDesktopServices.openUrl(url)


while True:
    try:
        a = float(input('Введите сторону a: '))
        b = float(input('Введите сторону b: '))
        c = float(input('Введите сторону c: '))

        if a <= 0 or b <= 0 or c <= 0:
            print('Ошибка: Значения сторон треугольника должны быть положительными числами.')
        elif (a >= b + c) or (b >= a + c) or (c >= a + b):
            print('Треугольника с такими сторонами не существует.')
        else:
            print('Это треугольник.')

            if a == b == c:
                print('Треугольник равносторонний и равнобедренный.')
            elif a == b or b == c or c == a:
                print('Треугольник равнобедренный.')
            else:
                print('Треугольник разносторонний.')

        break
    except ValueError:
        print('Ошибка: Введите числовые значения сторон треугольника.')


#python -m unittest discover tests  运行tests文件夹下所有测试文件

import unittest
from VarFun import Variable,square
import numpy as np

def numerical_diff(f,x:Variable,eps=1e-4):
    x0=Variable(x.data-eps)
    x1=Variable(x.data+eps)
    y0=f(x0)
    y1=f(x1)
    return (y1.data-y0.data)/(2*eps)

class SquareTest(unittest.TestCase):

    def test_forward(self):
        x=Variable(np.array(2.0))
        y=square(x)
        expected=np.array(4.0)
        self.assertEqual(y.data,expected)

    def test_backward(self):
        x=Variable(np.array(3.0))
        y=square(x)
        expected=np.array(6.0)
        y.backward()
        self.assertEqual(x.grad,expected)

    def test_gradient_check(self):

        for i in range(20):
            x=Variable(np.random.rand(1))
            y=square(x)
            y.backward()
            num_grad=numerical_diff(square,x)
            flg=np.allclose(x.grad,num_grad,rtol=1e-5,atol=1e-8)
            self.assertTrue(flg)

# unittest.main() #运行时可以省略掉-m unittest


#!/usr/bin/python3
#
# A program to check the validity of topics.list
#
# usage: check-topic.py WHENCE KERNEL-RPMs...
#

from sys import argv
from fwtopics import FWTopics

if __name__ == '__main__':
    fw = FWTopics()
    argv.pop(0)
    fw.parse_whence(argv.pop(0))
    for arg in argv:
        fw.scan_firmware(arg, fw.check_module())


from board_logic import BoardLogic
from game_manager import GameManager
from game_piece import GamePiece
import re

# A board game for Othello
BLACK = 0
WHITE = 255

class Board:
    """A class for the Othello board"""

    def __init__(self, WIDTH, HEIGHT, SIZE):
        """Creates an instance of a board for Othello given the width, height,
        and size of the board.
        """
        self.name = ""
        self.WIDTH = WIDTH
        self.HEIGHT = HEIGHT
        self.SIZE = SIZE
        self.SPACE_SIZE = WIDTH//SIZE
        self.HOR_LINES = []
        self.VERT_LINES = []
        self.game_pieces = []
        self.board_logic = BoardLogic(WIDTH, HEIGHT, SIZE, self.SPACE_SIZE)
        self.click_count = 0
        self.pieces_on_board = 0
        self.game_manager = GameManager(self.board_logic)
        self.current_color = BLACK
        self.needs_check = True
        self.game_started = False
        self.no_legal_moves = 0
        self.display_turn = True
        self.game_over = False
        self.file_handle_needed = True

    def start_game(self):
        """Displays the first four pieces of the game"""
        x_mid = self.WIDTH // 2
        y_mid = self.HEIGHT // 2
        mid_space = self.SPACE_SIZE / 2
        top_right_space_x = x_mid + mid_space
        top_right_space_y = y_mid - mid_space
        top_left_space_x = x_mid + mid_space
        top_left_space_y = y_mid + mid_space
        bottom_right_space_x = x_mid - mid_space
        bottom_right_space_y = y_mid - mid_space
        bottom_left_space_x = x_mid - mid_space
        bottom_left_space_y = y_mid + mid_space
        self.place_piece(top_right_space_x, top_right_space_y)
        self.place_piece(top_left_space_x, top_left_space_y)
        self.place_piece(bottom_left_space_x, bottom_left_space_y)
        self.place_piece(bottom_right_space_x, bottom_right_space_y)
        self.game_started = True
        for piece in self.game_pieces:
            piece.display()

    def create_lines(self):
        """Draws the game board lines according to the size of the game"""
        for i in range(1, self.SIZE):
            self.VERT_LINES.append((self.WIDTH//self.SIZE)*i)
        for j in range(1, self.SIZE):
            self.HOR_LINES.append((self.HEIGHT//self.SIZE)*j)

    def display(self):
        """Displays the game lines of the board"""
        stroke(0, 0, 10)
        strokeWeight(5)
        self.create_lines()
        for x in self.VERT_LINES:
            line(x, 0, x, self.HEIGHT)
        for y in self.HOR_LINES:
            line(0, y, self.WIDTH, y)
        self.start_game()

    def update_click(self, x, y):
        """Places a new piece on the board if a legal empty space is clicked"""
        if self.game_over:
            return
        self.place_piece(x, y)
        for piece in self.game_pieces:
            piece.display()
        self.game_over = self.game_manager.winning_conditions(
                         self.no_legal_moves,
                         self.game_pieces,
                         self.pieces_on_board)

    def place_piece(self, clicked_x, clicked_y):
        """Places a game piece at the given x and y coordinates"""
        if self.board_logic.point_clicked(clicked_x, clicked_y) is not None:
            x, y = self.board_logic.point_clicked(clicked_x, clicked_y)
            this_point = (x, y)
            self.legal_move(this_point, self.current_color)

    def legal_move(self, this_point, COLOR):
        """Determines whether or a not a clicked upon space is a legal move"""
        if (self.board_logic.space_available(this_point) and
            self.board_logic.adjacent_to_otherpiece(self.game_started,
                                                    this_point, COLOR)):
                self.no_legal_moves = 0
                self.game_pieces.append(GamePiece(this_point[0], this_point[1],
                                                  COLOR, self.SPACE_SIZE))
                self.board_logic.occupy_space(this_point, COLOR)
                self.pieces_on_board += 1
                pieces_to_flip = self.board_logic.target_pieces(COLOR)
                self.flip_pieces(pieces_to_flip, COLOR)
                self.display_turn = True
                if self.current_color == BLACK:
                    self.current_color = WHITE
                else:
                    self.current_color = BLACK
                    self.needs_check = True

        elif not self.board_logic.check_move_possible(self.game_started,
                                                      self.current_color):
            if not self.game_over:
                self.no_legal_moves += 1
                if self.current_color == BLACK:
                    self.current_color = WHITE
                    print("BLACK HAS NO MORE MOVES, WHITE'S TURN")
                else:
                    self.current_color = BLACK
                    print("WHITE HAS NO MORE MOVES, BLACK'S TURN")

    def flip_pieces(self, pieces_to_flip, COLOR):
        """Flips the opponents pieces if a legal move is made"""
        for coordinate in pieces_to_flip:
            for piece in self.game_pieces:
                if (piece.x == coordinate[0] and piece.y == coordinate[1]):
                    piece.COLOR = COLOR

    def file_handling(self, game_pieces):
        """Prints the player's score at the end of the game onto the 'scores.txt' document
        allow with other past scores from previously played games"""
        score = self.game_manager.count_colors(game_pieces)[0]
        my_pair = (str(self.name) + " " + str(score), score)
        pair_score_list = []
        pair_score_list.append(my_pair)
        score_file = open("scores.txt", "r+")
        score_file.readline()
        for line in score_file:
            parse_results = re.findall("\w+", line)
            if len(parse_results) == 0:
                continue
            else:
                pair_score_list.append((line.strip(), int(parse_results[-1])))
        sorted_pairs = sorted(pair_score_list, key=lambda x: x[1],
                              reverse=True)
        score_file.truncate(0)
        score_file.seek(0)
        score_file.write("===== HIGH SCORES =====\n")
        for pair in sorted_pairs:
            score_file.write(pair[0] + "\n")
        score_file.close()


age = int(input('enter your age: '))
while age < 25:
    print('you\'re still in school')
    break
else:
    print("you're working")
money=int(input('enter amount'))
while money<500 and age>25:
    print('You\'re just too poor!!!')
    exit()
else:
    print('Perhaps You\'re rich...')


import heapq
import sys
input = sys.stdin.readline

(N, M, X) = map(int, input().split())

edge = [[sys.maxsize for j in range(N+1)] for i in range(N+1)]

for m in range(M):
    (A, B, T) = map(int, input().split())
    edge[A][B] = T

come = [sys.maxsize for n in range(N+1)]
go = [sys.maxsize for n in range(N+1)]

come[X] = 0
go[X] = 0

heap_c = [(0, X)]
heap_g = [(0, X)]

while heap_c:
    (t, n) = heapq.heappop(heap_c)
    for i in range(1, N+1):
        if edge[n][i] != sys.maxsize and edge[n][i] + t < come[i]:
            come[i] = edge[n][i] + t
            heapq.heappush(heap_c, (come[i], i))

while heap_g:
    (t, n) = heapq.heappop(heap_g)
    for i in range(1, N+1):
        if edge[i][n] != sys.maxsize and edge[i][n] + t < go[i]:
            go[i] = edge[i][n] + t
            heapq.heappush(heap_g, (go[i], i))

print(max([come[i] + go[i] for i in range(1, N+1)]))


import numpy as np
import matplotlib.pyplot as plt
from tri_functions import *
import os
from matplotlib import animation
import time
from mpl_toolkits.axes_grid1 import Divider, Size

@jit(nopython=True)
def get_e_stack(vi,vj):
    e_stack = np.zeros((vi.shape[0],3,2,2))
    for i in range(vi.shape[0]):
        for j in range(3):
            e_stack[i,j] = np.row_stack((vi[i,j],vj[i,j]))
    return e_stack

def plot_mesh(ax,v,neigh,Lx,Ly,color="black",alpha=1):
    v = v[~np.isnan(v[:,0])]
    neigh = neigh[neigh[:,0]!=-1]
    v_neigh = tri_call3(v, neigh)
    v_CCW = roll3(v_neigh, 1)
    vn = get_vn(v, v_CCW, Lx, Ly)
    vi = np.expand_dims(v,1)*np.ones_like(vn)
    vj = vi-vn
    e_stack = get_e_stack(vi,vj)
    ax.plot(e_stack[:,:,:,0].reshape(-1,2).T,e_stack[:,:,:,1].reshape(-1,2).T,color=color,alpha=alpha)
    # for i in range(vi.shape[0]):
    #     for j in range(3):
    #         e = np.row_stack((vi[i,j],vj[i,j]))
    #         ax.plot(e[:,0],e[:,1],color="black")
    ax.set(xlim=(0,Lx),ylim=(0,Ly),aspect=1)

def plot_tri(ax,tcnt,Lx,Ly,color="black"):
    tcnt = tcnt[~np.isnan(tcnt[:,0])]
    for i in range(3):
        cnts = np.array((tcnt[:, i], tcnt[:, np.mod(i + 1, 3)]))
        cnts[1] = cnts[0] + per(cnts[1]-cnts[0],Lx,Ly)
        ax.plot(cnts[:,:,0],cnts[:,:,1],color=color)

def fix_axes_size_incm(axew, axeh,fig,ax,pad=0.8):
    axew = axew*pad
    axeh = axeh*pad

    #lets use the tight layout function to get a good padding size for our axes labels.
    # fig = plt.gcf()
    # ax = plt.gca()
    # fig.tight_layout()
    #obtain the current ratio values for padding and fix size
    oldw, oldh = fig.get_size_inches()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom

    #work out what the new  ratio values for padding are, and the new fig size.
    neww = axew+oldw*(1-r+l)
    newh = axeh+oldh*(1-t+b)
    newr = r*oldw/neww
    newl = l*oldw/neww
    newt = t*oldh/newh
    newb = b*oldh/newh

    #right(top) padding, fixed axes size, left(bottom) pading
    hori = [Size.Scaled(newr), Size.Fixed(axew), Size.Scaled(newl)]
    vert = [Size.Scaled(newt), Size.Fixed(axeh), Size.Scaled(newb)]

    divider = Divider(fig, (0.0, 0.0, 1., 1.), hori, vert, aspect=False)
    # the width and height of the rectangle is ignored.

    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    #we need to resize the figure now, as we have may have made our axes bigger than in.
    fig.set_size_inches(neww,newh)

def animate_mesh(v_save,neigh_save,L,n_frames=100, file_name=None, dir_name="plots",scale=10):
    if L.shape == L.size:
        L = np.ones((v_save.shape[0],1))*np.expand_dims(L,0)

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

    fig = plt.figure(figsize=(scale,scale*L[:,1].max()/L[:,0].max()))
    sf = scale/L[:,0].max()
    ax1 = fig.add_subplot(1, 1, 1)

    skip = int((v_save.shape[0]) / n_frames)

    def animate(i):

        ax1.cla()

        v = v_save[i*skip]
        neigh = neigh_save[i*skip]
        Lx,Ly = L[i*skip]
        plot_mesh(ax1,v,neigh,Lx,Ly)
        xlim = (0, Lx)
        ylim = (0, Ly)
        # ax1.set_facecolor('black')

        ax1.set(aspect=1, xlim=xlim, ylim=ylim)
        fix_axes_size_incm(Lx*sf,Ly*sf,fig,ax1)

    Writer = animation.writers["ffmpeg"]
    writer = Writer(fps=20, bitrate=500)
    if file_name is None:
        file_name = "animation %d" % time.time()
    an = animation.FuncAnimation(fig, animate, frames=n_frames, interval=200)
    an.save("%s/%s.mp4" % (dir_name, file_name), writer=writer, dpi=264)


# this program will pull random meal plans for the keto diet

import random

proteins = [
    'chicken',
    'steak',
    'fish',
    'sausage link',
    'ham',
    'pastrami',
    'pork',
    'ground beef',
    'turkey',
    'seafood',
    'hot dogs',
    'eggs'
]

veggies = [
    'cauliflower',
    'artichokes',
    'cabbage',
    'celery',
    'mushrooms',
    'okra',
    'sauerkraut',
    'spinach',
    'tomatoes',
    'brocolli',
    'squash',
    'zuchinni',
    'brussel sprouts',
    'green salad',
    'radish',
    'turnip',
    'Jicama',
    'green beans',
    'cucumber',
    'onion',
    'bell peppers'
]

fats = [
    'butter',
    'cooking oil',
    'cheese',
    'bacon',
    'avocado',
    'dressing',
    'nuts',
    'pork rinds'
]

meal = {
    'protein': random.choice(proteins),
    'veggie': random.choice(veggies),
    'fat': random.choice(fats)
}

# sometimes we want one more veggie
if random.randint(0,100) < 50:
    meal['veggie'] = meal['veggie']  + ' and ' + random.choice(veggies)

meal_str = "Tonight's meal is {protein} with a side of {veggie}, topped with {fat}."
print(meal_str.format(**meal))


import os

DB_URI = "mysql+pymysql://root:wei3511@localhost:3306/icbc_demo?charset=utf8"

SQLALCHEMY_DATABASE_URI = DB_URI

SQLALCHEMY_TRACK_MODIFICATIONS = False

SECRET_KEY = os.urandom(24)  #给session 加盐，随机数字


from tkinter import *
from tkinter import ttk
from colors import *
import os
root = Tk()

names_dict = {'Sebastian Mielczarek':'SM',
                    'Magda':'Mg'
                    }
def gui_init():
    #Mainwindows settings
    root.title('Kreator folderów R')
    root.maxsize(1920,1080)
    root.minsize(600,400)

    root_frame=Frame(root,bg=c_dark_grey)
    root_frame.pack(fill="both",expand=True)

    Label(root_frame,
        text="Wybierz autora:",
        foreground=c_black,
        background=c_grey).grid(row=0, column=0, padx=(5,5), pady=0, sticky="sew")

    type_combobox = ttk.Combobox(root_frame,
        foreground=c_black,
        background=c_grey,
        values=[x for x in list(names_dict.keys())],
        height=20,state="readonly")

    type_combobox.current(0)
    type_combobox.grid(row=1,column=0,padx=(5,5), sticky="new")

    path = 'Radzyń 1'

    if not os.path.exists(path+'/Sebastian Mielczarek/'):
        os.makedirs(path+'/Sebastian Mielczarek/')

if __name__ == "__main__":
    gui_init()
    root.mainloop()


import string
import random

#LETTERS = string.ascii_lowercase + string.ascii_uppercase
LETTERS = string.ascii_letters
print(LETTERS)

key = random.randrange(0,len(LETTERS))

plaintext = "Hello World"

#caesarEncryption
ciphertext = ""
for char in plaintext:
    if char in LETTERS:
        ciphertext += LETTERS[(LETTERS.find(char) + key) % len(LETTERS)]
    else:
        ciphertext += char

print(ciphertext)
#caesarDecryption
#ciphertext,key,LETTERS
decrypt = ""
for char in ciphertext:
    if char in LETTERS:
        decrypt += LETTERS[(LETTERS.find(char) - key) % len(LETTERS)]
    else:
        decrypt += char

print(decrypt)


"""Download dataset : https://www.robots.ox.ac.uk/~vgg/data/pets/
"""

import os
from typing import List, Tuple, Union

import albumentations as A
import numpy as np
import torch
from albumentations.pytorch import ToTensorV2
from PIL import Image
from torch.utils.data import Dataset

def make_transform(image_set: str) -> A.Compose:
    """Creates a transformation pipeline based on the given image set ("train" or "test").

    Args:
    - image_set (str): The set of images for which transformations need to be made ("train" or otherwise).

    Returns:
    - A.Compose: A composition of various augmentations.
    """
    # Mean and Standard deviation for normalization
    mean = (0.485, 0.456, 0.406)
    std = (0.229, 0.224, 0.225)

    # Augmentations for training set
    if image_set == "train":
        return A.Compose(
            [
                A.Rotate(limit=35),  # Rotation augmentation
                A.HorizontalFlip(),  # Horizontal flip augmentation
                A.VerticalFlip(),  # Vertical flip augmentation
                A.Resize(height=256, width=256),  # Resizing the images
                A.Normalize(mean=mean, std=std, max_pixel_value=255.0),  # Normalizing images
                ToTensorV2(),  # Converting images to PyTorch tensors
            ],
        )
    # Augmentations for validation or test set
    else:
        return A.Compose(
            [
                A.Resize(height=256, width=256),  # Resizing the images
                A.Normalize(mean=mean, std=std, max_pixel_value=255.0),  # Normalizing images
                ToTensorV2(),  # Converting images to PyTorch tensors
            ],
        )

class OxfordIiitPets(Dataset):
    """PyTorch Dataset for Oxford-IIIT Pet Dataset.

    Args:
    - image_dir (str): Path to the directory containing images.
    - images_list (List[str]): List of paths to the images.
    - mask_dir (str): Path to the directory containing masks.
    - transforms (Union[A.Compose, None]): Transformations to apply on the images and masks.
    """

    def __init__(
        self,
        image_dir: str,
        images_list: List[str],
        mask_dir: str,
        transforms: Union[A.Compose, None] = None,
    ):
        self.image_dir = image_dir
        self.images_list = images_list
        self.mask_dir = mask_dir
        self.transforms = transforms

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

    def __getitem__(self, idx) -> Tuple[torch.Tensor, torch.Tensor]:
        """Fetches an image and its corresponding mask based on the index provided.

        Args:
        - idx (int): Index of the image and mask pair to fetch.

        Returns:
        - tuple: A tuple containing the transformed image and mask.
        """
        ip = os.path.join(self.image_dir, self.images_list[idx])
        mp = os.path.join(self.mask_dir, self.images_list[idx].replace("jpg", "png"))

        image = Image.open(ip).convert("RGB")
        mask = Image.open(mp)

        mask = np.array(mask)
        mask[mask == 3] = 0  # background
        mask[mask == 2] = 2  # border
        mask[mask == 1] = 1  # pet

        if self.transforms:
            transformed = self.transforms(image=np.array(image), mask=mask)
            image = transformed["image"]
            mask = transformed["mask"]

        return image, mask

# if __name__=="__main__":
#     import glob

#     import matplotlib.pyplot as plt
#     from torch.utils.data import DataLoader

#     image_dir = "sample_dataset/oxford_iiit_pets/images"
#     mask_dir = "sample_dataset/oxford_iiit_pets/annotations/trimaps"

#     image_dir = r"C:\Users\anant\Downloads\images.tar\images"
#     mask_dir = r"C:\Users\anant\Downloads\oxford_iiit_pets\annotations.tar\annotations\trimaps"
#     images_list = []
#     for ext in [".jpg", ".jpeg", ".png"]: # filtering images
#         files = glob.glob(f"{image_dir}/*{ext}")
#         images_list += [os.path.basename(f) for f in files]

#     dset = OxfordIiitPets(
#         mask_dir=mask_dir,
#         image_dir=image_dir,
#         images_list=images_list,
#         transforms=make_transform(image_set="val"),
#     )

#     loader = DataLoader(dset, batch_size=1)
#     for x, y in loader:
#         print(x.shape, y.shape)
#         plt.subplot(1, 2, 1)
#         plt.imshow(x[0].permute(1, 2, 0))

#         plt.subplot(1, 2, 2)
#         plt.imshow(y[0])

#         plt.show()