import json
def VMPFC(si,a,m,p,e): #si:Stimulus, a:Hidonic, m:Magnitude, p:Probability, e:salience
    r = []
    mayor = []
    action = DLPPFC()# take the disponible actions from DLPFC function
    experience = VLPFC(si) #Use the historial associacions from VLPFC fuction

    k=0.4 #volatil variable
    c =0.3 #volatil variable
    Pv = (k*(a*m*p))+(c*e)/(k+c) #Utility stabelized
    print("Pv:",Pv)
    labelo = [Valorations(a),Valorations(m),Valorations(p),Valorations(e),Valorations(Pv)] #Label of status string
    #rule
    if(experience !=0):
        if (Pv >= experience["Utility"]): #compare only the stimulus selected
            #labelo.append(Valorations(Pv)) #add the label to labels array
            r = [si,action,Pv] #crate tuple stimulus, action, Utility
        else:
            all=VLPFC(1) #incert "1" to obtain all the historial
            for i in all:
                mayor.append(i["Utility"])
                aa=max(mayor) #obtain the biggest utility from the historial
            for i in all:
                if aa == i["Utility"]: #look for the associasion corresponding with the biggest ulility
                    si = str(i["if"])
            r=[si, action,aa]    #append the new biggest associasion

    return labelo, r

def VLPFC(si):#Assosiations historial
    historial = ""
    memory_association = ({"Id":0,"if":"A" ,"then":1,"Utility":0.64},{"Id":1,"if":"B" ,"then":1,"Utility":0.23},
    {"Id":2,"if":"C" ,"then":1,"Utility":0.54},{"Id":3,"if":"D" ,"then":1,"Utility":0.70})
    a = json.dumps(memory_association)
    memory_association = json.loads(a)
    for i in memory_association:
        if(i["if"] == si):
            historial = i
            print(historial)
    if(si == 1):
        historial = memory_association
    return historial

def DLPPFC():#disponible actions
    act = "selecto"
    return act

def Valorations(num): #Label Hidonic states
    val = []
    layer = ""
    if num >= 0.87:
        layer = "Excelente"
    elif num < 0.87 and num >= 0.55:
        layer = "Very_good"
    elif num < 0.55 and num >= 0.35:
        layer = "Good"
    elif num < 0.35 and num >= 0.15:
        layer = "More_less_good"
    elif num < 0.15 and num >= 0.01:
        layer = "Few_good"
    elif num == 0:
        layer = "Neutral"
    elif num > -0.15 and num <= -0.01:
        layer = "Few_bad"
    elif num > -0.35 and num <= -0.15:
        layer = "More_less_bad"
    elif num > -0.55 and num <= -0.35:
        layer = "Bad"
    elif num > -0.87 and num <= -0.55:
        layer = "Very_bad"
    elif num <= -0.87:
        layer = "Horrible"
    val.append(layer)

    return val

print(VMPFC("A", -0.53,0.57,1,-0.87)) #incert (stimulus, hidonic-value, reward-magnitude, reward-probability, incentive-salience)


import logging
import os
import time

from google.cloud import storage

from export_src import utils

logger = logging.getLogger('exporter')

def upload_file(local_file_path, storage_folder):
    if not local_file_path:
        logger.debug('No CSV-file had been generated, skipping the upload')
        return

    service_account_json = os.getenv('GCP_SERVICE_ACCOUNT_JSON', None)
    if service_account_json:
        storage_client = storage.Client.from_service_account_json(service_account_json)
    else:
        storage_client = storage.Client()

    bucket_id = utils.get_bucket_id()
    logger.debug('Uploading "{}" to bucket "{}" ...'.format(local_file_path, bucket_id))

    bucket = storage_client.bucket(bucket_id)
    file_name = os.path.basename(local_file_path)
    object_blob = bucket.blob(os.path.join(storage_folder, file_name))

    start_time = time.time()
    # this will override existing objects (if not prevented by the bucket versioning and lifecycle policies)
    object_blob.upload_from_filename(filename=local_file_path)
    end_time = time.time()

    elapsed_time_in_sec = end_time - start_time
    file_size_in_mb = os.path.getsize(local_file_path) / 1.0e6
    upload_rate_in_mbit_per_sec = 8 * file_size_in_mb / elapsed_time_in_sec
    logger.debug('... done ({:.1f} MB), {:.1f} Mbit/s'.format(file_size_in_mb, upload_rate_in_mbit_per_sec))


# https://www.acmicpc.net/problem/2754

# 성적에 따른 평점을 dictionary 변수로 저장합니다.
grade_to_score = {
    'A+': 4.3, 'A0': 4.0, 'A-': 3.7,
    'B+': 3.3, 'B0': 3.0, 'B-': 2.7,
    'C+': 2.3, 'C0': 2.0, 'C-': 1.7,
    'D+': 1.3, 'D0': 1.0, 'D-': 0.7,
    'F': 0.0
}

# 첫째 줄에 C언어 성적을 입력합니다.
C_grade = input()

# 입력한 성적에 따른 평점을 출력합니다.
print(grade_to_score[C_grade])


from typing import Final, Sequence, Tuple
import datetime
from spideriment_ng.logger.LogSeverity import LogSeverity
from spideriment_ng.logger.LoggingStrategyIface import LoggingStrategyIface

class Logger:
    _LOG_DATETIME_FORMAT: Final[str] = "%Y-%m-%d %H:%M:%S"

    def __init__(self, logging_strategy: LoggingStrategyIface, logged_severities: Sequence[LogSeverity], source_identifier: str):
        self._logging_strategy: Final[LoggingStrategyIface] = logging_strategy
        self._logged_severities: Final[Tuple[LogSeverity, ...]] = tuple(logged_severities)
        self._source_identifier: Final[str] = source_identifier
        self._operational: bool = True

    def log(self, severity: LogSeverity, message: str) -> None:
        assert self._operational

        if severity not in self._logged_severities:
            return

        log_string = "[{datetime} / {source} / {severity}] {message}".format(
            datetime=datetime.datetime.now().strftime(self.__class__._LOG_DATETIME_FORMAT),
            source=self._source_identifier,
            severity=self._get_string_representation_of_log_severity(severity),
            message=message
        )

        self._logging_strategy.process_log_string(log_string)

    def _get_string_representation_of_log_severity(self, severity: LogSeverity) -> str:
        severity_string = ({
            LogSeverity.ERROR: "ERROR",
            LogSeverity.WARNING: "WARN",
            LogSeverity.INFO: "INFO",
            LogSeverity.DEBUG: "DEBUG"
        }.get(severity, None))

        assert (severity_string is not None)

        return severity_string

    def terminate(self) -> None:
        assert self._operational
        self._operational = False

        self._logging_strategy.terminate()


import cv2
import sys
from PIL import Image
import numpy as np
import csv
import shortuuid
import os
import glob
import re
import ntpath

ROOT_PATH = 'C:\\dev\\courses\\2.131 - Advanced Instrumentation\\'
# FILE_NAME = 'Ecoli-HangingDrop-20x-Dilution-1.MOV'
FILE_NAME = 'Ecoli-Slide-Coverslip.MOV'
# FILE_NAME = 'Rhodosprillum-HangingDrop-3ul.MOV'
# FILE_NAME = 'HangingDrop-100ul-Nutrient-25ul-Ecoli-lRhodo-(50-50).MOV'
# FILE_NAME = 'Perturbation-Test1-PCB-Slide.MOV'

tracker_types = ['BOOSTING', 'MIL', 'KCF', 'TLD', 'MEDIANFLOW', 'GOTURN']
WIN_NAME = "2.131 Bacterial Tracker"
POS_TRACKBAR = "FRAME"

class TrackerUI(object):

    def __init__(self, tracker_type='MIL', duration_sec=10.0):
        self._filename = FILE_NAME
        self._root_path = ROOT_PATH
        self._tracker_type = tracker_type
        self._cap = cv2.VideoCapture(ROOT_PATH + FILE_NAME)
        self._cap_fps = self._cap.get(cv2.CAP_PROP_FPS)
        self._save_video = True
        self._duration_sec=duration_sec
        self._duration_frames = int(self._cap_fps * self._duration_sec)
        self._is_tracking = False
        self._is_playing = False
        self.load_existing_trackers()
        self.setup_ui()

    def get_tracker(self, tracker_type):
        if tracker_type == 'BOOSTING':
            return cv2.TrackerBoosting_create()
        if tracker_type == 'MIL':
            return cv2.TrackerMIL_create()
        if tracker_type == 'KCF':
            return cv2.TrackerKCF_create()
        if tracker_type == 'TLD':
            return cv2.TrackerTLD_create()
        if tracker_type == 'MEDIANFLOW':
            return cv2.TrackerMedianFlow_create()
        if tracker_type == 'GOTURN':
            return cv2.TrackerGOTURN_create()

    def load_existing_trackers(self):
        self._existing_trackers = {}
        self._trackers_by_id = {}
        self._loaded_trackers = {}
        # self._live_trackers = {}
        tracker_csvs = glob.glob(ROOT_PATH + FILE_NAME + ".*.csv")
        for f in tracker_csvs:
            # parse out key info
            m = re.match('.*\.(\w+)\.(\d+)\.(\d+)\.(\d+)\.csv', ntpath.basename(f))
            if m:
                id = m.group(1)
                w = int(m.group(2))
                h = int(m.group(3))
                start = int(m.group(4))
                # key them by their start frame
                if start in self._existing_trackers:
                    self._existing_trackers[start].append((id,f,w,h))
                else:
                    self._existing_trackers[start] = [(id, f, w, h)]
                self._trackers_by_id[id] = (start, w, h)

    def seek_callback(self, x):
        if self._is_tracking or self._is_playing:
            return
        i = cv2.getTrackbarPos(POS_TRACKBAR, WIN_NAME)
        self._cap.set(cv2.CAP_PROP_POS_FRAMES, i-1)
        self.next_frame()

    def skip_frame_generator(self, df):
        cf = self._cap.get(cv2.CAP_PROP_POS_FRAMES) - 1
        self._cap.set(cv2.CAP_PROP_POS_FRAMES, cf + df)
        cv2.setTrackbarPos(POS_TRACKBAR, WIN_NAME,
            int(self._cap.get(cv2.CAP_PROP_POS_FRAMES)))
        _, frame = self._cap.read()
        self._current_frame = frame
        cv2.imshow(WIN_NAME, frame)

    def next_frame(self):
        ret, frame = self._cap.read()
        self._current_frame = frame

        cv2.putText(frame, "2.131 Bacterial Tracker", (100, 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);

        # add any existing trackers
        current_frame = int(self._cap.get(cv2.CAP_PROP_POS_FRAMES))
        # load a live
        valid_trackers = [s for s in self._existing_trackers.keys()
                          if s <= current_frame and
                          s + self._duration_frames > current_frame-1]

        for t in valid_trackers:
            for (id, f, w, h) in self._existing_trackers[t]:
                if id not in self._loaded_trackers:
                    # load the csv
                    with open(f, 'r') as my_file:
                        reader = csv.reader(my_file)
                        self._loaded_trackers[id] = list(reader)
                # now draw the appropriate rect for this tracker
                try:
                    line = self._loaded_trackers[id][current_frame - t + 1]
                    p1 = (int(int(line[3]) - w/2.), int(int(line[4]) - h/2.))
                    p2 = (int(int(line[3]) + w/2.), int(int(line[4]) + h/2.))
                    cv2.rectangle(frame, p1, p2, (255, 128, 128), 2, 1)
                    p1x, p1y = p1
                    cv2.putText(frame, id[:3], (p1x,p1y-20),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
                except Exception as e:
                    print(e)
                    print("Id: {0}, Start Frame: {1} Current Frame: {2}, Total: {3}".format(
                        id, t, current_frame, len(self._loaded_trackers[id])
                    ))
        cv2.imshow(WIN_NAME, frame)
        return frame

    def play_pause(self):
        self.is_playing = True
        while True:
            self.next_frame()
            cv2.setTrackbarPos(POS_TRACKBAR, WIN_NAME,
                int(self._cap.get(cv2.CAP_PROP_POS_FRAMES)))
            key = cv2.waitKey(10) & 0xFF
            if key == ord(" "):
                break
        self.is_playing = False

    def setup_ui(self):
        cv2.namedWindow(WIN_NAME)
        cv2.createTrackbar(
            POS_TRACKBAR, WIN_NAME, 0,
            int(self._cap.get(cv2.CAP_PROP_FRAME_COUNT)), self.seek_callback)
        # cv2.createButton("Play", self.play, buttonType=cv2.QT_PUSH_BUTTON)
        self.next_frame()

        actions = dict()
        actions[ord("\n")] = lambda: self.track_trajectory()
        actions[ord("\r")] = lambda: self.track_trajectory()
        actions[ord(" ")] = lambda: self.play_pause()
        # actions[ord("D")] = lambda: self.skip_frame_generator(10)
        # actions[ord("d")] = lambda: self.skip_frame_generator(1)
        # actions[ord("a")] = lambda: self.skip_frame_generator(-1)
        # actions[ord("A")] = lambda: self.skip_frame_generator(-10)
        actions[ord("q")] = lambda: exit(0)

        while True:
            key = cv2.waitKey(0) & 0xFF
            def dummy():
                pass
            actions.get(key, dummy)()

    def track_trajectory(self):
        self._is_tracking = True

        id = shortuuid.uuid()

        cap = self._cap

        # MIL appears to work best...
        tracker = self.get_tracker(self._tracker_type)

        cap_fps = cap.get(cv2.CAP_PROP_FPS)
        current_frame =  int(cap.get(cv2.CAP_PROP_POS_FRAMES)) # int(cap_fps * start_sec)
        duration_frames = int(cap_fps * self._duration_sec)

        # cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame)
        time = (current_frame-1) * cap_fps

        resw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        resh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        res = (resw, resh)

        frame = self._current_frame
        cv2.putText(frame, "SET MARK", (100, 150),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
        cv2.imshow(WIN_NAME, frame)

        if self._save_video:

            fourcc = cv2.VideoWriter_fourcc(*'DIVX')
            out_fname = self._root_path + self._filename + \
                        '.multi_track_{0}.avi'.format(id)
            out = cv2.VideoWriter(out_fname, fourcc, cap_fps, res)

        # Define an initial bounding box
        # bbox = (287, 23, 86, 320)

        bbox = cv2.selectROI(WIN_NAME, frame, True)
        ok = tracker.init(frame, bbox)

        # Uncomment the line below to select a different bounding box
        # selector_frame = frame.copy()

        csv_fname = self._root_path + self._filename + \
                    '.{0}.{1}.{2}.{3}.csv'.format(id, bbox[2], bbox[3], current_frame)
        csvfile = open(csv_fname, 'w', newline='')
        bac_writer = csv.writer(csvfile, delimiter=',',
            quotechar='|', quoting=csv.QUOTE_MINIMAL)

        bac_writer.writerow(['BacteriaId', 'Frame', 'Time (s)', 'X', 'Y'])

        invalid = False

        while cap.isOpened() and current_frame < duration_frames:
            # ret, frame = cap.read()
            frame = self.next_frame()

            # Start timer
            timer = cv2.getTickCount()

            # Update tracker
            ok, bbox = tracker.update(frame)

            # Calculate Frames per second (FPS)
            fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)

            # Draw bounding box
            if ok:
                p1 = (int(bbox[0]), int(bbox[1]))
                p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
                cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
                bac_writer.writerow([id, current_frame, "{:.3f}".format(time), int(bbox[0] + bbox[2]/2),
                                     int(bbox[1] + bbox[3]/2)])
            else:
                # Tracking failure
                cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

            if self._save_video:
                # Display tracker type on frame
                # cv2.putText(frame, "2.131 Bacterial Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
                # Display FPS on frame
                cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
                out.write(frame)

            # Display result
            cv2.imshow(WIN_NAME, frame)
            cv2.setTrackbarPos(POS_TRACKBAR, WIN_NAME,
                int(self._cap.get(cv2.CAP_PROP_POS_FRAMES)))

            current_frame = current_frame + 1
            time = time + 1.0/cap_fps

            # stop recording if ESC or space pressed
            k = cv2.waitKey(1) & 0xff
            if k == 27 or k == ord(" "):
                invalid = True
                break

        csvfile.close()
        if self._save_video:
            out.release()

        if invalid:
            cv2.putText(frame, "CANCELLED", (100, 80),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.75,  (0, 0, 255), 2);
            cv2.imshow(WIN_NAME, frame)
            os.remove(csv_fname)
            os.remove(out_fname)
            cv2.imshow(WIN_NAME, frame)

        self._current_frame = frame
        self._is_tracking = False
        self.load_existing_trackers()

# Goal - put in start_time seconds, get a screen

#tracker_UI = TrackerUI(Ecoli-Slide-Coverslip.MOV')
tracker_UI = TrackerUI()

# tracker_UI.track_trajectory()

# cap = cv2.VideoCapture(root_path + 'Ecoli-Slide-Coverslip.MOV')
# ret, frame = cap.read()
# mser_multi(frame)


def listCross2(l1,l2):
    """
    Returns sorted list of the words which begin with the same
    characters, common for two lists.

    Parameters
    ----------
    l1 : list of strings
    l2 : list of strings

    Returns
    -------
    Reversely sorted, unique list of words from the lists, that have the
    corresponding words beginning with the same two letters in another
    list, e.g.:
        l1 = ['Anna','Monika', 'Marek', 'Janusz']
        l2 = ['Gabriela', 'Marta', 'Maria','Antonina']
        -> ['Marta', 'Marek', 'Maria', 'Antonina', 'Anna']
    """
    newlist = []
    for el1 in l1:
        for el2 in l2:
            if(el1[:2]==el2[:2]):
                newlist.append(el1)
                newlist.append(el2)
    newlist = list(dict.fromkeys(newlist))
    newlist.sort(reverse=True)
    return newlist


from flask import Flask, render_template, url_for
app = Flask(__name__)

posts = [
    {
        'author': 'risqull',
        'title': 'blog post content',
        'content': 'testing'
    },
    {
        'author': 'random',
        'title': 'about',
        'content': 'tesss'
    }
]

@app.route('/')
def hello_world():
    return render_template('index.html', posts=posts)

@app.route('/about')
def aboutpage():
    return render_template('about.html', title='About')

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


from . import models
from django import forms
from django.forms.models import inlineformset_factory

class RecipeIngredientsForm(forms.ModelForm):

    class Meta:
        model = models.RecipeIngredients
        exclude = ()

RecipeIngredientsFormSet = inlineformset_factory(
    models.Recipe, models.RecipeIngredients, form=RecipeIngredientsForm,
    fields=['name', 'amount'], extra=1, can_delete=True)

class RecipeForm(forms.ModelForm):
    class Meta:
        model = models.Recipe
        fields = ['category', 'title', 'image', 'instructions', 'about']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if user is not None:
            self.fields['category'].queryset = (
                models.Category.objects.filter(
                    pk__in=user.category.values_list('category__pk')
                )
            )


import boto3
import pandas as pd
from sagemaker import get_execution_role

role = get_execution_role()

# Specify the S3 bucket
bucket_name = 'llminfo'

# Instantiate a s3 client
s3 = boto3.client('s3', region_name='us-west-2')

# List all the objects in the bucket
objects_in_bucket = s3.list_objects(Bucket=bucket_name)

# Suppose you have a CSV file you want to read into a pandas dataframe
file_to_read = 'FaCov_dataset (3).csv' # replace with your file name

# Check if the file exists in the bucket
if any(obj['Key'] == file_to_read for obj in objects_in_bucket['Contents']):

    # Get the file object
    file_obj = s3.get_object(Bucket=bucket_name, Key=file_to_read)

    # Read the file object into a pandas dataframe
    data = pd.read_csv(file_obj['Body'])
    # print(df.head())
    # print(df.columns)
    # print(df['content'][0])
    # print(df['raw_label'][0])
    # print(df.raw_label.unique())
    selected_values = ['mostly true', 'half true', 'true', 'partly true', 'Partly True']
    sub_df = data[data['raw_label'].isin(selected_values)]
    print(sub_df.head())
    length = len(sub_df)
    print("Length of the subdataframe:", length)
    print(sub_df.columns)
    print(sub_df['content'].tolist()[0])
    print('********')
    content_string = '\n'.join(sub_df['content'].astype(str))

print(content_string)


#!/usr/bin/env python

#run these in bash before script
#1. $srun --account=bgmp --partition=bgmp --nodes=1 --ntasks-per-node=1 --time=2:00:00 --cpus-per-task=1 --pty bash
#2. $dir="/projects/bgmp/shared/2017_sequencing"

import numpy as np
import bioinfo
import matplotlib.pyplot as plt
import gzip
import argparse

def get_args():
    parser = argparse.ArgumentParser(description = "client input program")
    parser.add_argument("-f", "--filename", help = "specify filename", type=str, required = True)
    parser.add_argument("-r", "--readlength", help = "specify readlength", type=int, required = True)
    parser.add_argument("-o", help = "specify outfile name", type=str, required = True)

    return parser.parse_args()

#make arg input name easier to type
clinput = get_args()
f = clinput.filename
r = clinput.readlength
o = clinput.o

#create a numpy array that we will fill with mean values
fa_array = np.zeros(r,dtype=np.int64) #should the end length by length of file? (wc -l)/4?

numrecord = 0
with gzip.open(f,"rt") as fh: #open file
        i = 0

        for line in fh: #iterate through input file
            i+=1
            line = line.strip('\n') #strip new line characters

            if i%4 == 0: #grab every 4th line (q score line)
                numrecord = int(i/4) -1
                if numrecord % 100000 == 0 :
                    print(f"Current Record Is {numrecord}")
                for c,s in enumerate(line): #populates list using c for counter and s for conver_phred. Lets us do two different calculations at the same spot
                    score = bioinfo.convert_phred(s)
                    # fa_array[c,l] = score
                    fa_array[c] += score

#create empty array and call it 'mean'
mean = np.zeros(r, dtype=float)

#populate array w/ np.mean function
# for i in range(r):
#     mean[i] = fa_array[i]/numrecord

# another way of coding the above
mean = fa_array/numrecord

#np.mean(fa_array[i])

plt.bar(range(r), mean)
plt.xlabel("Sequence Postition")
plt.ylabel("Mean Quality Score")
plt.title("Mean Quality Scores by Position for FastQ File")
plt.savefig(o+'.png')


#!/usr/bin/python3
nameList = list()
namesFile = open("names", "r")

# read until we close the file
while not namesFile.closed:
    aLine = namesFile.readline().rstrip()
    if aLine != "":
        nameList.append(aLine)
    else:
        namesFile.close()

# What did we get?
print(nameList)


import os
import sys
import time

from PySide2 import QtGui, QtWidgets
from PySide2.QtCore import QProcess

import FreeCAD
import FreeCADGui as Gui

import fcpdwb_locator as locator
from . import pdserver
from . import pdtools, pdcontrolertools, pdincludetools, pdrawtools, pdgeometrictools

TRY2EMBED = False

pdProcess = QProcess()
pdServer = pdserver.PureDataServer()

# register message handlers
pdtools.registerToolList(pdServer)
pdcontrolertools.registerToolList(pdServer)
pdincludetools.registerToolList(pdServer)
pdrawtools.registerToolList(pdServer)
pdgeometrictools.registerToolList(pdServer)

userPref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/FCPD")

def pdIsRunning():
    return pdProcess.state() != QProcess.NotRunning

def runPD():
    if not pdIsRunning():
        pdBin = userPref.GetString('pd_path')

        pdArgs = ['-path', os.path.join(locator.PD_PATH, 'pdlib'),
                  '-helppath', os.path.join(locator.PD_PATH, 'pdhelp')]

        if userPref.GetBool('fc_allowRaw', False):
            clientTemplate = "client_raw.pdtemplate"
            pdArgs += ['-path', os.path.join(locator.PD_PATH, 'pdautogen'),
                       '-helppath', os.path.join(locator.PD_PATH, 'pdautogenhelp')]
        else:
            clientTemplate = "client.pdtemplate"

        with open(os.path.join(locator.PD_PATH, clientTemplate), 'r') as f:
            clientContents = f.read()
        clientContents = clientContents.replace('%FCLISTEN%',
                                                str(userPref.GetInt('fc_listenport')))
        clientContents = clientContents.replace('%PDLISTEN%',
                                                str(userPref.GetInt('pd_defaultport')))

        clientFilePath = os.path.join(locator.PD_PATH, 'client.pd')
        with open(clientFilePath, 'w') as f:
            f.write(clientContents)

        pdProcess.startDetached(pdBin, pdArgs + ['-open', clientFilePath])
        if TRY2EMBED:
            time.sleep(1)
            embedPD()

def embedPD():
    '''
    Try to embed the pd window(s) in FreeCAD
    return True in success
    only implemented for PureData and PlugData on Linux platform
    '''
    if not sys.platform.startswith('linux'):
        return False

    exe = userPref.GetString('pd_path').lower()
    if 'plugdata' in exe:
        wName = ['"PlugData"']
    elif ('pd' in exe or 'puredata' in exe):
        wName = ['"Pd"', '"PatchWindow"']
    else:
        return False

    #if not pdIsRunning():
    #    #runPD()
    #    return False

    mw = Gui.getMainWindow()
    mdi = mw.findChild(QtWidgets.QMdiArea)
    isOk = False
    for w in wName:
        cl = f'xwininfo -root -tree | grep \'{w}\' | cut -f9 -d" "'
        print(cl)
        cliP = QProcess()
        cliP.start('bash', ['-c', cl])
        cliP.waitForReadyRead();
        winid, _ = cliP.readAllStandardOutput().toInt(16)
        print(winid)
        if winid:
            win = QtGui.QWindow.fromWinId(winid)
            widget = QtWidgets.QWidget(mdi)
            cont = QtWidgets.QWidget.createWindowContainer(win, widget)
            mdi.addSubWindow(cont)
            cont.show()
            isOk = True
    return isOk


"""aaa URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include, re_path

from news import views as news_views
from auto import views as auto_views
from garage import views as garage_views
from b1 import views as b1_views
from maps import views as maps_views

user_url = [
    path('', b1_views.home_def, name='home'),
    re_path(r'^register', b1_views.RegisterUser.as_view(), name='register'),
    path('login/', b1_views.LoginUser.as_view(), name='login'),
    path('logout/', b1_views.logout_user, name='logout'),
]

news_url = [
    path('post/<slug:slug>/', news_views.post_detail.as_view(), name='post'),
    path('category/<slug:slug>/', news_views.post_category.as_view(), name='post_category'),
    path('', news_views.post_list.as_view(), name='post_list'),
    path('create/', news_views.post_create.as_view(), name='post_create'),
]

garage_url = [
    path('<slug>/', garage_views.my_car.as_view(), name='mycar'),
    path('', garage_views.garage.as_view(), name='garage'),
]

auto_url = [
    re_path(r'^/(?P<slug>[-\w]+)/$', auto_views.car_detail.as_view(), name='cars'),
    re_path(r'^(?P<slug>[-\w]+)/$', auto_views.model_list.as_view(), name='brands'),
    re_path(r'^', auto_views.brand_list.as_view(), name='auto'),
]

map_url = [
    path('', maps_views.maps, name='map')
]

urlpatterns = [
    path('admin/', admin.site.urls),
    path('garage/', include(garage_url)),
    path('map/', include(map_url)),
    re_path(r'^', include(user_url)),
    path('news/', include(news_url)),
    path('auto/', include(auto_url)),
    path('newcar/', auto_views.car_create.as_view(), name='newcar'),
    path('captcha/', include('captcha.urls')),
    path('search/', b1_views.Search.as_view(), name='search'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import XMLFeedSpider
import json
import time
from filtering.items import FilteringItem

class HackNewsSpider(XMLFeedSpider):
    name = 'martinfowler'
    alias = 'martinfowler'
    group = '海外'

    start_urls = ['https://martinfowler.com/feed.atom']
    itertag = 'entry'

    def parse_node(self, response, selector):
        print('111111111111')
        item = FilteringItem()
        item['title'] = selector.css("title::text").extract_first()
        item['url'] = selector.css("link::href").get()
        t = time.mktime(
            time.strptime(selector.css("updated::text").extract_first(),
            "%Y-%m-%dT%H:%M:%S-04:00")
        )
        item['time'] = int(t)
        item['site'] = self.alias
        item['group'] = self.group
        print(item)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  9 16:28:39 2020

@author: Peter Meisrimel, Lund University
"""

import numpy as np

#############################################################
#  SDIRK 2, Time adaptive, single adaptive
#############################################################
## time grid is constructed during Dirichlet solve and same time grid is used for Neumann solver.
## Implementation not properly maintained, use on own risk
#############
# DEPRECATED
#############
def DNWR_SDIRK2_TA_single(self, tf, init_cond, maxiter = 100, TOL = 1e-8):
    print('this scheme is outdated and did not receive analogous updates')
    print('TOL = ', TOL)
    if self.WR_type != 'DNWR': raise ValueError('invalid solution method')
    u10, u20, ug0 = self.get_initial_values(init_cond) ## different for 1D and 2D

    tt_old = [0., tf]
    ug_WF_old = [np.copy(ug0), np.copy(ug0)] # waveform of ug, N grid
    ug_WF_new = [np.copy(ug0), np.copy(ug0)] # waveform of ug, N grid
    flux0 = np.zeros(ug0.shape) # zero flux irrelevant

    timesteps = 0
    TOL_FP, TOL_D = TOL, TOL/5 ## paper
    dt0 = self.get_dt0(tf, TOL_D, u10, which = 1)
    rel_tol_fac, updates = self.norm_interface(ug0), []
    if rel_tol_fac < 1e-6: rel_tol_fac = 1.
    self.r_old = TOL_D # for PI controller
    for k in range(maxiter):
        # Dirichlet time-integration
        t, u1 = 0., np.copy(u10) # init time-integration
        dt = dt0
        tt, tt_stage = [0.], [0.] # times for flux WF
        flux_WF_1, flux_WF_2 = [np.copy(flux0)], [np.copy(flux0)] # data for flux WF

        ug_WF_func = self.interpolation(tt_old, ug_WF_old) # interface values WF
        while t + dt < tf:
            u1, err1, flux1, flux2 = self.solve_dirichlet_SDIRK2(t, dt, u1, ug_WF_func)
            tt_stage.append(t + self.a*dt); flux_WF_1.append(flux1)
            t += dt
            tt.append(t); flux_WF_2.append(flux2)
            dt = self.get_new_dt_PI(dt, self.norm_inner(err1, 'D'), TOL_D)
            if dt < 1e-14: raise ValueError('too small timesteps, aborting')
        # final timestep
        dt = tf - t
        u1, _, flux1, flux2 = self.solve_dirichlet_SDIRK2(t, dt, u1, ug_WF_func)
        tt_stage.append(t + self.a*dt); flux_WF_1.append(flux1)
        tt.append(tf); flux_WF_2.append(flux2)

        # Neumann time-integration
        u2 = np.copy(u20)
        flux_WF_1_func = self.interpolation(tt_stage, flux_WF_1)
        flux_WF_2_func = self.interpolation(tt, flux_WF_2)
        ug_WF_new = [np.copy(ug0) for i in range(len(tt))]
        for i, t in enumerate(tt[:-1]):
            u2, ug_WF_new[i+1], _ = self.solve_neumann_SDIRK2(t, tt[i+1] - t, u2, ug_WF_new[i], flux_WF_1_func, flux_WF_2_func)

        # relaxation
        tmp = np.copy(ug_WF_old[-1]) # backup of old last value
        ug_WF_old = ug_WF_func(tt)# interpolate old data to new grid
        ## relaxation, calculate optimal theta
        theta = self.DNWR_theta_opt_TA(tt, tt)
        # new becomes old in next iteration
        ug_WF_old = [theta*ug_WF_new[i] + (1-theta)*ug_WF_old[i] for i in range(len(tt))]
        tt_old = tt

        # bookkeeping
        updates.append(self.norm_interface(ug_WF_old[-1] - tmp))
        timesteps += 2*len(tt) - 2
        print(k, updates[-1], len(tt) - 1)
        if updates[-1]/rel_tol_fac < TOL_FP: # STOPPING CRITERIA FOR FIXED POINT ITERATION
            break
    return u1, u2, ug_WF_old[-1], updates, k+1, timesteps

#############################################################
#  SDIRK 2, Time adaptive, double adaptive
#############################################################
## Does adaptivity on both the Dirichlet and Neumann solve
def DNWR_SDIRK2_TA_double(self, tf, init_cond, maxiter = 100, TOL = 1e-8):
    if self.WR_type != 'DNWR': raise ValueError('invalid solution method')
    print('TOL = ', TOL)
    TOL_FP, TOL_D, TOL_N = TOL, TOL/5, TOL/5 ## paper

    u10, u20, ug0 = self.get_initial_values(init_cond) ## different for 1D and 2D
    flux0 = np.zeros(ug0.shape) # placeholder only

    t1, t2_old = [0., tf], [0., tf] ## initial time grids
    ug_WF_old = [np.copy(ug0), np.copy(ug0)] # waveform of ug, N grid
    ug_WF_new = [np.copy(ug0), np.copy(ug0)] # waveform of ug, N grid

    ## intitial timesteps do not change
    dt0_D = self.get_dt0(tf, TOL_D, u10, which = 1)
    dt0_N = self.get_dt0(tf, TOL_N, u20, which = 2)

    timesteps = 0 # counter for total number of timesteps

    rel_tol_fac, updates = self.norm_interface(ug0), []
    if rel_tol_fac < 1e-6: rel_tol_fac = 1.
    for k in range(maxiter):
        # Dirichlet time-integration
        t, u1 = 0., np.copy(u10) # init time-integration
        dt = dt0_D ## initial timesteps
        t1, t1_stage = [0.], [0.] # time grids
        flux_WF_1, flux_WF_2 = [np.copy(flux0)], [np.copy(flux0)] # data for flux WF, placeholders

        self.r_old = TOL_D # for PI controller
        ug_WF_func = self.interpolation(t2_old, ug_WF_old) # interface values WF

        u1_list = [] # storage for initial flux computation
        ## adaptive time-integration loop, iterate while current timestep does not overstep tf
        while t + dt < tf:
            u1, err1, flux1, flux2 = self.solve_dirichlet_SDIRK2(t, dt, u1, ug_WF_func)
            t1_stage.append(t + self.a*dt); flux_WF_1.append(flux1) ## stage value
            t += dt
            t1.append(t); flux_WF_2.append(flux2) ## value on full timestep
            if len(u1_list) < 2: ## storage for initial flux computation, saves up to 2 values, and their timesteps
                u1_list.append((dt, np.copy(u1)))
            dt = self.get_new_dt_PI(dt, self.norm_inner(err1, 'D'), TOL_D) ## PI controller
            if dt < 1e-14: raise ValueError('too small timesteps, aborting') ## prevents too small timesteps
        # final timestep, truncate to hit tf
        dt = tf - t
        u1, _, flux1, flux2 = self.solve_dirichlet_SDIRK2(t, dt, u1, ug_WF_func)
        t1_stage.append(t + self.a*dt); flux_WF_1.append(flux1)
        t1.append(tf); flux_WF_2.append(flux2)
        if len(u1_list) < 2: ## storage for initial flux computation
            u1_list.append((dt, np.copy(u1)))
        if len(u1_list) == 1: ## only single timestep was done => 2 point difference
            u1dot = (-u10 + u1)/dt0_D
            ugdot = (-ug0 + ug_WF_func(dt0_D))/dt0_D
            flux0 = self.Mgg1.dot(ugdot) + self.Mg1.dot(u1dot) + self.Agg1.dot(ug0) + self.Ag1.dot(u10)
        elif len(u1_list) == 2: ## 3 point difference formula
            ## variable stepsize 3 point difference formular
            dtt1, dtt2 = u1_list[0][0], u1_list[1][0]
            c = dtt1/(dtt1 + dtt2)
            u1dot = (-u10*(1 - c**2) + u1_list[0][1] - u1_list[1][1]*c**2)/(dtt1*(1 - c))
            ugdot = (-ug0*(1 - c**2) + ug_WF_func(dtt1) - ug_WF_func(dtt1 + dtt2)*c**2)/(dtt1*(1 - c))
            flux0 = self.Mgg1.dot(ugdot) + self.Mg1.dot(u1dot) + self.Agg1.dot(ug0) + self.Ag1.dot(u10)
        else:
            raise ValueError('this is not supposed to happen, check code in detail')

        # Neumann time-integration
        t, u2, ug_old = 0., np.copy(u20), np.copy(ug0)
        dt = dt0_N

        flux_WF_1[0], flux_WF_2[0] = flux0, flux0 ## inserting initial flux here
        flux_WF_1_func = self.interpolation(t1_stage, flux_WF_1)
        flux_WF_2_func = self.interpolation(t1, flux_WF_2)

        self.r_old = TOL_D # for PI controller
        t2_new, ug_WF_new = [0.], [np.copy(ug0)]
        while t + dt < tf:
            u2, ug_new, err2 = self.solve_neumann_SDIRK2(t, dt, u2, ug_old, flux_WF_1_func, flux_WF_2_func)
            t += dt
            t2_new.append(t)
            ug_WF_new.append(np.copy(ug_new))
            ug_old = ug_new
            dt = self.get_new_dt_PI(dt, self.norm_inner(err2, 'N'), TOL_N)
            if dt < 1e-14: raise ValueError('too small timesteps, aborting')
        # final timestep
        dt = tf - t
        u2, ug_new, _ = self.solve_neumann_SDIRK2(t, dt, u2, ug_old, flux_WF_1_func, flux_WF_2_func)
        t2_new.append(tf)
        ug_WF_new.append(np.copy(ug_new))
        ## time-integration done

        # relaxation
        tmp = np.copy(ug_WF_old[-1]) # backup of old last value
        ug_WF_old = ug_WF_func(t2_new) # interpolate old data to new grid
        ## relaxation, calculate optimal theta
        theta = self.DNWR_theta_opt_TA(t1, t2_new)
        # new becomes old in next iteration
        ug_WF_old = [theta*ug_WF_new[i] + (1-theta)*ug_WF_old[i] for i in range(len(t2_new))]
        t2_old = t2_new

        # bookkeeping
        updates.append(self.norm_interface(ug_WF_old[-1] - tmp))
        timesteps += len(t2_new) + len(t1) - 2
        if updates[-1]/rel_tol_fac < TOL_FP: # STOPPING CRITERIA FOR FIXED POINT ITERATION
            print('converged', len(t1) - 1, len(t2_new) - 1)
            break
    return u1, u2, ug_WF_old[-1], updates, k+1, timesteps

if __name__ == '__main__':
    from FSI_verification import get_problem, get_solver, solve_monolithic
    from FSI_verification import get_parameters, get_init_cond
    from FSI_verification import visual_verification, verify_adaptive

    init_cond_1d = get_init_cond(1)
    init_cond_2d = get_init_cond(2)
    p_base = get_parameters('test') ## basic testing parameters
    save = 'verify/DNWR/TA/'

    for order in [-2]: # double adaptive
        p1 = {'init_cond': init_cond_1d, 'n': 50, 'dim': 1, 'order': order, 'WR_type': 'DNWR', **p_base}
        p2 = {'init_cond': init_cond_2d, 'n': 32, 'dim': 2, 'order': order, 'WR_type': 'DNWR', **p_base}

        verify_adaptive(k = 6, which_ref = 'fine', savefig = save, **p1) # 1D
        verify_adaptive(k = 5, which_ref = 'fine', savefig = save, **p2) # 2D

        for which in ['air_water', 'air_steel', 'water_steel']:
            pp = get_parameters(which)
            p1 = {'init_cond': init_cond_1d, 'n': 50, 'dim': 1, 'order': order, 'WR_type': 'DNWR', **pp, 'tf': 10000}
            p2 = {'init_cond': init_cond_2d, 'n': 32, 'dim': 2, 'order': order, 'WR_type': 'DNWR', **pp, 'tf': 10000}
            verify_adaptive(k = 7, savefig = save + which + '/' + which, which_ref = 'fine', **p1)
            verify_adaptive(k = 6, savefig = save + which + '/' + which, which_ref = 'fine', **p2)


from typing import List

"""
Problem Name: Insert Delete GetRandom O(1)

Problem URL: https://leetcode.com/explore/interview/card/top-interview-questions-medium/112/design/813/

Problem Section: Design, Set, Data Structures

Problem Statement:
Implement the RandomizedSet class:

    bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
    bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
    int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

Follow up: Could you implement the functions of the class with each function works in average O(1) time?

Constraints:
-231 <= val <= 231 - 1
At most 105 calls will be made to insert, remove, and getRandom.
There will be at least one element in the data structure when getRandom is called.

Resources:

runtime:
18 / 18 test cases passed.
	Status: Accepted
Runtime: 104 ms
Memory Usage: 18.5 MB

18 / 18 test cases passed.
	Status: Accepted
Runtime: 96 ms
Memory Usage: 18.4 MB
"""

# Solution techniques are use List with Dict

# Time complexity : O(1) Space complexity : O(n)

class RandomizedSet:

    def __init__(self):
        self.nums = []
        self.pos = {}

    def insert(self, val: int) -> bool:
        if val not in self.pos:
            self.nums.append(val)
            self.pos[val] = len(self.nums) - 1
            return True
        return False

    def remove(self, val: int) -> bool:
        if val in self.pos:
            idx = self.pos[val] # get val index in list
            last = self.nums[-1] # get the last addition
            self.nums[idx] = last # overwrite val index with last addition
            self.pos[last] = idx # update the last addition's index to it's new spot
            self.nums.pop() # get rid of the last addition from it's original spot
            del self.pos[val] # we don't need pop-or-default semantics here, del will work
            return True
        return False

    def getRandom(self) -> int:
        return random.choice(self.nums)

# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

LeetCode/Insert Delete GetRandom O(1).py


for c in range(int(input())):
    N = int(input())
    v = list(map(int, input().split()))

    a = 0
    prev = v[0]
    for i in range(1, len(v)):
        current = v[i]
        if prev > current:
            a += prev - current
        prev = current

    max_rate = 0
    prev = v[0]
    for i in range(1, len(v)):
        current = v[i]
        rate = max(prev - current, 0)
        max_rate = max(rate, max_rate)
        prev = current

        #print(max_rate)
    b = 0
    for i in range(len(v)-1):
        current = v[i]
        if current - max_rate <= 0:
            b += current
        else:
            b += max_rate

    print("Case #{}: {} {}".format(c+1, a, b))


import numpy as np
class LinearRegression:
    def __init__(self,lr,num_iter,batch_size):

        self.lr=lr
        self.num_iter=num_iter
        self.batch_size=batch_size
        #self.ep=ep

    def generate_data(self,mu,sd,N):

        X1 = np.random.normal(loc=mu,scale=sd, size=N)
        X1 = np.array(X1)
        return X1

    def h(self,X,theta,b):
        y_pred= np.dot(X.T,theta)+b

        return y_pred

    def cost(self,theta,b,X,y):
        m = X.shape[1]

        h=self.h(X,theta,b)

        J = (1/(2*m))*np.sum(np.square(h-y))

        return J

    def initialize_and_vectorize(self,x1,x2):
        X=np.zeros((2,1000000))
        X[0,:]=x1
        X[1,:]=x2

        theta=np.zeros((2,1))
        b=1

        return (X,theta,b)

    def Normalize(self,X):
        X = (X - np.min(X))/(np.max(X)-np.min(X))
        return X

    def grad(self,theta,b,X,y):
        m=X.shape[1]
        dJ_theta = [0]*3
        y_pred=self.h(X,theta,b)
        #print("grad",y.shape)
        #print("x",X.shape)
        db = (1/m) * np.sum(y_pred-y)

        dtheta = (1/m) *(np.dot(X,(y_pred-y)))

        return (dtheta,db)

    def check_(self):
        print("working")
    def train(self,X,y,theta,b,theta_prev,b_prev):
        loss=[]
        t0=[]
        t1=[]
        t2=[]

        jj=0
        print(theta)
        pre_loss=0
        tt1_p=0
        tt2_p=0
        tt0_p=0
        for i in range (self.num_iter):

            batch_per_epoch=int(X.shape[1] / self.batch_size)
            XX = np.zeros((2,self.batch_size))
            #print(batch_per_epoch)
            shuffle_index = np.random.permutation(X.shape[1])

            for step in range(batch_per_epoch):

                theta_prev=theta
                b_prev=b

                batch_x1 = X[0,shuffle_index[step*self.batch_size:(step+1)*self.batch_size]]
                batch_x2= X[1,shuffle_index[step*self.batch_size:(step+1)*self.batch_size]]
                XX[0,:]=batch_x1

                XX[1,:]=batch_x2
                batch_y = y[shuffle_index[step*self.batch_size:(step+1)*self.batch_size]]

                J=self.cost(theta,b,XX,batch_y)
                #print("loss=",J)
                loss.append(J)

                dJ_theta,db=self.grad(theta,b,XX,batch_y)

                theta0 = b_prev - self.lr*db
                theta1 = theta_prev - self.lr*dJ_theta
                theta=theta1
                b=theta0

                t0.append(theta0)
                t1.append(theta1)

            loss_ = self.cost(theta,b,X,y)

            if(i and X.shape[1]!=1000000):
                print("Loss after {} epoch = {} and pamameters= {} {}" .format(i,J,theta,b))
            if(i%100==0 and X.shape[1]==1000000):
                print("Loss after {} epoch = {} and pamameters= {} {}" .format(i,J,theta,b))
            #COnvergence Criteria

            if abs(loss_-pre_loss) < 0.01 and X.shape[1]!=1000000:
                print("convergence criteria met at {} epoch ...STOP training".format(i))
                break

            pre_loss=loss_
            if abs(float(dJ_theta[0]))<0.001 and abs(float(dJ_theta[1]))<0.001 and abs(float(db))<0.001 and X.shape[1]!=1000000 :
                print("convergence criteria met at {} epoch ...STOP training1".format(i))
                break
            tt0_p=b
            tt1_p=theta[0]
            tt2_p=theta[1]

        return(loss,t0,t1)


import sys
from collections import defaultdict
data = [[i.strip() for i in line.split("-")] for line in sys.stdin]
paths = defaultdict(lambda: set())
uniq_paths = set()
for a, b in data:
    paths[a].add(b)
    paths[b].add(a)

def dfs(seen, node):
    count = 0
    if node == "end":
        return 1
    if node in seen:
        return 0
    if node.islower():
        seen.add(node)
    for n in paths[node]:
        count += dfs(seen.copy(), n)
    return count

def dfs2(seen, node, twice, path):
    path.append(node)
    if node == "end":
        uniq_paths.add(",".join(path))
        return 1
    if node in seen:
        return 0
    if node.islower():
        seen.add(node)
    for n in paths[node]:
        dfs2(seen.copy(), n, twice, path.copy())
        if not twice and node != "start" and node.islower():
            seen2 = seen.copy()
            seen2.remove(node)
            dfs2(seen2.copy(), n, True, path.copy())
    return

if __name__ == "__main__":
    print(dfs(set(), "start"))
    dfs2(set(), "start", False, list())
    print(len(uniq_paths))


from pytube import YouTube
from playsound import playsound
import tkinter as tk

window_width = 500
window_height = 150
window_title = "YouTube Downloader"
button_click = "clicks.m4a"

class YouTubeDownloader:
    def __init__(self):
        self.window = tk.Tk()
        self.window.geometry("{}x{}".format(window_width, window_height))
        self.window.configure(bg="#a8323a")
        self.window.title(window_title)

        #creation of lables
        self.link_lable = tk.Label(self.window, text = "Download Link")
        self.link_lable.grid(column= 0, row=0)
        self.name_lable = tk.Label(self.window, text= "Save File As")
        self.name_lable.grid(column = 0, row= 1)
        self.path_lable = tk.Label(self.window, text = "Save File Path")
        self.path_lable.grid(column = 0, row = 2)
        self.extension_lable = tk.Label(self.window, text = "File Extension")
        self.extension_lable.grid(column = 0, row = 3)

        #creation of entry
        self.link_entry = tk.Entry(master=self.window, width = 50)
        self.link_entry.grid(column = 1 , row = 0)
        self.name_entry = tk.Entry(master=self.window, width = 50)
        self.name_entry.grid(column =1, row= 1)
        self.path_entry = tk.Entry(master= self.window, width = 50)
        self.path_entry.grid(column = 1, row=2)
        self.extension_entry = tk.Entry(master=self.window, width = 50)
        self.extension_entry.grid(column = 1, row=3)

        #creation of button
        self.download_button = tk.Button(self.window, text = "Download", command = self.__getLink)
        self.download_button.grid(column= 1, row = 4)

        return

    def __downloader(self, link, save_path = "", save_name = "", extension ="1080p"):
        yt = YouTube(link)
        yt_stream  = yt.streams.filter(progressive=True, file_extension = extension).order_by("resolution").desc().first()
        yt_stream.download(output_path = save_path, filename = save_name)

        return

    def __getLink(self):
        #playsound(button_click)
        link = self.link_entry.get()
        name = self.name_entry.get()
        path = self.path_entry.get()
        extension = self.extension_entry.get()

        self.__downloader(link, path, name, extension)

        return

    def run_app(self):
        self.window.mainloop()
        return

if __name__ == "__main__":
    app = YouTubeDownloader()
    app.run_app()


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from day.models import Day
from .models import Student

class GetDayAttendencesView(APIView):
    permission_classes = (permissions.AllowAny, )

    def get(self, request, daySlug, format=None):
        try:
            day_slug = daySlug
        except:
            return Response(
                {'error': 'Day ID must be an integer'},
                status=status.HTTP_404_NOT_FOUND
            )

        try:
            if not Day.objects.filter(slug=day_slug).exists():
                return Response(
                    {'error': 'This day does not exist'},
                    status=status.HTTP_404_NOT_FOUND
                )

            day = Day.objects.get(slug=day_slug)

            results = []

            if Student.objects.filter(day=day).exists():
                students = Student.objects.order_by(
                    '-date_created'
                ).filter(day=day)

                for student in students:
                    item = {}

                    item['id'] = student.id
                    item['comment'] = student.comment
                    item['date_created'] = student.date_created
                    item['user'] = student.user.username
                    item['is_present'] = student.is_present

                    results.append(item)

            return Response(
                {'students': results},
                status=status.HTTP_200_OK
            )
        except:
            return Response(
                {'error': 'Something went wrong when retrieving comments'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class GetDayAttendenceView(APIView):
    def get(self, request, daySlug, format=None):
        user = self.request.user

        try:
            day_slug = daySlug
        except:
            return Response(
                {'error': 'day ID must be an integer'},
                status=status.HTTP_404_NOT_FOUND
            )

        try:
            if not Day.objects.filter(slug=day_slug).exists():
                return Response(
                    {'error': 'This day does not exist'},
                    status=status.HTTP_404_NOT_FOUND
                )

            day = Day.objects.get(slug=day_slug)

            result = {}

            if Student.objects.filter(user=user, day=day).exists():
                student = Student.objects.get(user=user, day=day)

                result['id'] = student.id
                result['comment'] = student.comment
                result['date_created'] = student.date_created
                result['user'] = student.user.username
                result['is_present'] = student.is_present

            return Response(
                {'student': result},
                status=status.HTTP_200_OK
            )
        except:
            return Response(
                {'error': 'Something went wrong when retrieving comment'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class CreateAttendenceView(APIView):
    def post(self, request, daySlug, format=None):
        user = self.request.user
        data = self.request.data

        try:
            day_slug = daySlug
        except:
            return Response(
                {'error': 'day ID must be an integer'},
                status=status.HTTP_404_NOT_FOUND
            )

        try:
            comment = str(data['comment'])
        except:
            return Response(
                {'error': 'Must pass a comment when creating comment'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            if not Day.objects.filter(slug=day_slug).exists():
                return Response(
                    {'error': 'This  does not exist'},
                    status=status.HTTP_404_NOT_FOUND
                )

            day = Day.objects.get(slug=day_slug)

            result = {}
            results = []

            # if Student.objects.filter(user=user, day=day).exists():
            #     return Response(
            #         {'error': 'day for this  already created'},
            #         status=status.HTTP_409_CONFLICT
            #     )

            student = Student.objects.create(
                user=user,
                day=day,
                comment=comment,
                is_present=False
            )

            if Student.objects.filter(user=user, day=day).exists():
                result['id'] = comment.id
                result['comment'] = comment.comment
                result['date_created'] = comment.date_created
                result['user'] = comment.user.first_name
                result['is_present'] = comment.is_present

                students = Student.objects.order_by('-date_created').filter(
                    day=day
                )

                for student in students:
                    item = {}

                    item['id'] = student.id
                    item['comment'] = student.comment
                    item['date_created'] = student.date_created
                    item['user'] = student.user.username

                    results.append(item)

            return Response(
                {'student': result, 'students': results},
                status=status.HTTP_201_CREATED
            )
        except:
            return Response(
                {'error': 'Something went wrong when creating comment'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


import ast
import types

import stypy_functions_copy
import functions_copy
import core_language_copy

"""
Code that deals with various code idioms that can be optimized to better obtain the types of the variables used
on these idioms. The work with this file is unfinished, as not all the intended idioms are supported.

TODO: Finish this and its comments when idioms are fully implemented
"""

# Idiom constant names:

# Idiom identified, var of the type call, type
default_ret_tuple = False, None, None

may_be_type_func_name = "may_be_type"
may_not_be_type_func_name = "may_not_be_type"
may_be_var_name = "__may_be"
more_types_var_name = "__more_types_in_union"

def __has_call_to_type_builtin(test):
    if type(test) is ast.Call:
        if type(test.func) is ast.Name:
            if len(test.args) != 1:
                return False
            if test.func.id == "type":
                return True
    else:
        if hasattr(test, "left"):
            if type(test.left) is ast.Call:
                if len(test.comparators) != 1:
                    return False
                if type(test.left.func) is ast.Name:
                    if len(test.left.args) != 1:
                        return False
                    if test.left.func.id == "type":
                        return True
    return False

def __has_call_to_is(test):
    if len(test.ops) == 1:
        if type(test.ops[0]) is ast.Is:
            return True
    return False

def __is_type_name(test):
    if type(test) is ast.Name:
        name_id = test.id
        try:
            type_obj = eval(name_id)
            return type(type_obj) is types.TypeType
        except:
            return False
    return False

def type_is_idiom(test, visitor, context):
    """
    Idiom "type is"
    :param test:
    :param visitor:
    :param context:
    :return:
    """
    if type(test) is not ast.Compare:
        return default_ret_tuple

    if __has_call_to_type_builtin(test) and __has_call_to_is(test):
        if not (__has_call_to_type_builtin(test.comparators[0]) or __is_type_name(test.comparators[0])):
            return default_ret_tuple
        type_param = visitor.visit(test.left.args[0], context)
        if __is_type_name(test.comparators[0]):
            is_operator = visitor.visit(test.comparators[0], context)
        else:
            is_operator = visitor.visit(test.comparators[0].args[0], context)
            if not isinstance(is_operator[0], list):
                is_operator = ([is_operator[0]], is_operator[1])

        return True, type_param, is_operator

    return default_ret_tuple

def not_type_is_idiom(test, visitor, context):
    """
    Idiom "not type is"

    :param test:
    :param visitor:
    :param context:
    :return:
    """
    if type(test) is not ast.UnaryOp:
        return default_ret_tuple
    if type(test.op) is not ast.Not:
        return default_ret_tuple

    return type_is_idiom(test.operand, visitor, context)

def __get_idiom_type_param(test):
    return test.left.args[0]

def __set_type_implementation(if_test, type_, lineno, col_offset):
    param = __get_idiom_type_param(if_test)
    if type(param) is ast.Name:
        return stypy_functions_copy.create_set_type_of(param.id, type_, lineno, col_offset)
    if type(param) is ast.Attribute:
        obj_type, obj_var = stypy_functions_copy.create_get_type_of(param.value.id, lineno, col_offset)
        set_member = stypy_functions_copy.create_set_type_of_member(obj_var, param.attr, type_, lineno, col_offset)
        return stypy_functions_copy.flatten_lists(obj_type, set_member)

    return []

def __remove_type_from_union_implementation(if_test, type_, lineno, col_offset):
    param = __get_idiom_type_param(if_test)
    if type(param) is ast.Name:
        obj_type, obj_var = stypy_functions_copy.create_get_type_of(param.id, lineno, col_offset)
        remove_type_call = functions_copy.create_call(core_language_copy.create_Name("remove_type_from_union"),
                                                 [obj_var, type_], line=lineno, column=col_offset)
        set_type = stypy_functions_copy.create_set_type_of(param.id, remove_type_call, lineno, col_offset)

        return stypy_functions_copy.flatten_lists(obj_type, set_type)
    if type(param) is ast.Attribute:
        # Get the owner of the attribute
        obj_type_stmts, obj_var = stypy_functions_copy.create_get_type_of(param.value.id, lineno, col_offset)
        # Get the current type of the owner of the attribute
        att_type_stmts, att_var = stypy_functions_copy.create_get_type_of_member(obj_var, param.attr, lineno, col_offset)
        remove_type_call = functions_copy.create_call(core_language_copy.create_Name("remove_type_from_union"),
                                                 [att_var, type_], line=lineno, column=col_offset)
        set_member = stypy_functions_copy.create_set_type_of_member(obj_var, param.attr, remove_type_call, lineno,
                                                               col_offset)
        return stypy_functions_copy.flatten_lists(obj_type_stmts, att_type_stmts, set_member)

    return []

def set_type_of_idiom_var(idiom_name, if_branch, if_test, type_, lineno, col_offset):
    if idiom_name == "type_is":
        if if_branch == "if":
            return __set_type_implementation(if_test, type_, lineno, col_offset)
        if if_branch == "else":
            return __remove_type_from_union_implementation(if_test, type_, lineno, col_offset)

    if idiom_name == "not_type_is":
        if_test = if_test.operand
        if if_branch == "if":
            return __remove_type_from_union_implementation(if_test, type_, lineno, col_offset)
        if if_branch == "else":
            return __set_type_implementation(if_test, type_, lineno, col_offset)

    return []

# Recognized idioms
recognized_idioms = {
    "type_is": type_is_idiom,
    "not_type_is": not_type_is_idiom,
}

# Implementation of recognized idioms
recognized_idioms_functions = {
    "type_is": may_be_type_func_name,
    "not_type_is": may_not_be_type_func_name,
}

def get_recognized_idiom_function(idiom_name):
    """
    Gets the function that process an idiom once it has been recognized
    :param idiom_name: Idiom name
    :return:
    """
    return recognized_idioms_functions[idiom_name]

def is_recognized_idiom(test, visitor, context):
    """
    Check if the passed test can be considered an idioms

    :param test: Source code test
    :param visitor: Type inference visitor, to change generated instructions
    :param context: Context passed to the call
    :return: Tuple of values that identify if an idiom has been recognized and calculated data if it is been recognized
    """
    for idiom in recognized_idioms:
        result = recognized_idioms[idiom](test, visitor, context)
        if result[0]:
            temp_list = list(result)
            temp_list.append(idiom)
            return tuple(temp_list)

    return False, None, None, None


import json
# reading the data from the file
with open('questions.txt') as f:
    #data = f.read()
    questionList = json.load(f)

for x in questionList:
    for soc in x['discussion']:
        print(soc)

print(len(questionList))
from win32api import GetMonitorInfo, MonitorFromPoint

monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
work_area = monitor_info.get("Work")
print("The work area size is {}x{}.".format(work_area[2], work_area[3]))


from random import choice
from copy import deepcopy
from time import time

class Board:

    def __init__(self):
        self.white = {(4, 5), (5, 4)}
        self.black = {(4, 4), (5, 5)}
        ls = [
               [1000, -50, 100, 100, 100, 100,  -50, 1000],
               [-50, -200,   1,   1,   1,   1, -200,  -50],
               [100,    1,   1,   1,   1,   1,    1,  100],
               [100,    1,   1,   0,   0,   1,    1,  100],
               [100,    1,   1,   0,   0,   1,    1,  100],
               [100,    1,   1,   1,   1,   1,    1,  100],
               [-50, -200,   1,   1,   1,   1, -200,  -50],
               [1000, -50, 100, 100, 100, 100,  -50, 1000]
             ]
        self.available = {(6, 3), (6, 4), (6, 5), (6, 6), (5, 6), (4, 6), (3, 6), (3, 5), (3, 4), (3, 3), (4, 3), (5, 3)}
        self.weigths = {(i + 1, j + 1) : ls[i][j] for i in range(8) for j in range(8)}

    def around(self, x, y): # zwraca listę pól dookoła (x, y); uważa, żeby nie wyjechać poza planszę
        tmp = {(x + 1, y - 1), (x + 1, y), (x + 1, y + 1), (x, y + 1), (x, y - 1), (x - 1, y - 1), (x - 1, y), (x - 1, y + 1)}
        return set(filter(lambda x : 0 < x[0] < 9 and 0 < x[1] < 9, tmp))

    def canBeat(self, x, y, player): # zwraca True jeśli gracz player ma bicie stawiając pionek na polu(x, y); wpp False
        myDisks = self.black if player == 1 else self.white
        oppDisks = self.white if player == 1 else self.black
        neighOppDisks = self.around(x, y) & oppDisks
        for (a, b) in neighOppDisks:
            du, dv = a - x, b - y
            u, v = x, y
            steps = 0
            while (u + du, v + dv) in oppDisks:
                steps += 1
                u += du
                v += dv
            if steps > 0 and (u + du, v + dv) in myDisks:
                return True
        return False

    def correctCorner(self, x, y, justAdded):
        if (x, y) not in {(1, 1), (8, 8), (1, 8), (8, 1)}:
            return
        if justAdded:
            for (u, v) in self.around(x, y):
                self.weigths[(u, v)] = 20 if abs(u - x) == 1 and abs(v - y) == 1 else 200
        else:
            for(u, v) in self.around(x, y):
                self.weigths[(u, v)] = -200 if abs(u - x) == 1 and abs(v - y) == 1 else -50

    def move(self, x, y, player): # wykonuje ruch gracza player stawiając pionek na polu (x, y)
        myDisks = self.black if player == 1 else self.white
        oppDisks = self.white if player == 1 else self.black
        direction = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)]
        myDisks.add((x, y))
        self.correctCorner(x, y, True)
        self.available.remove((x, y))
        newAvailable = self.around(x, y) - (self.white | self.black | self.available)
        self.available |= newAvailable
        beaten = set()
        for (du, dv) in direction:
            u, v = x, y
            tmp = set()
            while (u + du, v + dv) in oppDisks:
                u += du
                v += dv
                tmp.add((u, v))
            if (u + du, v + dv) in myDisks:
                beaten |= tmp
        myDisks |= beaten
        oppDisks -= beaten
        return beaten, newAvailable

    def randomMove(self, player): # wykonuje losowy ruch gracza player
        possible = [(x, y) for (x, y) in self.available if self.canBeat(x, y, player)]
        if possible == []:
            self.noMoves += 1
            return
        (x, y) = choice(possible)
        self.move(x, y, player)
        self.noMoves = 0

    def heura(self):
        tmp1 = sum(self.weigths[p] for p in self.black)
        tmp2 = sum(self.weigths[p] for p in self.white)
        return tmp1 - tmp2

    def minn(self, depth, alpha, beta):
        if depth == 1:
            return self.heura(), (9, 9)
        value = 1000000000000
        bestPos = (-1, -1)
        possible = [(x, y) for (x, y) in self.available if self.canBeat(x, y, -1)]
        if possible == []:
            return self.maxx(depth - 1, alpha, beta)
        for (x, y) in possible:
            beaten, newAvailable = self.move(x, y, -1) #  wykonujemy ruch na pozycję (x, y)
            tmpVal, _ = self.maxx(depth - 1, alpha, beta)
            if tmpVal <= value: # sprawdzamy czu poprawiamy value
                value = tmpVal
                bestPos = (x, y)
            self.available -= newAvailable
            self.available.add((x, y))
            self.white.remove((x, y))
            self.white -= beaten
            self.black |= beaten
            self.correctCorner(x, y, False)
            if value <= alpha: # jeśli value jest gorsze od alpha to odcinamy
                return value, bestPos
            beta = min(value, beta)
        return value, bestPos

    def maxx(self, depth, alpha, beta):
        if depth == 1:
            return self.heura(), (9, 9)
        value = -1000000000000
        bestPos = (-1, -1)
        possible = [(x, y) for (x, y) in self.available if self.canBeat(x, y, 1)]
        if possible == []:
            return self.minn(depth - 1, alpha, beta)
        for (x, y) in possible:
            beaten, newAvailable = self.move(x, y, 1) # wykonujemy ruch na pozycję (x, y)
            tmpVal, _ = self.minn(depth - 1, alpha, beta)
            if tmpVal >= value: # sprawdzamy czu poprawiamy value
                value = tmpVal
                bestPos = (x, y)
            self.available -= newAvailable
            self.available.add((x, y))
            self.black.remove((x, y))
            self.black -= beaten
            self.white |= beaten
            self.correctCorner(x, y, False)
            if value >= beta:
                return value, bestPos # jeśli value jest gorsze od alpha to odcinamy
            alpha = max(alpha, value)
        return value, bestPos

    def agentMove(self, player):
        _, bestPosition = self.maxx(4, -1000000000000, 1000000000000) if player == 1 else self.minn(4, -1000000000000, 1000000000000)
        if bestPosition == (-1, -1)  or bestPosition == (9, 9):
            self.noMoves += 1
            return
        (i, j) = bestPosition
        self.move(i, j, player)
        self.noMoves = 0

    def game(self, startingPlayer):
        self.noMoves = 0
        player = 1
        while self.black and self.white and len(self.white) + len(self.black) != 64:
            if self.noMoves == 2:
                break
            if player == startingPlayer:
                self.agentMove(player)
            else:
                self.randomMove(player)
            player *= -1
        return len(self.black) - len(self.white)

def match():
    start = time()
    wins = 0
    losses = 0
    draws = 0
    for i in range(1000): # should be 1000
        startingPlayer = 1 if i%2 == 0 else -1
        newGame = Board()
        # print("Game", i)
        res = newGame.game(startingPlayer) # 1 is agent, -1 is randomAgent
        if res*startingPlayer > 0:
            wins += 1
        elif res*startingPlayer < 0:
            losses += 1
        else:
            draws += 1
    print('Wins: ', wins)
    print('Losses: ', losses)
    print('Draws: ', draws)
    end = time()
    print('Time elapsed: ', end - start)

match()


#!/usr/bin/env python

import matplotlib.pyplot as plt
import rospy
from geometry_msgs.msg import PoseArray
from matplotlib.animation import FuncAnimation
from nav_msgs.msg import Odometry

# Dynamic trajectory visualizer
class Visualizer:
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.real_ln, self.ln = plt.plot([], [], 'b', [], [], 'r')
        self.ln.set_label('real')
        self.real_ln.set_label('reference')
        self.ax.legend()
        self.x_data, self.y_data = [], []
        self.real_x, self.real_y = [], []

    def plot_init(self):
        self.ax.set_xlim(0, 6)
        self.ax.set_ylim(0, 3)
        return self.real_ln, self.ln

    def set_trajectory(self, msg):
        self.real_x = [p.position.x for p in msg.poses]
        self.real_y = [p.position.y for p in msg.poses]

    def odom_callback(self, msg):
        self.x_data.append(msg.pose.pose.position.x + 1)
        self.y_data.append(msg.pose.pose.position.y + 1)

    def update_plot(self, frame):
        self.real_ln.set_data(self.real_x, self.real_y)
        self.ln.set_data(self.x_data, self.y_data)
        return self.real_ln, self.ln

# Plot trajectory in real time
if __name__ == '__main__':
    rospy.init_node('plot_trajectory')
    vis = Visualizer()
    path_sub = rospy.Subscriber('/trajectory', PoseArray, vis.set_trajectory)
    ani = FuncAnimation(vis.fig, vis.update_plot, init_func=vis.plot_init, blit=True)
    rospy.sleep(3)
    odom_sub = rospy.Subscriber('/odom', Odometry, vis.odom_callback)
    plt.show(block=True)


#GET VALUE TYPE (CHECKERS)

from operator import ge

def get_int():
    while True:
        try:
            x = int(input("Enter a number: "))
            return x
        except ValueError:
            print("Please Enter a number.")
            continue

def get_flaot():
    while True:
        try:
            x = float(input("Enter a number: "))
            return x
        except ValueError:
            print("Please Enter a number.")
            continue

def get_str():
    while True:
        try:
            x = input("Enter text: ")
            return x
        except ValueError:
            print("Please enter words.")
            continue

#CLEAR SCREEN
def clear():
    import os
    os.system("cls" if os.name == 'nt' else "clear")

num1 = get_int()
f1= get_flaot()
st= get_str()


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  8 10:04:10 2016

@author: zhuchunwu
"""

import requests

def getliofP():
    apiurl='http://tpv.daxiangdaili.com/ip/?tid=557576382820459&num=20&filter=on'
    api =requests.get(apiurl)
    api = str(api.text)
    lis1 = api.splitlines()
    return(lis1)

def checkP(lis1):
    checklis = []
    checkurl = 'http://whois.ipcn.org/'
    for i in lis1:
        proxies = {'http':'http://%s' %i}
        try:
            requests.get(checkurl,proxies = proxies)
            checklis.append(proxies)
            print(proxies)
        except Exception:
            print(i)
            pass
#        print(proxies)
    print(checklis)

lis1 = getliofP()
checkP(lis1)


import numpy as np
import cv2 as cv2
import sys

from frame_selector import Frame_selector

frame1 = cv2.imread('frame_1.png')
frame2 = cv2.imread('frame_2.png')

def find_move(frame1, frame2):
    '''find the movement of frame2 w.r.t. frame1'''
    h, w = frame1.shape[:2]
    dist = min(w,h) // 5
    cropped = frame2[h//2-dist:h//2+dist, w//2-dist:w//2+dist]

    frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
    cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)

    h, w = frame1.shape[:2]
    x_move, y_move = 0, 0
    curr_dif = sys.maxsize

    for x in range(-dist, dist):
        for y in range(-dist, +dist):

            # compare the cropped section with a part in original image
            diff= np.abs(
                cropped - frame1[h//2+x-dist:h//2+x+dist, w//2+y-dist:w//2+y+dist]).sum()

            if diff < curr_dif:
                print(diff, 'x=', x, 'y=', y)
                curr_dif = diff
                x_move, y_move = x, y
                # x,y is the point in frame1 that corres to the mid of img2
                # (on the right of the center in frame1)

    print(x_move, y_move)
    return x_move, y_move

def _find_xy(frame1, crop2, d0:int, x0:int, y0:int, step:int):
    print('new recursion d0----------: ', d0)

    if step <= 2:
        return x0, y0

    else:
        curr_dif = sys.maxsize
        for x in range(x0-step, x0+step, step//3):

            for y in range(y0-step, y0+step, step//3):

                print([x0-d0+x-(x0+d0+x), y0-d0+y-(y0+d0+y)])

                crop1 = frame1[x0-d0+x:x0+d0+x, y0-d0+y:y0+d0+y]
                # crop1 = frame1[:2*d0, :2*d0]
                print('shape1: ',crop1.shape)
                print('shape2: ',crop2.shape)

                # compare the crop1 section with a part in original image
                diff = np.abs(crop1 - crop2).sum()

                if diff < curr_dif:
                    print('find smaller ----------')
                    print(diff, 'x=', x, 'y=', y)
                    curr_dif = diff
                    x_move, y_move = x, y

        _find_xy(frame1, crop2, d0, x0+x_move, y0+y_move, step//3)

def find_move1(frame1, frame2):
    '''find the movement of frame2 w.r.t. frame1'''
    h, w = frame1.shape[:2]
    d0 = min(w,h) // 5
    crop2 = frame2[h//2-d0:h//2+d0, w//2-d0:w//2+d0]

    frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
    crop2 = cv2.cvtColor(crop2, cv2.COLOR_BGR2GRAY)

    h, w = frame1.shape[:2]
    x_move, y_move = 0, 0

    x_move, y_move = _find_xy(frame1, crop2, d0, x0=h//2, y0=w//2, step=d0) # recursive

    return x_move, y_move

xm, ym = find_move(frame1, frame2)
# find_move1(frame1, frame2)


import sys
sys.stdin = open("p3.txt")

wayx = [0, 0, 1, -1, 1, 1, -1, -1]
wayy = [1, -1, 0, 0, 1, -1, 1, -1]

def dfs(x, y):
    visited[x][y] = 1
    for z in range(8):
        if nxn[x+wayx[z]][y+wayy[z]] > 1 and visited[x+wayx[z]][y+wayy[z]] == 0:
            dfs(x+wayx[z], y+wayy[z])

def count(x, y):
    global cnt
    for z in range(8):
        if visited[x+wayx[z]][y+wayy[z]] == 1:
            return cnt
    cnt += 1
    return cnt

T = int(input())
if 1 <= T <= 10:
    for tc in range(1, T+1):
        N = int(input())

        arr = [list(map(int, input().split())) for _ in range(N)]
        nxn = [[0 for _ in range(N + 2)] for _ in range(N + 2)]
        visited = [[0 for _ in range(N + 2)] for _ in range(N + 2)]
        ans = []

        for i in range(1, N+1):
            for j in range(1, N+1):
                nxn[i][j] = arr[i-1][j-1]
        cnt = 0

        for i in range(1, N+1):
            for j in range(1, N+1):
                if nxn[i][j] >= 1 and visited[i][j] == 0:
                    dfs(i, j)
        c = 0

        for i in range(1, N+1):
            for j in range(1, N+1):
                if visited[i][j] == 1:
                    count(i, j)

        print('#{} {}'.format(tc, cnt))


import numpy as np

class DayEight:

    def __init__(self, input_path):
        self.input_path = input_path

    def get_visible_trees_by_row(self, tree_heights):

        tree_heights_list = tree_heights.tolist()[0]

        # create list to track visibility (1 = visible)
        scenic_scores = [0] * len(tree_heights_list)

        tallest_tree_height = max(tree_heights_list)
        current_max = -1
        index = 0

        # check visibility from one direction
        while current_max < tallest_tree_height:
            if current_max < tree_heights_list[index]:
                scenic_scores[index] = 1
                current_max = tree_heights_list[index]

            index += 1

        # check visibility from opposite direction
        current_max = -1
        index = len(tree_heights_list) -1

        while current_max < tallest_tree_height:
            if current_max < tree_heights_list[index]:
                scenic_scores[index] = 1
                current_max = tree_heights_list[index]

            index -= 1

        return scenic_scores

    def get_visible_tree_count(self, tree_heights_grid):

        if tree_heights_grid.shape[0] == 0:
            return 0
        elif tree_heights_grid.shape[0] < 3:
            return tree_heights_grid.shape[0] * tree_heights_grid.shape[1]

        tree_visibility_grid_by_row = np.apply_along_axis(self.get_visible_trees_by_row, axis=1, arr=tree_heights_grid)
        tree_visibility_grid_by_column = np.apply_along_axis(self.get_visible_trees_by_row, axis=0, arr=tree_heights_grid)

        # use logical_or to get total visibility
        tree_visibility_grid = np.logical_or(tree_visibility_grid_by_row, tree_visibility_grid_by_column).astype(int)

        return np.sum(tree_visibility_grid)

    def get_scenic_score_by_row(self, tree_heights):

        tree_heights_list = tree_heights.tolist()[0]
        tree_heights_length = len(tree_heights_list)

        # create list to track scenic scores
        scenic_scores = [0] * tree_heights_length

        for tree_house_index in range(tree_heights_length):

            viewing_distance = 0
            current_index = tree_house_index - 1
            break_flag  = False

            # check viewing distance from tree house in one direction
            while (0 <= current_index and not break_flag):

                viewing_distance += 1

                if tree_heights_list[tree_house_index] <= tree_heights_list[current_index]:
                    break_flag = True

                current_index -= 1

            scenic_scores[tree_house_index] = viewing_distance

            # check viewing distance from tree house opposite direction
            viewing_distance = 0
            current_index = tree_house_index + 1
            break_flag = False

            while (current_index < tree_heights_length and not break_flag):

                viewing_distance += 1

                if tree_heights_list[tree_house_index] <= tree_heights_list[current_index]:
                    break_flag = True

                current_index += 1

            scenic_scores[tree_house_index] *= viewing_distance

        return scenic_scores

    def get_largest_scenic_score(self, tree_heights_grid):

        if tree_heights_grid.shape[0] == 0:
            return 0

        scenic_score_grid_by_row = np.apply_along_axis(self.get_scenic_score_by_row, axis=1, arr=tree_heights_grid)
        scenic_score_grid_by_column = np.apply_along_axis(self.get_scenic_score_by_row, axis=0, arr=tree_heights_grid)

        # multiply scenic scores by row and scenic scores by column to get final result
        scenic_score_grid = np.multiply(scenic_score_grid_by_row, scenic_score_grid_by_column).astype(int)

        return np.amax(scenic_score_grid)

    def main(self, part):

        f = open(self.input_path, "r")

        tree_height_rows = []

        for line in f:
            tree_height_rows.append([])

            for tree_height in line.strip():
                tree_height_rows[len(tree_height_rows) - 1].append(int(tree_height))

        tree_heights_grid = np.matrix(tree_height_rows)

        if part == 1:
            return self.get_visible_tree_count(tree_heights_grid)

        else:
            return self.get_largest_scenic_score(tree_heights_grid)

day_eight = DayEight("Input/DayEightInput.txt")

print("Part One: " + str(day_eight.main(1)))

print("Part Two: " + str(day_eight.main(2)))


# coding: utf-8

# In[1]:

import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

from color_spectrum import Spectrum

# In[2]:

spec = Spectrum()
spec._init_empty_colormeshes()
spec._colorize_colormeshes()

# In[3]:

# name = "red green blue white"
# rgbb = spec.get_colormesh(name)
# orig = rgbb[name].copy()

# In[4]:

# mask = orig[:, :, 0] > 0.8 * orig[:, :, 1]**3 + 0.4

# In[5]:

# cut = orig.copy()
# cut[mask] = 0

# In[6]:

# fig, (ax_orig, ax_cut) = plt.subplots(ncols=2)
# ax_orig.imshow(orig, origin="lower")
# ax_orig.set_title("Original")
# ax_orig.set_xlabel("R")
# ax_orig.set_ylabel("G")
# ax_cut.imshow(cut, origin="lower")
# ax_cut.set_title(r"$R < 0.8 \cdot G^2$")
# ax_cut.set_xlabel("R")
# ax_cut.set_ylabel("G")
# fig.tight_layout()
# fig.savefig("/tmp/cut.png")

# In[7]:

def plot_orig_cut(mesh, color0 = 0, color1 = 1, factor = 0, offset = 0, exponent = 1, mantisse = 1, dark=True):
    """Plots original and cut colormesh side to side.

    Parameter:
        mesh: numpy.ndarray with shape (256, 256, 3)
        dark: boolean if mesh is darker or lighter
        cut: dictinary

    """
    fig, (ax_orig, ax_cut) = plt.subplots(ncols=2, figsize=(8, 4))
    colors = {0: "R", 1: "G", 2: "B"}

    x0 = color0
    x1 = color1
    a = factor
    o = offset
    e = exponent
    m = mantisse
    mask = orig[:, :, x0] > a * (orig[:, :, x1] + o) ** e + m

    cut = mesh.copy()
    cut[mask] = 1 if dark else 0

    ax_orig.imshow(mesh, origin="lower")
    ax_orig.set_title("Original")
    ax_orig.set_xlabel(colors[x0])
    ax_orig.set_ylabel(colors[x1])
    ax_cut.imshow(cut, origin="lower")
    ax_cut.set_title(r"Cut-Out: ${} > {} \cdot ({} + {}) ^ {} + {}$".format(colors[x0], a, colors[x1], o, e, m))
    ax_cut.set_xlabel(colors[x0])
    ax_cut.set_ylabel(colors[x1])

    fig.tight_layout()

    return fig, cut

# In[8]:

name = "red green blue white"
rgbb = spec.get_colormesh(name)
orig = rgbb[name].copy()
fig, cut = plot_orig_cut(mesh=orig, **{"color0": 0, "color1": 1, "factor": 1.1, "exponent": 4, "mantisse": 0.3}, dark=False)
fig.savefig("/tmp/cut.png")

# In[13]:

name = "green blue red black"
rgbb = spec.get_colormesh(name)
orig = rgbb[name].copy()
fig, cut = plot_orig_cut(orig, **{"color0": 1, "color1": 2, "factor": 1, "exponent": 3, "mantisse": 0.15, "offset": 0.1}, dark=True)

fig.savefig("/tmp/cut.png")

# In[12]:

name = "blue red green white"
rgbb = spec.get_colormesh(name)
orig = rgbb[name].copy()
fig, cut = plot_orig_cut(orig, **{"color0": 1, "color1": 2, "factor": 1, "exponent": 3, "mantisse": 0.15, "offset": 0.1}, dark=False)

fig.savefig("/tmp/cut.png")


#
# Second step in the chembl synonym generation pipeline:
# python ${PYDIR}/chembl/dump_mysql_table_data.py --tablename=molecule_synonyms | \
#   sort -k1,1 -n | \
#   python ${PYDIR}/parse_chembl_synonyms.py | \
#   python ${PYDIR}/generate_syn_dictionary.py > ${CDATADIR}/syn_dict_all.txt
#
#
import time
import datetime
import re
import os, sys
import random
import json
from datahelper import Datahelper

def main():
  """
  Requires the input to be sorted on the first field (the numeric molregno).
  One record per molregno is output.

  Calls a datahelper function to normalise each word or phrase (convert to
  lower case and remove special characters)
  """
  count = 0
  last_molno = ""
  related_synonyms = []
  dh = Datahelper()

  for line in sys.stdin:
    data = line.strip().split('\t')
    if data[0] != last_molno and last_molno != "":
      print('|'.join(related_synonyms) + "|MOLREGNO:" + last_molno)
      related_synonyms = []
    last_molno = data[0]
    text = dh.get_normalised_phrase(data[1])
    stype = data[2]
    syn = stype + ":" + text
    if syn not in related_synonyms:
      related_synonyms.append(syn)

  # output the last synonym group
  print('|'.join(related_synonyms) + "|MOLREGNO:" + last_molno)

# execution flow starts here
#
start_time = time.time()

count = main()


from queue import PriorityQueue
from collections import defaultdict

def search(starting_state, pods_in_group):
    # game states
    states = defaultdict(lambda: float('inf'))
    target_states = defaultdict(int)
    states[starting_state] = 0
    lowest_energy = int(1e9)
    # 'visited' states
    visited = []
    queue = PriorityQueue()
    queue.put((0, starting_state))
    while not queue.empty():
        (energy, current_state) = queue.get()
        #print(queue.qsize())
        visited.append(current_state)
        if is_target_state(current_state):
            if energy < lowest_energy:
                target_states[current_state] = energy
                print(f'found target state: {current_state} energy {energy}')
                lowest_energy = energy
            continue
        for (energy, next_state) in get_moves(current_state, pods_in_group):
            if next_state not in visited:
                old_energy = states[next_state]
                new_energy = states[current_state] + energy
                if new_energy < lowest_energy and new_energy < old_energy:
                    queue.put((new_energy, next_state))
                    states[next_state] = new_energy
    return target_states

def is_target_state(state):
    for i, a in enumerate(state):
        target_room = 2*(i//2)+2
        if a[1] == 0 or a[0] != target_room:
            return False
    return True

def get_hallway_path(x, target):
    start = min(x, target)
    end = max(x, target)
    path = list(range(start, end))
    path.append(end)
    path.remove(x)
    return path

def get_energy(i, moves):
    if i in [0,1,2,3]: return moves
    if i in [4,5,6,7]: return moves * 10
    if i in [8,9,10,11]: return moves * 100
    if i in [12,13,14,15]: return moves * 1000

DPM = {}
def get_moves(state, pods_in_group):

    if state in DPM:
        return DPM[state]

    moves = []
    rooms = defaultdict(lambda: [])
    hallway = []
    for i, a in enumerate(state):
        if a[1] < 0:
            rooms[a[0]].append((i, a))
        else:
            hallway.append(a[0])
    # state
    #    A     A     B     B     C     C     D     D
    # [(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)]
    for i, a in enumerate(state):
        target_room = pods_in_group*(i//pods_in_group)+2

        # are we where we belong?
        if a[0] == target_room:

            # if we're at the back, we're fine
            if a[1] == pods_in_group * -1:
                continue

            # if the room only contains my peeps, we're fine
            if all(pods_in_group*(t[0]//pods_in_group)+2 == target_room for t in rooms[target_room]):
                continue

        # if we are in the hallway
        if (a[1] == 0):

            # do we have a line of site to our room?
            # - figure out which spaces we'll need to move to on our way to our room
            hallway_path = get_hallway_path(a[0], target_room)

            # - are we blocked by someone else in the hallway?
            if any(step in hallway_path for step in hallway):
                continue

            # can we enter our target room?
            if len([x for x in rooms[target_room] if x[0]//pods_in_group != i//pods_in_group]) > 0:
                continue

            # - move into our room
            room_steps = pods_in_group - len(rooms[target_room])
            new_state = list(state)
            new_state[i] = (target_room, room_steps * -1)
            energy = get_energy(i, len(hallway_path) + room_steps)
            move = list()
            move.append((energy, tuple(new_state)))
            DPM[state] = move
            return move

        # if we are moving into a hallway
        if a[1] < 0:

            # are we blocked?
            if a[0] != target_room and a[1] < -1 and len(rooms[a[0]]) > 1:
                for i, b in rooms[a[0]]:
                    if b[1] > a[1]:
                        continue

            # for all of the possible destinations in the hallway
            for destination in [0,1,3,5,7,9,10]:
                hallway_path = get_hallway_path(a[0], destination)

                # - are we blocked by someone else in the hallway?
                if any(step in hallway_path for step in hallway):
                    continue
                new_state = list(state)
                new_state[i] = (destination, 0)
                energy = get_energy(i, len(hallway_path) + (a[1] * -1))
                moves.append((energy, tuple(new_state)))

    DPM[state] = moves
    return moves

##################
#     01234567890
#    #############
#  0 #...........#
# -1 ###B#C#B#D###
# -2   #D#C#B#A#
# -3   #D#B#A#C#
# -4   #A#D#C#A#
#      #########
#start = ((2,-4),(8,-2),(8,-4),(6,-3),(2,-1),(6,-1),(4,-3),(6,-2),(4,-1),(6,-2),(4,-2),(8,-3),(4,-2),(8,-1),(2,-2),(2,-3))
#energy = 12521
#    #############
#  0 #...........#
# -1 ###D#C#A#B###
# -2   #D#C#B#A#
# -3   #D#B#A#C#
# -4   #D#C#B#A#
#      #########
#start = ((6,-1),(8,-2),(6,-2),(8,-1),(4,-2),(4,-1),(2,-2),(2,-1))
#energy =

states = search(start, 4)
key_min = min(states.keys(), key=(lambda k: states[k]))
print(f'looks like {states[key_min]} is the least energy possible')


import json
import tldextract
import re
import yaml
import base64
import requests

def run(search):
    with open("apikey.yaml") as f:
        param = yaml.load(f.read(),Loader=yaml.FullLoader)
        param = param.get('Fofa')
    email = param.get('email')
    key = param.get('key')

    ulist = []
    url = f'https://fofa.info/api/v1/search/all?email={email}&key={key}&qbase64={search}&size=1&fields=host'
    resp = requests.get(url)
    try:
        size = resp.json().get('size')
        if size > 20: size = 20
        url = f'https://fofa.info/api/v1/search/all?email={email}&key={key}&qbase64={search}&size={size}&fields=host'
        resp = requests.get(url)
        ulist.extend(resp.json().get('results'))

        # for u in ulist:
        #     print(f"[+] {u}")
    except:
        print(f"[warning] {resp.json()}")

    uulist = []
    for u in ulist:
        if re.match("http", u) or re.match("https", u):
            u = u.split('/')[2]
        uulist.append(u)
    return uulist

def fofa_domain_run(domain):
    search = f'domain={domain}'
    search = base64.b64encode(search.encode()).decode()
    return run(search)

def fofa_name_run(name):
    search = f'{name}'
    search = base64.b64encode(search.encode()).decode()
    return run(search)

if __name__ == '__main__':
    domain = "auroradss.com"
    fofa_run(domain)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Utility functions."""

import gc
import socket
from typing import Dict, Optional

from pyppeteer.chromium_downloader import check_chromium, chromium_executable
from pyppeteer.chromium_downloader import download_chromium

__all__ = [
    'check_chromium',
    'chromium_executable',
    'download_chromium',
    'get_free_port',
    'merge_dict',
]

def get_free_port() -> int:
    """Get free port."""
    sock = socket.socket()
    sock.bind(('localhost', 0))
    port = sock.getsockname()[1]
    sock.close()
    del sock
    gc.collect()
    return port

def merge_dict(dict1: Optional[Dict], dict2: Optional[Dict]) -> Dict:
    """Merge two dictionaries into new one."""
    new_dict = {}
    if dict1:
        new_dict.update(dict1)
    if dict2:
        new_dict.update(dict2)
    return new_dict


import random
from cachetools import TTLCache, cached
from youtubesearchpython import VideosSearch
from imdb import IMDb

imdb = IMDb()
cache = TTLCache(maxsize=100, ttl=86400)

class NotFound(Exception):
    pass

@cached(cache)
def _get_movie(movie_title: str):
    results = imdb.search_movie(movie_title)[0]
    imdb.get_movie_infoset()
    return imdb.get_movie(results.movieID)

@cached(cache)
def get_top_250():
    res = imdb.get_top250_movies()
    movies = [movie['title'] for movie in res]
    return movies

def get_plot(movie_title: str):
    results = _get_movie(movie_title)
    results = str(results['plot'][0])
    try:
        results = results.split('::')[0]  # remove unnecessary characters
    except ValueError:
        pass
    return results

def get_poster(movie_title: str):
    movie = _get_movie(movie_title)
    return movie['cover url']

def get_directors(movie_title: str):
    movie = _get_movie(movie_title)
    res = str()
    for person in movie['directors']:
        res = res + person['name'] + ", "
    if len(movie['directors']) == 1:
        for person in movie['directors']:
            res = res + person['name']
    return res

def get_runtime(movie_title: str):
    movie = _get_movie(movie_title)
    runtime_mins = int(movie['runtimes'][0])
    runtime = '{:02d}:{:02d}'.format(*divmod(runtime_mins, 60))
    hours, minutes = runtime.split(':')
    runtime = int(hours) * 60 + int(minutes)
    return runtime

def get_cast(movie_title: str):
    movie = _get_movie(movie_title)
    res = str()
    for person in movie['cast']:
        res = res + person['name'] + ", "
    return res

def get_category(movie_title: str):
    movie = _get_movie(movie_title)
    return movie['genres'][0]

def get_producer(movie_title: str):
    movie = _get_movie(movie_title)
    res = str()
    # added this hackish nonsense cause VARCHAR count for producer in movie is not large enough
    person_count = 0
    for person in movie['producers']:
        if person_count == 1:
            break
        res = res + person['name']
        person_count += 1
    return res

def get_reviews(movie_title: str):
    movie = _get_movie(movie_title)
    results = imdb.get_movie_reviews(movie.movieID)
    # select a random review from the 10000000 provided lol
    return results['data']['reviews'][random.randint(0, len(results['data']['reviews']) - 1)]['content']

def get_imdb_rating(movie_title: str):
    movie = _get_movie(movie_title)
    return movie['rating']

def get_trailer(movie_title: str):
    vid = VideosSearch(f"{movie_title} Movie Trailer", limit=1)
    return vid.result()['result'][0]['link']

def get_mpaa_rating(movie_title: str):
    movie = _get_movie(movie_title)
    for cert in movie['certificates']:
        # grab the USA film rating
        if 'United States' in str(cert):
            # make sure it's not the TV rating
            if 'TV' in str(cert):
                continue
            return str(cert).split(':')[1]


from email.mime import image
import os
from django.shortcuts import render
from django.views import View
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
import cv2
import urllib
import numpy as np

FACE_DETECTOR_PATH = "{base_path}/cascades/haarcascade_frontalface_default.xml".format(base_path=os.path.abspath(os.path.dirname(__file__)))

def _grab_image(path=None, stream=None, url=None):
    # if the path is not None, then load the image from disk
    if path is not None:
        image = cv2.imread(path)
    # otherwise, the image does not reside on disk
    else:
        # if the URL is not None, then download the image
        if url is not None:
            #resp = urllib.urlopen(url)
            resp = urllib.request.urlopen(url)
            data = resp.read()
        # if the stream is not None, then the image has been uploaded
        elif stream is not None:
            data = stream.read()
        # convert the image to a NumPy array and then read it into
        # OpenCV format
        image = np.asarray(bytearray(data), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    # return the image
    return image

class FaceDetectionView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request):
        data = {'message':'Hello world'}
        return JsonResponse(data)

    def post(self, request):
        data = {"success": False}

        if request.FILES.get("image", None) is not None:
            image = _grab_image(stream=request.FILES["image"])
        else:
            url = request.POST.get("url", None)
            if url is None:
                data["error"] = "Not Url provided"
                return JsonResponse(data)

            image = _grab_image(url=url)

        # convert the image to grayscale, load the face cascade detector,
        # and detect faces in the image
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
        rects = detector.detectMultiScale(gray, 1.3, 5)

        # construct a list of bounding boxes from the detection
        rects = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects]
        # update the data dictionary with the faces detected
        data.update({"num_faces": len(rects), "faces": rects, "success": True})
        # return a JSON response
        return JsonResponse(data)

    def put(self, request):
        pass

    def delete(self, request):
        pass