import datetime
from matplotlib import dates
import numpy as np
import json
import re
import math
import time
import collections
import itertools

positions = ["_right_arm", "_mattrass"]

for vp_number in range(26, 32):
    for smartphone_position in positions:

        current_folder = "result_data_vp"+str(vp_number)+smartphone_position+"/"

        sleep_stage_file = open("sleep_staging_files/VP"+str(vp_number)+"_NAP.TXT", "r")
        acceleration_value_file = open(current_folder+"result_acceleration", "r")
        audio_value_file = open(current_folder+"result_audio", "r")

        output_file = open(str(current_folder)+"VP"+str(vp_number)+smartphone_position+"_30sec_chunks.csv", "w")

        content = ""
        with open("marker_files/timestamp_and_marker_"+str(vp_number)+".txt", "r") as volume_peak_timestamp_file:
            content = volume_peak_timestamp_file.readlines()

        volume_peak_timestamp = float(content[0]) / 1000.0
        marker_index = int(content[1])

        marker_starting_point = (marker_index / 500)
        print("Marker_starting_point "+ str(marker_starting_point))

        current_timestamp = volume_peak_timestamp
        current_audio_timestamp = current_timestamp
        starting_timestamp = current_timestamp

        # prepare data of sleepstaging file
        data = [re.sub('\D','',x.split("\t")[1]) for x in sleep_stage_file]
        t_stamp = starting_timestamp
        timestamps = []
        for x in range(0,len(data)):
            t_stamp+=30.0
            timestamps.append( t_stamp )

        acceleration_json_data = json.load( acceleration_value_file )
        audio_json_data = json.load( audio_value_file )

        print( "JSON-len"+ str(len(acceleration_json_data)) )

        previous_vector = [0,0,0]
        previous_audio_vector = 0
        date_and_distance = []

        def calculate_distance(vec1, vec2):
            return math.sqrt( math.pow( (vec1[0]-vec2[0]), 2) + math.pow( (vec1[1]-vec2[1]), 2) + math.pow( (vec1[2]-vec2[2]), 2) )

        ordered_audio_dict = collections.OrderedDict()
        ordered_dict = collections.OrderedDict()
        ordered_dict_start = collections.OrderedDict()

        for x in audio_json_data:
            ordered_audio_dict[ x[0] ] = x[1]

        cnt = 0
        for x in acceleration_json_data:
            cnt += 1
            key = x.keys()[0]
            vec1 = x[key]
            distance = calculate_distance( vec1, previous_vector )
            if(distance > 0.0):
                ordered_dict[str(key)] = distance
                previous_vector = vec1

        keys = ordered_dict.keys()
        first_timestamp = min(keys, key=lambda x:abs( float(x) - current_timestamp ))

        for x in list(itertools.dropwhile(lambda k: k!= first_timestamp, ordered_dict.iterkeys() )) :
            ordered_dict_start[x] = ordered_dict[x]

        def plot_audio_data( current_x, data_length, idx ):
            global current_audio_timestamp
            keys = ordered_audio_dict.keys()

            # # get closest timestamp from audio peak timestamp
            current_audio_timestamp = min(keys, key=lambda x:abs( float(x) - float(timestamps[idx]) ))
            initial_timestamp = current_audio_timestamp

            valueList = []
            cnt = 0
            for x in list(itertools.dropwhile(lambda k: k != initial_timestamp, ordered_audio_dict.iterkeys() )) :
                if( initial_timestamp != starting_timestamp ):
                    if( float(x) < float(initial_timestamp) + 30 and float(x) > float(initial_timestamp) ):
                        cnt += 1
                        value = ordered_audio_dict[x]
                        current_audio_timestamp = float(x)
                        valueList.append(value)
                else:
                    if( float(x) < float(initial_timestamp) + (30 - int(marker_starting_point)) and float(x) > float(initial_timestamp) ):
                        current_audio_timestamp = float(x)

            output_file.write( str(np.mean(valueList))+"," )
            output_file.write( str(np.amax(valueList))+"," )
            output_file.write( str(cnt)+"," )
            current_audio_timestamp = initial_timestamp + 30
            return

        def plot_accelerometer_data( current_x, data_length, idx ):
            global current_timestamp
            keys = ordered_dict_start.keys()

            # get closest timestamp from audio peak timestamp
            current_timestamp = min(keys, key=lambda x:abs( float(x) - float(timestamps[idx]) ))
            initial_timestamp = current_timestamp

            cnt = 0
            valueList = []
            for x in list(itertools.dropwhile(lambda k: k != initial_timestamp, ordered_dict_start.iterkeys() )) :
                if( initial_timestamp != starting_timestamp ):
                    if( float(x) < float(initial_timestamp) + 30 and float(x) > float(initial_timestamp) ):
                        current_timestamp = float(x)
                        cnt += 1
                        valueList.append(ordered_dict_start[x])
                else:
                    if( float(x) < float(initial_timestamp) + (30 - int(marker_starting_point)) and float(x) > float(initial_timestamp) ):
                      current_timestamp = float(x)
            output_file.write( str(cnt)+"," )
            output_file.write( str(np.mean(valueList))+"," )
            output_file.write( str(np.amax(valueList))+"\n" )
            return

        previous_value=0
        current_x=0.0
        growth_x=1.0
        rem_phase_adjustment = 0
        rem_value = 5
        sleep_value = 6

        max_x = len(data)
        max_y = 6
        min_x = 0
        min_y = -5
        compensate = math.fabs(min_y)
        overall_height = max_y + compensate

        i = 0
        time_t = time.time()

        output_file.write("sleep_stage, change_classifier, audio_means, audio_max, audio_count, acceleration_count, acceleration_means, acceleration_max\n")
        for value in data:
            print( str(i) +"from "+ str(len(data)) )

            if( int(value) == sleep_value ):
                value = 0

            output_file.write(str(value)+",")

            print("value: "+str(value)+" prev:"+str(previous_value))
            if int(value) > int(previous_value):
                print("fall_asleep")
                output_file.write("fall asleep,")
            if int(value) < int(previous_value):
                print("wakeup")
                output_file.write("wake up,")
            if int(value) == int(previous_value):
                print("constant")
                output_file.write("constant,")

            previous_value = value
            plot_audio_data( current_x, max_x, i )
            plot_accelerometer_data( current_x, max_x, i )
            i+=1
            current_x += growth_x

        print( "Execution Time: " + str( time.time() - time_t) )


#!/usr/bin/env python

import os
import rospy
from tag_manager.srv import CheckTagKnown, CheckTagKnownResponse
from tag_manager.srv import AddTag, AddTagResponse
from tag_manager.srv import GetTags, GetTagsResponse

from tag_manager.msg import TagList, TagPoint

from std_msgs.msg import Bool

from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from nav_msgs.msg import OccupancyGrid, MapMetaData

class TagManager:

    def __init__(self):
        rospy.on_shutdown(self._shutdown)
        rospy.init_node('tag_manager')

        self.abs_file_path=rospy.get_param("~tag_file",default="/home/daniel/catkin_ws/src/tag_manager/StoredTag/tags.store")

        self.tag_list = []
        self.tag_detection_radius = 10
        self._load_tags()

        self.map_info = MapMetaData()
        self.markerArray = MarkerArray()

        # --- Publisher ---
        self.marker_publisher = rospy.Publisher('visualization_marker_array', MarkerArray, queue_size=100)

        # --- Services ---
        self.check_tag_known_service = rospy.Service('check_tag_known', CheckTagKnown, self._handle_check_tag_known)
        self.add_tag_service = rospy.Service('add_tag', AddTag, self._handle_add_tag)
        self.get_tags_service = rospy.Service('get_tags', GetTags, self._handle_get_tags)

        self._setup()

        rospy.spin()

    def _setup(self):
        """
        Get map meta information
        """
        map = rospy.wait_for_message('map', OccupancyGrid)
        self.map_info = map.info

    def _shutdown(self):
        self._store_tags()

    def _handle_check_tag_known(self, data):
        """
        Service handler to check if the tag at the given x and y coordinates is known.
        """
        # extract the data
        x = data.x
        y = data.y

        # create the response
        response = Bool()
        response.data = self._check_tag_x_y(x,y)
        return CheckTagKnownResponse(response)

    def _check_tag_x_y(self, x, y):
        """
        Check if the given tag is kown.
        """
        known = False
        for (y_known, x_known) in self.tag_list:
            if x_known >= (x - self.tag_detection_radius) and x_known <= (x + self.tag_detection_radius) and y_known >= (y - self.tag_detection_radius) and y_known <= (y + self.tag_detection_radius):
                known = True
                break
        return known

    def _handle_add_tag(self, data):
        """
        Service handler to add a tag to the list of known tags.
        """
        # extract the data
        x = data.x
        y = data.y

        known = self._check_tag_x_y(x,y)

        response = Bool()
        response.data = False

        if not known:
            self.tag_list.append((y, x))
            response.data = True
            rospy.loginfo("Added tag: y=" + str(y) + " x=" + str(x))
        self._publish_point(x, y)

        return AddTagResponse(response)

    def _handle_get_tags(self, data):
        """
        Handle request for tag list.
        """
        tag_list = TagList()

        for (y, x) in self.tag_list:
            tag = TagPoint()
            tag.x = x
            tag.y = y
            tag_list.tags.append(tag)

        return GetTagsResponse(tag_list)

    def _load_tags(self):
        """
        Loads tags from the file if any are stored in the file.
        """
        file = None
        try:
            rospy.loginfo("--- Loading tags ---")
            # open the file
            file = open(self.abs_file_path, "r")

            # read every line and add to the tag list
            fileRead = file.readlines()
            count = 0
            for line in fileRead:
                count = count + 1
                coords = line.strip().split(',')
                rospy.loginfo(coords[0] + "," + coords[1])
                self.tag_list.append((int(coords[0]), int(coords[1])))

            rospy.loginfo("--- Loaded " + str(count) + " tags ---")
        except IOError:
            rospy.loginfo("--- No tags loaded because ./StoredTag/tags.store does not exist---")
        finally:
            if file != None:
                file.close()

    def _store_tags(self):
        """
        Store tags to the file.
        """
        file = None
        try:
            rospy.loginfo("--- Storeing tags ---")
            # open the file
            file = open(self.abs_file_path, "w")

            count = 0
            # write all entries in tag_list to the file
            for (y, x) in self.tag_list:
                count = count + 1
                file.write(str(y) + "," + str(x) + "\n")

            rospy.loginfo("--- Stored " + str(count) + " tags ---")
        except IOError:
            rospy.loginfo("--- Storing tags to file failed ---")
        finally:
            file.close()

    def _publish_point(self, x, y):
        """
        Publish tag position so they can be visualized in RViz
        """
        marker = Marker()
        marker.header.frame_id = "Turtle4711/map"
        marker.type = marker.SPHERE
        marker.action = marker.ADD
        marker.scale.x = 0.1
        marker.scale.y = 0.1
        marker.scale.z = 0.1
        marker.color.r = 1.0
        marker.color.g = 1.0
        marker.color.b = 0.0
        marker.color.a = 1.0
        marker.pose.orientation.w = 1.0
        marker.pose.position.x = (x * self.map_info.resolution) + self.map_info.origin.position.x
        marker.pose.position.y = (y * self.map_info.resolution) + self.map_info.origin.position.y
        marker.pose.position.z = 1

        self.markerArray.markers.append(marker)

        id = 0
        for m in self.markerArray.markers:
            m.id = id
            id += 1

        self.marker_publisher.publish(self.markerArray)

        rospy.sleep(0.01)

if __name__ == "__main__":
    try:
        tagManager = TagManager()
    except rospy.ROSInterruptException:
        pass


import pygame

pygame.init() # 초기화 (반드시 필요)

#화면 크기 설정
screen_width = 480 # 가로
screen_height = 640 # 세로
screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 크기 설정

# 화면 타이틀 설정
pygame.display.set_caption("Nado Game")

# FPS 설정
clock = pygame.time.Clock()

# 배경 이미지 불러오기
background = pygame.image.load("./background.png")

# 캐릭터 불러오기
character = pygame.image.load("./character.png")
character_size = character.get_rect().size  # 이미지의 크기를 구해옴
character_width = character_size[0]         # 캐릭터의 너비
character_height = character_size[1]        # 캐릭터의 높이
character_x_pos = screen_width / 2  - character_width / 2    # 화면 가로의 절반 크기에 해당하는 곳에 위치    (가로위치)
character_y_pos = screen_height - character_height          # 화면 세로 크기 가장 아래에 해당하는 곳에 위치 (세로위치)

# 이동할 좌표
to_x = 0
to_y = 0

# 이동 속도
character_speed = 0.6

# 적 캐릭터
enemy = pygame.image.load("./enemy.png")
enemy_size = enemy.get_rect().size  # 이미지의 크기를 구해옴
enemy_width = enemy_size[0]         # 캐릭터의 너비
enemy_height = enemy_size[1]        # 캐릭터의 높이
enemy_x_pos = screen_width / 2  - enemy_width / 2   # 화면 가로의 절반 크기에 해당하는 곳에 위치    (가로위치)
enemy_y_pos = screen_height / 2 - enemy_height / 2  # 화면 세로 크기 가장 아래에 해당하는 곳에 위치 (세로위치)

#이벤트 루프
running = True # 게임이 진행중인가?
while running:
    dt = clock.tick(144)     # 게임화면의 초당 프레임 수 설정

    # 캐릭터가 1초 동안에 100만큼 이동 해야 할 때
    # 10 fps : 1초에 10번 화면 전환 => 1초에 10번 동작 => 1번에 10만큼 이동 = 10 * 10 = 100
    # 20 fps : 1초에 20번 화면 전환 => 1초에 20번 동작 => 1번에  5만큼 이동 =  5 * 20 = 100

    for event in pygame.event.get():    # 필수 부분 어떤 이벤트가 발생하였는가?
        if event.type == pygame.QUIT :  # 창 닫기 버튼 눌렀을 때
            running = False

        if event.type == pygame.KEYDOWN:    # 키가 눌러 졌는지 확인
            if event.key == pygame.K_LEFT:      # 캐릭터를 왼쪽으로
                to_x -= character_speed # 5위치만큼 왼쪽으로
            elif event.key == pygame.K_RIGHT:   # 캐릭터를 오른쪽으로
                to_x += character_speed # 5위치만큼 오른쪽으로
            elif event.key == pygame.K_UP:      # 캐릭터를 위로
                to_y -= character_speed # 5위치만큼 위쪽으로
            elif event.key == pygame.K_DOWN:    # 캐릭터를 아래로
                to_y += character_speed # 5위치만큼 아래쪽으로

        if event.type == pygame.KEYUP: #방향키를 떼면 멈춤
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                to_y = 0

    character_x_pos += to_x * dt
    character_y_pos += to_y * dt

    # 가로 경계 값 처리
    if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width

    # 세로 경계값 처리
    if character_y_pos < 0:
        character_y_pos = 0
    elif character_y_pos > screen_height - character_height:
        character_y_pos = screen_height - character_height

    # 충돌 처리를 위한 rect 정보 업데이트
    character_rect = character.get_rect()
    character_rect.left = character_x_pos
    character_rect.top = character_y_pos

    enemy_rect = enemy.get_rect()
    enemy_rect.left = enemy_x_pos
    enemy_rect.top = enemy_y_pos

    # 충돌 체크
    if character_rect.colliderect(enemy_rect):      # 충돌 처리 함수
        print("!충돌!")
        running = False

    screen.blit(background, (0,0))      # 배경 그리기
    screen.blit(character, (character_x_pos, character_y_pos))  # 캐릭터 그리기
    screen.blit(enemy, (enemy_x_pos, enemy_y_pos))  # 적 그리기

    pygame.display.update()             # 게임 화면 다시 그리기! 반복 호출

# 게임 종료 시
# pygame 종료

pygame.quit()


import pandas as pd
import gspread
from gspread_pandas import Spread, conf
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

def read_gsheet(sheetname, tab, first_row=0):
    #first_row has to be an integer, it helps to set the df headers as the correct columns if not starting from the top
    workbook = client.open(sheetname)
    ws = workbook.worksheet(tab)
    sheet = ws.get_all_values()
    column_name = sheet[first_row]
    df = pd.DataFrame(sheet[first_row+1:], columns=column_name)
    return df

# The entire tab is now in the dataframe


from collections import deque

#Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ret = []
        queue = deque([[root, 0]])
        while queue:
            node, cur_depth = queue.pop()
            if not node: continue
            queue.append([node.right, cur_depth + 1])
            queue.append([node.left, cur_depth + 1])
            if len(ret) == cur_depth: ret.append([node.val])
            else: ret[cur_depth].append(node.val)
        return ret


import sys
from typing import List

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

class Part:
    def __init__(self, from_n: int, to_n: int, from_color: str, to_color: str):
        self.from_n = from_n
        self.to_n = to_n
        self.from_color = from_color
        self.to_color = to_color

#  Create gradient colors according to colored parts
class Colored:
    def __init__(self, parts: List[Part]):
        self._parts = parts

    def get_color(self, current_value):
        h = self._parts[0].from_color
        for part in self._parts:
            if part.from_n <= current_value < part.to_n:
                h = color_fader(part.from_color, part.to_color,
                                (current_value - part.from_n) / (part.to_n - part.from_n))
                break
        print(h)
        r, g, b = tuple(int(round(col * 255)) for col in c.to_rgb(h))
        return f"              <viz:color r=\"{r}\" g=\"{g}\" b=\"{b}\"/>\n"

    def plot_gradient(self, step=500):
        fig, ax = plt.subplots(figsize=(8, 5))
        for i, part in enumerate(self._parts):
            for x in range(step):
                ax.axvline(i * step + x, color=color_fader(part.from_color, part.to_color, x / step), linewidth=4)
        plt.show()

authors_colored = Colored([Part(50, 150, '#040254', '#49a692'),
                           Part(150, 350, '#49a692', '#f9ffe0'),
                           Part(350, sys.maxsize, '#fff9c9', '#fff9c9')])

projects_colored = Colored([Part(50, 100, '#480266', '#910049'),
                            Part(100, 1000, '#910049', '#ffe330'),
                            Part(1000, 306900, '#fff9c9', '#fff9c9')])

# AuthorsColored = Colored([Part()])

def color_fader(c1, c2, mix=0.0):  # fade (linear interpolate) from color c1 (at mix=0) to c2 (mix=1)
    c1 = np.array(c.to_rgb(c1))
    c2 = np.array(c.to_rgb(c2))
    return c.to_hex((1 - mix) * c1 + mix * c2)

# ptojects
c0 = '#480266'
c1 = '#910049'  # red
c2 = '#ffe330'  # yellow

# old_authors
# c1='#49a692' #dark blue
# c2='#f9ffe0' #yellow
#
c3 = '#fff9c9'
#
# c1_small = '#040254'
# c2_small = '#49a692'
#
# from_n = 50
# to_n = 200
# или 2000?

authors_colored.plot_gradient()


import skimage
from skimage.feature import match_descriptors
import numpy as np
import cv2
from debug_utils import *
import matplotlib.pyplot as plt
from skimage.feature import (match_descriptors, corner_harris,
                             corner_peaks, ORB, plot_matches)
from tqdm import tqdm

def add_md_args(parser):
    parser.add_argument("--bf_metric", default="hamming", type=str, help="matching measure in brute force method")
    parser.add_argument("--bf_max_ratio", default=0.8, type=float, help="matching measure in brute force method")
    return parser

def match_descriptors_qs_db(qs_imgs, db_imgs, qs_descriptors, db_descriptors, qs_kps, db_kps, method_name, options):
    method = get_method(method_name)
    result = [[method(db_img, qs_img, qs_descriptor, db_descriptor, qs_kp, db_kp, options) for db_descriptor, db_img, db_kp in zip(db_descriptors, db_imgs, db_kps)] for qs_descriptor, qs_img, qs_kp in zip(qs_descriptors, qs_imgs, qs_kps)]
    #for qs_descriptor, qs_img, qs_kp in tqdm(zip(qs_descriptors, qs_imgs, qs_kps)):
    #result.append([[method(db_img, qs_img, qs_descriptor, db_descriptor, qs_kp, db_kp, options) for db_descriptor, db_img, db_kp in zip(db_descriptors, db_imgs, db_kps)] for qs_descriptor, qs_img, qs_kp in zip(qs_descriptors, qs_imgs, qs_kps)]) #[method(db_img, qs_img, qs_descriptor, db_descriptor, qs_kp, db_kp, options) for db_descriptor, db_img, db_kp in zip(db_descriptors, db_imgs, db_kps)])
    #result = [ ]
    result = np.array(result)
    return result

def automatic_brute_force_match(db_img, qs_img, descriptors1, descriptors2, qs_kp, db_kp, options):
    """ Returns number of matches for descriptor"""
    if type(descriptors1) != np.ndarray or type(descriptors2) != np.ndarray:
        return 0

    metric = options.bf_metric
    max_ratio = options.bf_max_ratio
    matches = match_descriptors(descriptors1, descriptors2, metric=metric, max_ratio=max_ratio, max_distance=0.8, p=1)
    # TODO: Add visualization tool if debug is enabled for point correspondance

    if isDebug() and len(matches) > 10:
        show_matches(qs_img, db_img, qs_kp, db_kp, matches)

    return len(matches)

def auto_bf_matcher_cv(db_img, qs_img, descriptors1, descriptors2, qs_kp, db_kp, options):
    """ Returns number of matches for descriptor"""
    if type(descriptors1) != np.ndarray or type(descriptors2) != np.ndarray:
        return 0

    bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=True)
    matches = bf.knnMatch(descriptors1,descriptors2,k=1)
    # Apply ratio test
    """ good = []
    for m,n in matches:
        if m.distance < 0.8*n.distance:
            good.append([m])
    matches = good """
    #if isDebug() and len(matches) > 10:
    #    show_matches(db_img, qs_img, db_kp, qs_kp, matches)

    return len(matches)

def show_matches(img1, img2, kp1, kp2, matches):
    # Need to draw only good matches, so create a mask
    kp1 = np.array([[int(kp.pt[0]), int(kp.pt[1])] for kp in kp1])
    kp2 = np.array([[int(kp.pt[0]), int(kp.pt[1])] for kp in kp2])

    fig, ax = plt.subplots(nrows=2, ncols=1)
    plot_matches(ax[0], cv2.resize(img1, (256,256)), cv2.resize(img2, (256,256)), kp1, kp2, matches)
    ax[0].axis('off')
    ax[0].set_title("Matches")
    plt.show()

    """ matchesMask = [[0,0] for i in range(len(matches))]
    # ratio test as per Lowe's paper
    for i,m in enumerate(matches):
        if len(matches[i]) != 0:
            matchesMask[i]=[1,0]

    draw_params = dict(matchColor = (0,255,0),
                    singlePointColor = (255,0,0),
                    matchesMask = matchesMask,
                    flags = cv2.DrawMatchesFlags_DEFAULT)

    img3 = cv2.drawMatchesKnn(cv2.resize(img1,(256,256)),kp1,cv2.resize(img2,(256,256)),kp2,matches,None,**draw_params)
    cv2.imshow("matches", img3)
    cv2.waitKey(0) """

"""
When using brote force matcher. From OpenCV documentation:
*---
One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are preferable choices for SIFT and SURF descriptors,
NORM_HAMMING should be used with ORB, BRISK and BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor description).
*---
"""

# Selection utils
BRUTE_FORCE = "BF"
OPTIONS = [BRUTE_FORCE]

METHOD_MAPPING = {
    OPTIONS[0]: automatic_brute_force_match
}

def get_method(method):
    return METHOD_MAPPING[method]


# -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 14:32:06 2019

@author: psarka
"""

#1. Write a function to compute 5/0 and use try/except to catch the exceptions.

import sys

def DivideByZero(x):
    try:
        x/0
    except ZeroDivisionError as e:
        print("Error: ",str(e).upper())

x=5
DivideByZero(x)

#2. Implement a Python program to generate all sentences where subject is in ["Americans",
#"Indians"] and verb is in ["Play", "watch"] and the object is in ["Baseball","cricket"].

subjects=["Americans","Indians"]
verbs=["play","watch"]
objects=["Baseball","Cricket"]
Sentence = [(Sub+' '+vrb+' '+Obj+".") for Sub in subjects for vrb in verbs for Obj in objects]
print("Output:")
for sen in Sentence:
    print(sen)


# Author: Joel Wachsler
# Date: 2015-08-02

class Rectangle():
    def __init__(self, persons):
        self.persons = persons
        # Start values of x and y
        self.x = int(persons ** 0.5)
        self.y = int(persons ** 0.5)
        # Holder for true values
        self.works = []
        # We stop after 5 false in a row
        self.falseCounter = 0

    def valid(self):
        return self.falseCounter != 3 and self.x != 1

    def increment(self):
        if (self.x * self.y) >= self.persons:
            self.works.append((self.x, self.y))
            self.falseCounter = 0
            self.x -= 1
        else:
            self.y += 1
            self.falseCounter += 1

    def smallestArea(self):
        return min([(x + 1) * (y + 1) for (x, y) in self.works])

def main():
    rec = Rectangle(int(input()))

    # Default values not needed to be calculated
    knownValues = {1:4,2:6,3:8}
    if rec.persons in knownValues:
        print(knownValues[rec.persons])
        return

    while rec.valid():
        rec.increment()

    print(rec.smallestArea())

if __name__ == "__main__":
    main()


from django.urls import path
from . import views

app_name='shop'

urlpatterns = [
	path('', views.ProductListTodo.as_view()),
    path('<int:pk>/', views.CategoryDetailTodo.as_view()),
	path('category/', views.CategoryListTodo.as_view()),
	path('<slug:c_slug>/',views.allProdCat, name='products_by_category'),
	path('<slug:c_slug>/<slug:product_slug>/', views.ProdCatDetail, name='ProdCatDetail'),
]


def premik(ukaz, x, y, smer):
    smeri = "NESW"
    premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    ismer = smeri.index(smer)
    if ukaz == "R":
        smer = smeri[(ismer + 1) % 4]
    elif ukaz == "L":
        smer = smeri[(ismer - 1) % 4]
    else:
        dx, dy = premiki[ismer]
        x += dx * ukaz
        y += dy * ukaz
    return x, y, smer

def izvedi(ime_datoteke):
    seznam = [(0,0,"N")]
    x = 0
    y = 0
    smer = "N"
    datoteka = open(ime_datoteke,"r")
    for vrstica in datoteka:
        vrstica = vrstica.strip().split()
        if len(vrstica)>1:
            ukaz = int(vrstica[1])
        else:
            if vrstica[0] == "DESNO":
                ukaz = "R"
            if vrstica[0] == "LEVO":
                ukaz = "L"
        seznam.append(premik(ukaz,x,y,smer))
        x = premik(ukaz,x,y,smer)[0]
        y = premik(ukaz, x, y, smer)[1]
        smer = premik(ukaz, x, y, smer)[2]
    return seznam

def opisi_stanje(x, y, smer):
     smeri = "NESW"
     smeri1 = "^>v<"
     ismer = smeri.index(smer)
     return "{:>3}:{:<3} {}".format(x,y,smeri1[ismer])

def prevedi(ime_vhoda, ime_izhoda):
    nova = open(ime_izhoda,"w")
    pot = izvedi(ime_vhoda)
    for (x,y,smer) in pot:
        nova.write("{}\n".format(opisi_stanje(x,y,smer)))

def opisi_stanje_2(x, y, smer):
    smeri = "NESW"
    smeri1 = "^>v<"
    ismer = smeri.index(smer)
    return "{}{:>5}:{})".format(smeri1[ismer],"("+str(x), y, )


def get_chatbot_response(message):
    if message[:2] != '!!':
        return ''

    points, command, args = message.split(' ', 2)
    if command == 'hello':
        return 'Hey there!'
    elif command == 'add':
        num1, num2 = args.split()
        return num1 + num2
    elif command == 'divide':
        num1, num2 = args.split()
        return num1 / num2
    elif command == 'say':
        return args
    else:
        return 'I didn\'t recognize your command :-('


from string import *
def subStringMatchExact(target, key):
    matches = []
    startPosition = 0
    matchPosition = 0
    while (matchPosition > -1):
        matchPosition = target.find(key,startPosition)
        startPosition = matchPosition + 1
        matches.append(matchPosition)
    return tuple(matches[:-1])

def constrainedMatchPair(firstMatch, secondMatch, length):
    filterMatch1 = ()
    for fM in firstMatch:
        for sM in secondMatch:
            if fM + length + 1 == sM:
                filterMatch1 = filterMatch1 + (fM,)
                break
    return filterMatch1

def subStringMatchOneSub(key,target):
    """search for all locations of key in target, with one substitution"""
    allAnswers = ()
    for miss in range(0,len(key)):
        # miss picks location for missing element
        # key1 and key2 are substrings to match
        key1 = key[:miss]
        key2 = key[miss+1:]
        print('breaking key ' + key + ' into ' + key1 + ' '+ key2)
        # match1 and match2 are tuples of locations of start of matches
        # for each substring in target
        match1 = subStringMatchExact(target,key1)
        match2 = subStringMatchExact(target,key2)
        # when we get here, we have two tuples of start points
        # need to filter pairs to decide which are correct
        filtered = constrainedMatchPair(match1,match2,len(key1))
        allAnswers = allAnswers + filtered
        print('match1: ' + str(match1))
        print('match2: ' + str(match2))
        print('possible matches for ' + key1 +  ' , ' + key2 + ' start at ' + str(filtered))
        print('---------------------')
    return tuple(set(allAnswers))

def subStringMatchExactlyOneSub(target,key):
    exactMatch =  subStringMatchExact(target, key)
    atMostOneMissMatch = subStringMatchOneSub(key,target)
    return tuple(set(atMostOneMissMatch) - set(exactMatch))


# -*- coding: UTF-8 -*-

# Copyright (C) 2012 Hiroki Horiuchi <x19290@gmail.com>
#
# [GNU all-permissive license]
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.

from jchecklib import jcheck
from com.appspot.x19290 import LayeredReplace
from argparse import ArgumentParser
from re import compile as regex, escape
from codecs import open, getwriter
from os.path import join, dirname
from sys import argv, stdout

_default_csv = join(dirname(__file__), 'jcheck.csv')

def main(args):
    args = parse_args(args)
    specs = tuple(get_replace_specs(args.dictionary, get_quote(args)))
    sink = editor_sink if args.in_place else default_sink
    for filename in get_files(args):
        r = LayeredReplace(open(filename, encoding='UTF-8').read())
        for key, repl in specs:
            r = r.replace((key,), repl)
        sink(filename).write(r.getvalue())

def parse_args(args):
    p = ArgumentParser()
    p.add_argument('-d', '--dictionary', default=_default_csv)
    p.add_argument('-q', '--quote', default=u'«»')
    p.add_argument('-i', '--in-place', action='store_true')
    p.add_argument('-l', '--ls')
    p.add_argument('files', nargs='*')
    return p.parse_args(args)

def get_replace_specs(dictfile, quote):
    dict = jcheck(file(dictfile))
    keys = sorted(dict.keys(), lambda x, y: len(y) - len(x))
    def repl(key):
        def fun():
            return quote[0] + key + ':' + '|'.join(dict[key]) + quote[1]
        return fun
    return ((regex(u'(' + escape(key) + u')'), repl(key)) for key in keys)

def get_quote(args):
    quote = args.quote
    if len(quote) == 1:
        got = quote_pairs.get(quote)
        if got == None:
            quote += quote
        else:
            quote = got
    return quote

quote_pairs = {
    u'<': u'<>', u'>': u'<>',
    u'[': u'[]', u']': u'[]',
    u'(': u'()', u')': u'()',
    u'{': u'{}', u'}': u'{}',
    u'«': u'«»', u'»': u'«»',
}

stdout_writer = getwriter('UTF-8')(stdout)
def default_sink(filename__):
    return stdout_writer

def editor_sink(filename):
    return open(filename, encoding='UTF-8', mode='w')

def get_files(args):
    ls = args.ls
    if ls:
        ls = ls.split(',')
        module = ls.pop(0)
        ls = list(__import__(module).impl(*ls))
    else:
        ls = []
    return ls + args.files

if __name__ == '__main__':
    main(argv[1:])


## Polynomial Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
# 这里等级对应的就是不同的职位，两者是等价的；所以并不需要把职位包含在自变量里面
# X must be a matrix
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Splitting the dataset into the Training set and Test set
# 这里不用分割训练集和测试集
"""from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""

# Feature Scaling
# 这里也不用对数据集进行特征缩放
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
# 数据预处理到这儿就完成了

## Fitting Linear Regression to the dataset vs
# 线性回归模型，为了和多项式回归模型形成对比
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

## Fitting Polynomial Regression to the dataset
# 多项式回归模型， 会将自变量转化成，包含自变量不同次方的一个矩阵
from sklearn.preprocessing import PolynomialFeatures
# degree 多项式最高次数
poly_reg = PolynomialFeatures(degree=4)
# 多项式线性回归模型和多元线性回归模型类似，只不过参数是自变量X的不同次项
# 首先创建包含自变量不同次数的多项式矩阵,第0列是常数项
X_poly = poly_reg.fit_transform(X)
# 然后，构建多项式模型，创建方法和线性回归一样
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

## 对比线性回归模型和多项式回归模型的结果
## Visulising the Linear Regression results
plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg.predict(X), color = 'blue')
plt.title('Truth of Bluff (Linear Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

## Visulising the Polynomial Regression results
plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color='blue')
# 使用 poly_reg.fit_transform(X) 更加方便
# plt.plot(X, lin_reg_2.predict(X_poly), color='green')
plt.title('Truth of Bluff (Polyminal Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
# 提高多项式次数可以改进模型的拟合度，这里认为4次得到的模型最好

## 改进模型的平滑度————缩小自变量的间距
# np.arange得到在某一区间平均分布的值 min max sep
X_grid = np.arange(min(X), max(X), 0.1)
# 将X_grid转化成矩阵形式  rows cols
X_grid = X_grid.reshape(len(X_grid), 1)
plt.scatter(X, y, color = 'red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color='blue')
# 使用 poly_reg.fit_transform(X) 更加方便
# plt.plot(X, lin_reg_2.predict(X_poly), color='green')
plt.title('Truth of Bluff (Polyminal Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

## 使用拟合好的模型预测求职者报的实际薪水
# 使用多元线性回归模型预测
res1 = lin_reg.predict([[6.5]]) # >> 330378.78787879

# 使用多项式模型预测
res2 = lin_reg_2.predict(poly_reg.fit_transform([[6.5]])) # >> 158862.45265153

Part 2 - Regression/Section 6 - Polynomial Regression/polynomial_regression_mine.py


from flask import render_template, redirect, url_for, session,request,flash
from Dashboard.conexion import getConnection

def create_cuenta():
    if not session:
        return redirect(url_for('auth.url_login'))

    cuenta = request.form.get('cuenta')
    red_social = request.form.get('red_social')

    bd, connection = getConnection()

    try:
        sql = "INSERT INTO cuentas VALUES (NULL,%s,%s,NULL,NULL)"
        bd.execute(sql, (cuenta,red_social))
        connection.commit()
        bd.close()
        flash(['Cuenta Guardada...', 'bg-success'])
    except Exception as e:
        flash(['Error...' + str(e) + '', 'bg-warning'])

    return redirect(url_for('cuentas.url_cuentas'))


#33. サ変名詞
#サ変接続の名詞をすべて抽出せよ．

import knock30

def extract_san(sentences):
	res=[]
	for sentence in sentences:
		for morpheme in sentence:
			if morpheme['pos']=='名詞' and morpheme['pos1']=='サ変接続':#完全一致必要がある
					res.append(morpheme['surface'])
	return res

if __name__=='__main__':
	inputfile='neko.txt.mecab'
	outputfile='neko.mecab_san.txt'
	f=open(inputfile,'r')
	g=open(outputfile,'w')
	sentences=knock30.mecab_reader(f)
	res=extract_san(sentences)
	for s in res:
		g.write(s+'\n')

	f.close()
	g.close()


import sqlalchemy
import pandas as pd
import pytest
from test_02.etl.load import DataLoader
from test_02.etl.fhir import FHIRDataTransformer

class TestDataLoading(object):

    @pytest.fixture(scope="session", autouse=True)
    def setup_once(self):
        # Setup the database
        pass

    def test_data_loaded(self):
        # Given
        ## Setup
        loader = DataLoader()
        transformer = FHIRDataTransformer()

        # When
        loader.load_data()
        patients = transformer.get_patient_resources()
        encounters = transformer.get_encounter_resources()

        # Then
        assert len(patients) == 4
        assert len(encounters) == 4
        names = set()
        for patient in patients:
            for name in patient["name"]:
                names.add((name["given"], name["family"]))

        assert ("John", "Doe") in names
        # add additional assertions (optional)


def Promedio():
    file = open("Calificaciones.txt", "r")
    lineas = file.readlines()

    #MATRIZ DE CALIFAS
    Alumno1 = ""
    Alumno2 = ""
    CalAlumno1Materia1 = 0.0
    CalAlumno1Materia2 = 0.0
    CalAlumno2Materia1 = 0.0
    CalAlumno2Materia2 = 0.0
    PromAlumno1 = 0.0
    PromAlumno2 = 0.0

    #CHECA QUE EN LA POSICION 0 DE LA LINEA 1 SEA LA LETRA J DE JORGE (NOMBRE)
    for i in lineas:
        if i[0] == "J":
            Alumno1 = i[0]+i[1]+i[2]+i[3]+i[4]+i[5]+i[6]+i[7]+i[8]+i[9]
        else:
            Alumno2 = i[0]+i[1]+i[2]+i[3]+i[4]+i[5]+i[6]+i[7]+i[8]+i[9]+i[10]+i[11]+i[12]+i[13]

    #CHECA EN LA PARTE DE LA MATERIA SI LA POSICION 11 ES Q "QUIMICA" Y M "MATEMATICAS" DEL ALUMNO 1
    for ii in lineas:
        if ii[11] == "q":
            CalAlumno1Materia1 = ii[19]+ii[20]+ii[21]+ii[22]+ii[23]
        if ii[11] == "m":
            CalAlumno1Materia2 = ii[23]+ii[24]+ii[25]+ii[26]+ii[27]

    #CHECA EN LA PARTE DE LA MATERIA SI LA POSICION 15 ES F "FISICA" Y E "ESPAÑOL" DEL ALUMNO 2
    for iii in lineas:
        if iii[15] == "f":
            CalAlumno2Materia1 = iii[22]+iii[23]+iii[24]+iii[25]+iii[26]
        if iii[15] == "e":
            CalAlumno2Materia2 = iii[23]+iii[24]+iii[25]+iii[26]+iii[27]

    #CALCULAMOS PROMEDIO Y CONVERTIMOS LOS STRINGS A FLOATS
    CalAlumno1Materia1 = float(CalAlumno1Materia1)
    CalAlumno1Materia2 = float(CalAlumno1Materia2)
    PromAlumno1 = float(PromAlumno1)
    CalAlumno2Materia1 = float(CalAlumno2Materia1)
    CalAlumno2Materia2 = float(CalAlumno2Materia2)
    PromAlumno2 = float(PromAlumno2)
    PromAlumno1 = (CalAlumno1Materia1 + CalAlumno1Materia2)/2.0
    PromAlumno2 = (CalAlumno2Materia1 + CalAlumno2Materia2)/2.0

    return (f"{Alumno1} {PromAlumno1}" + f"\n{Alumno2} {PromAlumno2}")

def main():
    print(Promedio())

if __name__ == '__main__':
    main()


# Py program to remove duplicate elements from a list.

#empty list
listt = []

num = int(input("\nEnter the num of list elements : "))

for i in range(1, (num + 1)):
    val = int(input("\nEnter list element : "))
    listt.append(val)

print(f"\nList entered is : {listt}")

# set() gives the unique elements from a tuple/list. Further casting/converting it to a list.
new_list = list(set(listt))

print(f"\nAfter duplicate removal, list is : {new_list}")


import argparse
from solver import Solver

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--batch_size', default=128, type=int, help='batch size')
    parser.add_argument('--learning_rate', default=0.01, type=float, help='learning rate')
    parser.add_argument('--num_epochs', default=50, type=int, help='epochs')

    args = parser.parse_args()
    solver = Solver(args)
    solver.solve()


from __future__ import (absolute_import, division, print_function,unicode_literals)

import pandas as pd
from backtrader import feed

from strategy.constance import china_stock_conn

def read_mysql(conn,table_name,stock_name,start_time,end_time):
    df = pd.read_sql('select * from douban', conn)
    df.head()

read_mysql(china_stock_conn,'sh.000001',)

class PandasData(feed.DataBase):
    '''
    The ``dataname`` parameter inherited from ``feed.DataBase`` is the pandas
    DataFrame
    '''

    params = (
        # Possible values for datetime (must always be present)
        #  None : datetime is the "index" in the Pandas Dataframe
        #  -1 : autodetect position or case-wise equal name
        #  >= 0 : numeric index to the colum in the pandas dataframe
        #  string : column name (as index) in the pandas dataframe
        ('datetime', None),

        # Possible values below:
        #  None : column not present
        #  -1 : autodetect position or case-wise equal name
        #  >= 0 : numeric index to the colum in the pandas dataframe
        #  string : column name (as index) in the pandas dataframe
        ('open', -1),
        ('high', -1),
        ('low', -1),
        ('close', -1),
        ('volume', -1),
        ('openinterest', -1),
    )

import argparse

import backtrader as bt

import pandas

def runstrat():

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(bt.Strategy)

    # Get a pandas dataframe
    datapath = ('../../datas/2006-day-001.txt')

    # Simulate the header row isn't there if noheaders requested

    dataframe = pandas.read_csv(datapath,
                                skiprows=skiprows,
                                header=header,
                                parse_dates=True,
                                index_col=0)

    print('--------------------------------------------------')
    print(dataframe)
    print('--------------------------------------------------')

    # Pass it to the backtrader datafeed and add it to the cerebro
    data = bt.feeds.PandasData(dataname=dataframe)

    cerebro.adddata(data)

    # Run over everything
    cerebro.run()

    # Plot the result
    cerebro.plot(style='bar')

if __name__ == '__main__':
    runstrat()


# Runtime: 2.09808349609375e-05 seconds
# Find sum of even fibonacci numbers less than 4 million
import time
start = time.time()

def fibonacci(limiter):
	sum = 0
	a = 0
	b = 1

	while(a < limiter and b < limiter):
		if(a <= b):
			a += b
			if(a >= limiter):
				break
			if(a % 2 == 0):
				sum += a
		else:
			b += a
			if(b >= limiter):
				break
			if(b % 2 == 0):
				sum += b
	return sum

print(fibonacci(4000000))
print(time.time()-start, "seconds")


from docutils.parsers.rst import Directive

from matplotlib import _mathtext, _mathtext_data

symbols = [
    ["Lower-case Greek",
     4,
     (r"\alpha", r"\beta", r"\gamma",  r"\chi", r"\delta", r"\epsilon",
      r"\eta", r"\iota",  r"\kappa", r"\lambda", r"\mu", r"\nu",  r"\omega",
      r"\phi",  r"\pi", r"\psi", r"\rho",  r"\sigma",  r"\tau", r"\theta",
      r"\upsilon", r"\xi", r"\zeta",  r"\digamma", r"\varepsilon", r"\varkappa",
      r"\varphi", r"\varpi", r"\varrho", r"\varsigma",  r"\vartheta")],
    ["Upper-case Greek",
     4,
     (r"\Delta", r"\Gamma", r"\Lambda", r"\Omega", r"\Phi", r"\Pi", r"\Psi",
      r"\Sigma", r"\Theta", r"\Upsilon", r"\Xi")],
    ["Hebrew",
     6,
     (r"\aleph", r"\beth", r"\gimel", r"\daleth")],
    ["Delimiters",
     5,
     _mathtext.Parser._delims],
    ["Big symbols",
     5,
     _mathtext.Parser._overunder_symbols | _mathtext.Parser._dropsub_symbols],
    ["Standard function names",
     5,
     {fr"\{fn}" for fn in _mathtext.Parser._function_names}],
    ["Binary operation and relation symbols",
     4,
     r"""\ast \pm \slash \cap \star \mp \cup \cdot \uplus
     \triangleleft \circ \odot \sqcap \triangleright \bullet \ominus
     \sqcup \bigcirc \oplus \wedge \diamond \oslash \vee
     \bigtriangledown \times \otimes \dag \bigtriangleup \div \wr
     \ddag \barwedge \veebar \boxplus \curlywedge \curlyvee \boxminus
     \Cap \Cup \boxtimes \bot \top \dotplus \boxdot \intercal
     \rightthreetimes \divideontimes \leftthreetimes \equiv \leq \geq
     \perp \cong \prec \succ \mid \neq \preceq \succeq \parallel \sim
     \ll \gg \bowtie \simeq \subset \supset \Join \approx \subseteq
     \supseteq \ltimes \asymp \sqsubset \sqsupset \rtimes \doteq
     \sqsubseteq \sqsupseteq \smile \propto \dashv \vdash \frown
     \models \in \ni \notin \approxeq \leqq \geqq \lessgtr \leqslant
     \geqslant \lesseqgtr \backsim \lessapprox \gtrapprox \lesseqqgtr
     \backsimeq \lll \ggg \gtreqqless \triangleq \lessdot \gtrdot
     \gtreqless \circeq \lesssim \gtrsim \gtrless \bumpeq \eqslantless
     \eqslantgtr \backepsilon \Bumpeq \precsim \succsim \between
     \doteqdot \precapprox \succapprox \pitchfork \Subset \Supset
     \fallingdotseq \subseteqq \supseteqq \risingdotseq \sqsubset
     \sqsupset \varpropto \preccurlyeq \succcurlyeq \Vdash \therefore
     \curlyeqprec \curlyeqsucc \vDash \because \blacktriangleleft
     \blacktriangleright \Vvdash \eqcirc \trianglelefteq
     \trianglerighteq \neq \vartriangleleft \vartriangleright \ncong
     \nleq \ngeq \nsubseteq \nmid \nsupseteq \nparallel \nless \ngtr
     \nprec \nsucc \subsetneq \nsim \supsetneq \nVDash \precnapprox
     \succnapprox \subsetneqq \nvDash \precnsim \succnsim \supsetneqq
     \nvdash \lnapprox \gnapprox \ntriangleleft \ntrianglelefteq
     \lneqq \gneqq \ntriangleright \lnsim \gnsim \ntrianglerighteq
     \coloneq \eqsim \nequiv \napprox \nsupset \doublebarwedge \nVdash
     \Doteq \nsubset \eqcolon \ne
     """.split()],
    ["Arrow symbols",
     4,
     r"""\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow
     \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow
     \Longrightarrow \Downarrow \leftrightarrow \updownarrow
     \longleftrightarrow \updownarrow \Leftrightarrow
     \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow
     \hookleftarrow \hookrightarrow \searrow \leftharpoonup
     \rightharpoonup \swarrow \leftharpoondown \rightharpoondown
     \nwarrow \rightleftharpoons \leadsto \dashrightarrow
     \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow
     \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft
     \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh
     \upuparrows \upharpoonleft \downharpoonleft \multimap
     \leftrightsquigarrow \rightrightarrows \rightleftarrows
     \rightrightarrows \rightleftarrows \twoheadrightarrow
     \rightarrowtail \looparrowright \rightleftharpoons
     \curvearrowright \circlearrowright \Rsh \downdownarrows
     \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow
     \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow
     \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow
     \leftsquigarrow
     """.split()],
    ["Miscellaneous symbols",
     4,
     r"""\neg \infty \forall \wp \exists \bigstar \angle \partial
     \nexists \measuredangle \eth \emptyset \sphericalangle \clubsuit
     \varnothing \complement \diamondsuit \imath \Finv \triangledown
     \heartsuit \jmath \Game \spadesuit \ell \hbar \vartriangle \cdots
     \hslash \vdots \blacksquare \ldots \blacktriangle \ddots \sharp
     \prime \blacktriangledown \Im \flat \backprime \Re \natural
     \circledS \P \copyright \ss \circledR \S \yen \AA \checkmark \$
     \cent \triangle \QED \sinewave \nabla \mho""".split()]
]

def run(state_machine):

    def render_symbol(sym, ignore_variant=False):
        if ignore_variant and sym != r"\varnothing":
            sym = sym.replace(r"\var", "\\")
        if sym.startswith("\\"):
            sym = sym.lstrip("\\")
            if sym not in (_mathtext.Parser._overunder_functions |
                           _mathtext.Parser._function_names):
                sym = chr(_mathtext_data.tex2uni[sym])
        return f'\\{sym}' if sym in ('\\', '|') else sym

    lines = []
    for category, columns, syms in symbols:
        syms = sorted(syms,
                      # Sort by Unicode and place variants immediately
                      # after standard versions.
                      key=lambda sym: (render_symbol(sym, ignore_variant=True),
                                       sym.startswith(r"\var")),
                      reverse=(category == "Hebrew"))  # Hebrew is rtl
        rendered_syms = [f"{render_symbol(sym)} ``{sym}``" for sym in syms]
        columns = min(columns, len(syms))
        lines.append("**%s**" % category)
        lines.append('')
        max_width = max(map(len, rendered_syms))
        header = (('=' * max_width) + ' ') * columns
        lines.append(header.rstrip())
        for part in range(0, len(rendered_syms), columns):
            row = " ".join(
                sym.rjust(max_width) for sym in rendered_syms[part:part + columns])
            lines.append(row)
        lines.append(header.rstrip())
        lines.append('')

    state_machine.insert_input(lines, "Symbol table")
    return []

class MathSymbolTableDirective(Directive):
    has_content = False
    required_arguments = 0
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {}

    def run(self):
        return run(self.state_machine)

def setup(app):
    app.add_directive("math_symbol_table", MathSymbolTableDirective)

    metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
    return metadata

if __name__ == "__main__":
    # Do some verification of the tables

    print("SYMBOLS NOT IN STIX:")
    all_symbols = {}
    for category, columns, syms in symbols:
        if category == "Standard Function Names":
            continue
        for sym in syms:
            if len(sym) > 1:
                all_symbols[sym[1:]] = None
                if sym[1:] not in _mathtext_data.tex2uni:
                    print(sym)

    print("SYMBOLS NOT IN TABLE:")
    for sym in _mathtext_data.tex2uni:
        if sym not in all_symbols:
            print(sym)


#!/usr/bin/python3

##############################################################################################
## Company: FSAE Lafayette College
## Engineers:Harrison Walker, Adam Tunnell, Lia Chrysanthopoulos, Mithil Shah,Irwin Frimpong
## Last Updated : 05/23/2021
## Project Name: SCADA FSAE 2021
## Module Name: can_scan.py
## Description: This script is meant to detect and display info for all available nodes
## currently on the CAN bus for CAN bus debug purposes
#############################################################################################

import sys, os
import time
import canopen

#Importing the config file
lib_path = '/usr/etc/scada'
config_path = '/usr/etc/scada/config'
#this is temporary, just for testing
local_path = '../utils'

sys.path.append(lib_path)
sys.path.append(config_path)
sys.path.append(local_path)

from drivers import can_driver

#invoke the CAN Driver to set up the CAN network
cd = can_driver.CanDriver()
network = cd.network

os.system('sudo ifconfig can0 txqueuelen 1000')
#ensure nodes are connected
network.scanner.search()
time.sleep(1)
print("Connected Nodes:")
for node_id in network.scanner.nodes:
    print("Found node %d!" % node_id)
    print('NODE %d INFORMATION:' % node_id)
    node = network[node_id]
    for obj in node.object_dictionary.values():
        print('0x%X: %s' % (obj.index, obj.name))
        if isinstance(obj, canopen.objectdictionary.Record):
            for subobj in obj.values():
                print('  %d: %s' % (subobj.subindex, subobj.name))


from django.contrib import admin
from .models import Predmet, Tema, Poraka, Korisnik, Profesor, Prostorija, Termin, UserTermin
# Register your models here.

class PredmetAdmin(admin.ModelAdmin):
    list_display = ('naslov', 'naslov_id')

class TemaAdmin(admin.ModelAdmin):
    list_display = ('naslov', 'predmet', 'avtor')

class PorakaAdmin(admin.ModelAdmin):
    list_display = ('tekst', 'avtor', 'tema', 'timestamp')

class UserTerminInline(admin.StackedInline):
    model = UserTermin
    extra = 1

class KorisnikAdmin(admin.ModelAdmin):
    inlines = [UserTerminInline]

class TerminAdmin(admin.ModelAdmin):
    list_display = ('id', 'predmet', 'profesor', 'prostorija', 'vreme', 'den', 'casovi')

admin.site.register(Predmet, PredmetAdmin)
admin.site.register(Tema, TemaAdmin)
admin.site.register(Poraka, PorakaAdmin)
admin.site.register(Korisnik, KorisnikAdmin)
admin.site.register(Profesor)
admin.site.register(Prostorija)
admin.site.register(Termin, TerminAdmin)


import tkinter as tk

def selecting_movie(df):
    mov = []
    movies_titles = df['movie title']
    # Create the root window
    root = tk.Tk()
    root.title("List of Movies")
    root.geometry('500x500')
    scrollbar = tk.Scrollbar(root)
    scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH)

    # Create a listbox
    listbox = tk.Listbox(root, width=100, height=200, selectmode=tk.SINGLE)
    listbox.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=listbox.yview)

    # Inserting the listbox items
    for item in movies_titles:
        listbox.insert(tk.END, item)

    # Function for printing the
    # selected listbox value(s)

    def selected_item():
        # Traverse the tuple returned by
        # curselection method and print
        # correspoding value(s) in the listbox

        for i in listbox.curselection():
            mov.append(listbox.get(i))
            root.quit()
            # return listbox.get(i)

    # Create a button widget and
    # map the command parameter to
    # selected_item function
    btn = tk.Button(root, text='Select Movie', command=selected_item)

    # Placing the button and listbox
    btn.pack(side='bottom')
    listbox.pack()
    root.mainloop()
    return mov[0]


'''
Sample Input 0

5 10 3
2 3 4 1 5
1 3 2 4 5
Sample Output 0

250
n, m, k where
n is the number of currencies excluding bitcoin,
m is the amount of bitcoins Ron has and
k is the conversion rate of bitcoin w.r.t dollar.
'''
nos_currency, nos_btcoin, dollar_per_btcoin = [int(x) for x in input().split()]
price_other = [int(x) for x in input().split()]
btcoin_multiple = [int(x) for x in input().split()]
max_value = nos_btcoin * dollar_per_btcoin
for i, v in enumerate(price_other):
    max_value = max(max_value, (nos_btcoin * btcoin_multiple[i] * v))
print(max_value)


import unittest

from src.generator_ada_project import Generator_Ada_Project
from src.dsl_grammar import parse_input
from src.template_engine import Template_Engine

from src.utils import (
    directory,
    rmdir,
    dir_exists,
    text_files_match,
)

class Test_Project_Nominal(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print(__class__)
        filename = "~/workspace/code_generator_py/tests/test_001/test_001.dsl"
        cls.project = parse_input(filename)

        template_dir = directory("~/workspace/code_generator_py/tests/test_001")
        template_engine = Template_Engine(template_directory = template_dir)
        generator = Generator_Ada_Project(template_engine)
        generator.output(cls.project)

    @classmethod
    def tearDownClass(cls):
        rmdir("~/tests")

    def test_field_name(self):
        print(__name__)
        self.assertEqual(Test_Project_Nominal.project.name,
                         "test_001",
                         "project name")

    def test_field_output_directory(self):
        self.assertEqual(Test_Project_Nominal.project._output_directory,
                         directory("~/tests/test_001"),
                         "output directory")

    def test_field_title(self):
        self.assertEqual(Test_Project_Nominal.project._title,
                         "test 001 title",
                         "project title")

    def test_field_brief(self):
        self.assertEqual(Test_Project_Nominal.project._brief,
                         "test 001 brief",
                         "project brief")

    def _setdown(self):
        super()._setdown()

    def _build_test_list(self):
        for test in (
                check_project,
                check_prj_dir,
                check_src_dir,
                check_gpr_file,
        ):
            self._add_test(test)

    def get_project(self):
        return self.__project


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

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Pango as pango

from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FC
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NT

# https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/subplots_demo.html
class PlotWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='Example Plot')
        self.set_icon_from_file("resources/CyberSolver_Icon.png")
        self.connect('destroy', Gtk.main_quit)

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

#fig.savefig("test.png")

main = PlotWindow()
main.set_title("Example Plot")
main.set_default_size(800,600)
box = Gtk.VBox()
main.add(box)

fc = FC(fig)
box.pack_start(fc, expand=True, fill=True, padding=False)
nt = NT(fc, main)
box.pack_start(nt, expand=False, fill=False, padding=False)
main.show_all()
Gtk.main()

#plt.show()


from eve import Eve
from flask import json, Response
import platform, psutil

app = Eve()

@app.route('/api/v1.0/status', methods=['GET'])
def status():
    """ Endpoint that returns a status message. """

    data = {'status': 'OK'}

    packet = json.dumps(data)
    resp = Response(packet, status=200, mimetype='application/json')

    return (resp)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)


from setuptools import setup

# For more information about uploading the python package to PyPI, please check the link:
# https://github.com/judy2k/publishing_python_packages_talk

# Use README.md as the long description
with open('README.md', encoding='utf-8') as f:
    long_description = f.read()

VERSION = "0.0.6"

if __name__ == '__main__':
    setup(
        name="mdr-library",
        version=VERSION,
        author="Kanishka Sharma, Joao Almeida e Sousa and Steven Sourbron",
        author_email="kanishka.sharma@sheffield.ac.uk, j.g.sousa@sheffield.ac.uk, s.sourbron@sheffield.ac.uk",
        description="Open-source, platform independent library for Model Driven Registration (MDR) in quantitative renal MRI",
        long_description=long_description,
        long_description_content_type="text/markdown",
        url="https://github.com/QIB-Sheffield/MDR-Library",
        license='Apache Software License (http://www.apache.org/licenses/LICENSE-2.0)',
        python_requires='>=3.6, <4',
        packages=['MDR'],
        install_requires=["numpy", "pandas", "SimpleITK", "itk-elastix"],
        include_package_data=True,
        keywords=['python', "medical imaging", "DICOM", "MRI", "renal", "kidney", "motion correction", "registration"],
        # Classifiers - the purpose is to create a wheel and upload it to PYPI
        classifiers=[
            # How mature is this project? Common values are
            #   3 - Alpha
            #   4 - Beta
            #   5 - Production/Stable
            'Development Status :: 3 - Alpha',

            # Indicate who your project is intended for
            'Intended Audience :: Developers',
            'Intended Audience :: Science/Research',
            'Topic :: Scientific/Engineering',
            'Environment :: Console',
            'Operating System :: OS Independent',

            'Programming Language :: Python :: 3',
            # Specify the Python versions you support here. In particular, ensure
            # that you indicate you support Python 3. These classifiers are *not*
            # checked by 'pip install'. See instead 'python_requires' below.
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',

            # Pick your license as you wish
            'License :: OSI Approved :: Apache Software License',
        ],
    )


#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""Fixtures for Glance unit tests."""
# NOTE(mriedem): This is needed for importing from fixtures.
from __future__ import absolute_import

import warnings

import fixtures as pyfixtures

class WarningsFixture(pyfixtures.Fixture):
    """Filters out warnings during test runs."""

    def setUp(self):
        super(WarningsFixture, self).setUp()
        # NOTE(sdague): Make deprecation warnings only happen once. Otherwise
        # this gets kind of crazy given the way that upstream python libs use
        # this.
        warnings.simplefilter('once', DeprecationWarning)

        # NOTE(sdague): this remains an unresolved item around the way
        # forward on is_admin, the deprecation is definitely really premature.
        warnings.filterwarnings(
            'ignore',
            message='Policy enforcement is depending on the value of is_admin.'
                    ' This key is deprecated. Please update your policy '
                    'file to use the standard policy values.')

        self.addCleanup(warnings.resetwarnings)


from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.template.defaultfilters import slugify
import itertools

class Address(models.Model):
	slug = models.SlugField(verbose_name=_('slug'), max_length=255, blank=True, unique=True)
	user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User"), related_name="user_address")
	cep = models.CharField(verbose_name=_("CEP"), max_length=255, null=True, blank=True)
	address = models.CharField(verbose_name=_("Address"), max_length=255, null=True, blank=True)
	number = models.IntegerField(verbose_name=_("Number"), null=True, blank=True)
	quarter = models.CharField(verbose_name=_("Quarter"), max_length=255, null=True, blank=True)
	city = models.CharField(verbose_name=_("City"), max_length=255, null=True, blank=True)
	state = models.CharField(verbose_name=_("State"), max_length=255, null=True, blank=True)

	def get_search_fields():
		return (
			("cep", _("Cep")),
			("address", _("Address")),
			("quarter", _("Quarter")),
			("city", _("City")),
			("state", _("State")),
		)

	get_search_fields = staticmethod(get_search_fields)

	def save(self, *args, **kwargs):
		if not self.id:
			self.slug = orig = slugify("%s-%s-%s-%s" % (self.address, self.quarter, self.city, self.state) )
			for x in itertools.count(1):
				if not Address.objects.filter(slug=self.slug).exists():
					break
				self.slug = "%s-%d" % (orig, x)
		super(Address, self).save(*args, **kwargs)

	def __unicode__(self):
		return unicode(self.address) + "-" + unicode(self.number) + "-" + unicode(self.quarter) + "-" + unicode(self.city) + "-" + unicode(self.state)

	def natural_key(self):
		return self.__unicode__()

	def verbose_name(self):
		return self._meta.verbose_name

	class Meta:
		ordering = ['-cep']
		verbose_name = _(u'Address')
		verbose_name_plural = _(u'Address')


print ("Hello world")

import random

class Card:
  def __init__(self, suit, val):
    self.suit = suit
    self.value = val

  def show(self):
    print ("{} of {}".format(self.value, self.suit))

class Deck:
  def __init__(self):
    self.cards = []
    self.build()

  def build(self):
    for s in ["Hearts", "Spades", "Diamonds", "Clubs"]:
      for v in range(1,14):
        self.cards.append(Card(s,v))

  def show(self):
    for c in self.cards:
      c.show()

  def shuffle(self): # Fisher-Yates shuffle algorithm
    for i in range(len(self.cards)-1,0,-1):
      r = random.randint(0,i)
      self.cards[i], self.cards[r] = self.cards[r], self.cards[i]

  def drawCard(self):
    return self.cards.pop() # draw from top of card stack

class Player:
  def __init__(self, name):
    self.name = name
    self.hand = []

  def draw(self, deck):
    self.hand.append(deck.drawCard())
    return self

  def showHand(self):
    for card in self.hand:
      card.show()

class Game:
  def __init__(self):
    self.deck = Deck()
    self.deck.shuffle()
    self.table = []
    self.burnPile = []

  def newDeck(self):
    self.deck = Deck()
    self.deck.shuffle()
    self.table = []
    self.burnPile = []

  def burn(self):
    self.burnPile.append(self.deck.drawCard())

  def drawFlop(self):
    self.burn()
    for i in range(0,3):
      self.table.append(self.deck.drawCard())

  def showTable(self):
    for card in self.table:
      card.show()

  def pairsGame(self):
    self.newDeck()
    me = Player("Me")
    opponent = Player("Opponent")

    num_pairs = 0
    num_hands = 0
    identified_pairs = 0
    while True:
      me.draw(self.deck)
      opponent.draw(self.deck)
      me.draw(self.deck)
      opponent.draw(self.deck)

      self.drawFlop()
      print("Flop: ")
      self.showTable()
      print(" ")
      print("Opponent's hand: ")
      opponent.showHand()
      print(" ")
      print("My hand: ")
      me.showHand()
      num_pairs, num_hands = self.askPairsQuestion(num_pairs, num_hands)
      identified_pairs += self.checkForPairs(me.hand,self.table)
      print('Computed number of pairs: {0:2d}'.format(identified_pairs))
      print(" ")
      self.deck = Deck()
      self.deck.shuffle()
      self.table = []
      self.burnPile = []
      me.hand = []

  def twoPlayerPairsGame(self):
    self.newDeck()
    me = Player("Me")
    opponent = Player("Opponent")

    num_wins = 0
    num_hands = 0
    num_losses = 0
    while True:

      me.draw(self.deck)
      opponent.draw(self.deck)
      me.draw(self.deck)
      opponent.draw(self.deck)

      self.drawFlop()
      print("Flop: ")
      self.showTable()
      print(" ")
      print("Opponent's hand: ")
      opponent.showHand()
      print(" ")
      print("My hand: ")
      me.showHand()

      num_wins, num_losses, num_hands = self.askTwoPlayerPairsQuestion(num_wins, num_losses, num_hands)
      print(" ")
      self.deck = Deck()
      self.deck.shuffle()
      self.table = []
      self.burnPile = []
      me.hand = []
      opponent.hand = []

  def askSinglePlayerPairsQuestion(self, num_pairs, num_hands): # statistics should not be kept here
    num_pairs += input("Number of pairs I hit on this hand: ")
    num_hands += 1

    print(" ")

    print('Total games: {0:2d}'.format(num_hands))
    print('Total pairs: {0:2d}'.format(num_pairs))

    return num_pairs, num_hands

  def askTwoPlayerPairsQuestion(self, num_wins, num_losses, num_hands): # statistics should not be kept here
    def tie():
      return num_hands + 1, num_wins, num_losses
    def win():
      return num_hands + 1, num_wins + 1, num_losses
    def loss():
      return num_hands + 1, num_wins, num_losses + 1

    switcher = {
      0: tie,
      1: win,
      2: loss
    }

    num_hands, num_wins, num_losses = switcher.get(input("Who has the higher pair? (tie = 0, me = 1, opponent = 2) : "), "nothing")()

    print(" ")

    print('Total games: {0:2d}'.format(num_hands))
    print('Total number of wins: {0:2d}'.format(num_wins))
    print('Total number of losses: {0:2d}'.format(num_losses))

    return num_wins, num_losses, num_hands

  def checkForPairs(self, hand, table):

    table_values = []
    for card in table:
      table_values.append(card.value)

    for card in hand:
      if card.value in table_values:
        return True # a pair is found on the table

    if hand[0].value == hand[1].value:
      return True # the player is holding a pair

    return False # no pairs were found

def main():
  game = Game()
  game.twoPlayerPairsGame()

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
## @package tigropy
#  LXC-container controller script.
#
#  This script is a part of TIGRO project.
#  Module contain classes and function for create and control LXC-containers.
from tigro.hostnode import HostNode
import logging

logging.basicConfig(
        format = u'%(levelname)-8s [%(asctime)s] %(name)-15s > %(message)s',
        level = logging.INFO)

if __name__ == '__main__':
    hn = HostNode()
    hn.start()
    hn.join()


import os
import sys
import hashlib
import json
from copy import deepcopy
from time import monotonic
import core.simulate
from conf import ROOT_DIR, load_equip_json, load_adv_json
from core.simulate import CHART_DIR, DURATION_LIST, QUICK_LIST_FILES, SLOW_LIST_FILES, ADV_LIST_FILES

ADV_DIR = 'adv'

import hashlib

def sha256sum(filename):
    if not os.path.exists(filename):
        return None
    h = hashlib.sha256()
    b = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

def sim_adv(adv_file, special=None, mass=None, sanity_test=False):
    t_start = monotonic()

    adv_file = os.path.basename(adv_file)
    if adv_file.endswith('.py'):
        adv_name = adv_file.split('.')[0]
    else:
        adv_name = adv_file
        adv_file += '.py'
    adv_file = adv_file.lower()
    if special is None and adv_file.count('.py') > 1:
        special == True

    sha_before = None

    verbose = -5
    durations = DURATION_LIST
    if special:
        durations = [180]
    if sanity_test:
        mass = None
        durations = [30]
        output = open(os.devnull, 'w')
    else:
        output_path = os.path.join(ROOT_DIR, CHART_DIR, 'chara', '{}.csv'.format(adv_file))
        sha_before = sha256sum(output_path)
        output = open(output_path, 'w', encoding='utf8')

    try:
        adv_module = core.simulate.load_adv_module(adv_name)
    except Exception as e:
        print(f'\033[93m{monotonic()-t_start:.4f}s - sim:{adv_file} {e}\033[0m', flush=True)
        output.close()
        return
    try:
        for d in durations:
            run_results = core.simulate.test(adv_module, {}, duration=d, verbose=verbose, mass=1000 if mass else None, special=special, output=output)
        if not sanity_test:
            print('{:.4f}s - sim:{}'.format(monotonic() - t_start, adv_file), flush=True)
    except Exception as e:
        print(f'\033[91m{monotonic()-t_start:.4f}s - sim:{adv_file} {e}\033[0m', flush=True)
        output.close()
        return
    output.close()
    if sha_before is not None and sha_before != sha256sum(output_path):
        return run_results[0][0].slots.c.icon
    else:
        return None

def run_and_save(adv_module, ele, dkey, ekey, conf, repair=False):
    if ekey == 'affliction':
        aff_name = core.simulate.ELE_AFFLICT[ele]
        conf[f'sim_afflict.{aff_name}'] = 1
    with open(os.devnull, 'w') as output:
        run_res = core.simulate.test(adv_module, conf, duration=int(dkey), verbose=0, output=output)
        core.simulate.save_equip(run_res[0][0], run_res[0][1], repair=repair, etype=ekey)

EQUIP_KEYS = ['base', 'buffer', 'affliction']
def repair_equips(adv_file):
    t_start = monotonic()
    try:
        adv_file = os.path.basename(adv_file)
        adv_name = adv_file
        if adv_file.endswith('.py'):
            adv_name = adv_file.split('.')[0]
        adv_module = core.simulate.load_adv_module(adv_name)
        adv_name = adv_module.__name__
        adv_ele = load_adv_json(adv_name)['c']['ele']
        adv_equip = deepcopy(load_equip_json(adv_name))

        eleaff = None
        for dkey, equip_d in adv_equip.items():
            pref = equip_d.get('pref', 'base')
            for ekey, conf in equip_d.items():
                if ekey == 'pref':
                    continue
                run_and_save(adv_module, adv_ele, dkey, ekey, conf, repair=True)
                # if affliction, check if base equip actually better
                if ekey == 'affliction':
                    try:
                        run_and_save(adv_module, adv_ele, dkey, ekey, equip_d['base'])
                    except KeyError:
                        pass
                # check if 180 equip is actually better for 120/60
                if dkey == '180':
                    continue
                try:
                    run_and_save(adv_module, adv_ele, dkey, ekey, adv_equip['180'][ekey])
                except KeyError:
                    pass
    except Exception as e:
        print(f'\033[91m{monotonic()-t_start:.4f}s - repair:{adv_file} {e}\033[0m', flush=True)
        return
    print('{:.4f}s - repair:{}'.format(monotonic() - t_start, adv_file), flush=True)

def sim_adv_list(list_file, sanity_test=False, repair=False):
    special = list_file.startswith('chara_sp')
    mass = list_file.endswith('slow.txt') and not special
    message = []
    with open(os.path.join(ROOT_DIR, list_file), encoding='utf8') as f:
        sorted_f = list(sorted(f))
    for adv_file in sorted_f:
        if repair:
            repair_equips(adv_file.strip())
        else:
            msg = sim_adv(adv_file.strip(), special, mass, sanity_test)
            if msg:
                message.append(msg)
    with open(os.path.join(ROOT_DIR, list_file), 'w', encoding='utf8') as f:
        for adv_file in sorted_f:
            f.write(adv_file.strip())
            f.write('\n')
    return message

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('USAGE python {} sim_targets [-c] [-sp]'.format(sys.argv[0]))
        exit(1)
    t_start = monotonic()

    arguments = sys.argv.copy()[1:]
    do_combine = False
    is_special = None
    is_mass = None
    is_repair = False
    sanity_test = False
    if '-c' in arguments:
        do_combine = True
        arguments.remove('-c')
    if '-sp' in arguments:
        is_special = True
        arguments.remove('-sp')
    if '-m' in arguments:
        is_mass = True
        arguments.remove('-m')
    if '-san' in arguments:
        sanity_test = True
    if '-rp' in arguments:
        arguments.remove('-rp')
        is_repair = True

    sim_targets = arguments

    if sanity_test or 'all' in sim_targets:
        list_files = ADV_LIST_FILES
    elif 'quick' in sim_targets:
        list_files = QUICK_LIST_FILES if not is_repair else ['chara_quick.txt']
    elif 'slow' in sim_targets:
        list_files = SLOW_LIST_FILES if not is_repair else ['chara_slow.txt']
    else:
        list_files = None
        sim_targets = [a for a in sim_targets if not a.startswith('-')]

    message = []
    if list_files is not None:
        do_combine = True
        for list_file in list_files:
            message.extend(sim_adv_list(list_file, sanity_test=sanity_test, repair=is_repair))
    else:
        for adv_file in sim_targets:
            if is_repair:
                repair_equips(adv_file)
            else:
                msg = sim_adv(adv_file, special=is_special, mass=is_mass, sanity_test=sanity_test)
                if msg:
                    message.append(msg)

    if not sanity_test:
        with open(os.path.join(ROOT_DIR, CHART_DIR, 'page/lastmodified.json'), 'r+') as f:
            try:
                lastmod = json.load(f)
            except:
                lastmod = {}
            f.truncate(0)
            f.seek(0)
            try:
                lastmod['changed'].extend(message)
            except KeyError:
                lastmod['changed'] = message
            json.dump(lastmod, f)

    if do_combine and not sanity_test:
        core.simulate.combine()

    print('total: {:.4f}s'.format(monotonic() - t_start))


import pickle

filename = 'imgs_skipped_1.pkl'
with open(filename, 'rb') as f:
    data = pickle.load(f)

def convert_path(path):
    s = path.split('/')[4:]
    s = ['', 'home', 'wilson', 'causal-infogan', 'data'] + s
    s = '/'.join(s)
    return s

new_data = list()
for d in data:
    (s1, i1), (s2, i2) = d
    s1, s2 = convert_path(s1), convert_path(s2)
    new_data.append(((s1, i1), (s2, i2)))

with open(filename, 'wb') as f:
    pickle.dump(new_data, f)


from sklearn.neural_network import MLPRegressor
import numpy as np

def ANN_train(timeseries, q, hidden_layers, alpha=1e-5, random_state=1):
    '''
    INPUT:
    timeseries: TYPE: DataFrame. Contains column named 'residual'
    q: TYPE: Integer. Decides how many historical values to consider
    hidden_layers: TYPE: Tuple of integers. The number on the i'th position decides number of nodes in hidden layer i

    OUTPUT:
    Returns trained model: TYPE: MLPRegressor
    '''
    X = np.array([timeseries['residual'].iloc[i:i+q]
                  for i in range(len(timeseries['residual'])-q)])
    y = timeseries['residual'].iloc[q:].values
    model = MLPRegressor(solver="lbfgs", alpha=alpha,
                         hidden_layer_sizes=hidden_layers, random_state=random_state)
    model.fit(X, y)
    return model


# Author: Brahim Belaoucha <>
import numpy as np
import os
import shutil
import random
from scipy.sparse import coo_matrix
from joblib import load
from . import linear_model
def _constructJt(Jt):
    n_s, m_p = Jt.shape
    jx = np.zeros((n_s, n_s**2*m_p))
    for i in range(n_s):
        jx[i, i*(n_s*m_p):(i+1)*n_s*m_p] = Jt.reshape(-1, order='F')
    return jx

def construct_J(G, SC, J, m_p, old=False):
    """
    This function build the transfer function between the MAR model
    coefficients and the EEG/MEG data (or brain activation at t sample
    when using old version)
    Parameters:
    -----------
    G:  (nbr_channels, nbr_sourcesxm_p)The gain matrix
    SC: (nbr_sources, nbr_sources)The structural connectivity
    J:  (nbr_sources, nbr_samples + m_p -1)The brain activation in a time window
    m_p: The MAR model order
    old: flag to use old iSDR version of the new one

    Return:
    -----------
    data_big: matrix that transfer MAR model to M or J(old==True)
    old = False:
        M_v = data_big x A_v
    old = True:
        J_v = data_big x A_v
    idx:  The MAR coefficients that can be non-zero, obtained from SC
    """
    n_s, n_t = J.shape
    n_m, n = G.shape
    if n != n_s:
        print('wrong dimenstion')
    SCx = np.zeros((n_s, n_s*m_p))
    if SC.shape[0] == SC.shape[1]:
        for i in range(m_p):
            SCx[:, i*n_s:(i+1)*n_s] = SC
    else:
        SCx = SC.copy()
    SCx = SCx.reshape(-1, order='C')
    idx = SCx > 0
    if old:
        n_m = n_s
    m = n_t-m_p+1
    data_big = np.zeros((m*n_m, np.sum(idx)), dtype=np.float)
    for t in range(m):
        data_x = _constructJt(J[:, t:t+m_p])[:, idx]
        if not old:
            data_x = np.dot(G, data_x)
        data_big[t*n_m:(t+1)*n_m, :] = data_x
    return data_big, idx

def Compute_alpha_max(Ga, M, model_p):
    """
    This function compute the alpha max which is the smallest regularization
    parameter alpha that results to no active brain region when using
    l21 mixed norm (MxNE)

    Parameters:
    ----------
        Ga: GxA where G is the gain matrix and A is the MAR model
        M: The EEG or MEG measurements
        model_p: The order of the MAR model

    Return:
    ---------
    alpha_max: the regularization value that results to no active brain
              region
    """
    _, n_s = Ga.shape
    n_s = n_s//model_p
    GM = np.zeros((M.shape[1]*model_p, n_s))
    alpha_max = 0
    for i in range(n_s):
        for j in range(model_p):
            Ax = np.dot(M.T, Ga[:, j*n_s + i])
            GM[j*M.shape[1]:(j+1)*M.shape[1], i] = Ax
    alpha_max = np.sqrt(np.sum(np.power(GM, 2, GM), axis=0))
    return np.max(alpha_max)

def createfolder(foldername):
    """
    this function creates a folder
    """
    try:
        os.mkdir(foldername)
    except OSError:
        print ("Creation of the directory %s failed" % foldername)
    else:
        print ("Successfully created the directory %s " % foldername)

def deletefolder(foldername):
    """
    this function deletes a folder
    """
    try:
        shutil.rmtree(foldername, ignore_errors=True)
    except OSError:
        print ("Deletion of the directory %s failed" % foldername)
    else:
        print ("Successfully deleted the directory %s" % foldername)

def create_bigG(G, A, M):

    """
    This function is used when running bias correction and build the
    the following matrix:
            ---                                        ---
            | G_p, G_p-1, ...., G_1, 0, ...........   0  |
            |  0 ,  G_p, .......G_2,G_1,0 .......        |
            |  .                                         |
    bigG =  |  .                                         |
            |  .                                         |
            |  .                                         |
            |  0 , ......................., G_p, ..., G_1|
            ---                                        ---
    Where M_v = bigG x J_v
          M_v: is the vec form of EEG/MEG measurement M
          J_v: is the vec form of the reconstructed brain activation J
          G: the gain matrix
          A_i: the ith MAR model
          p: the order of MAR model
          G_i = GxA_i
    """
    GA = np.dot(G, A)
    n_c , n_t  = M.shape
    _ , n_s = G.shape
    m_p = A.shape[1]//n_s
    row  = []
    col  = []
    data = []
    for i in range(n_t):
        for j in range(n_c):
            row.append([j+n_c*i]*n_s*m_p)
            col.append([n_s*i+k for k in range(n_s*m_p)])
            data.append(GA[j, :])
    data = np.array(data).reshape(-1)
    row = np.array(row).reshape(-1)
    col = np.array(col).reshape(-1)
    return coo_matrix((data, (row, col)), shape=(n_t*n_c, n_s*(n_t + m_p - 1)))

def _run(args):

    """
    The core function used to run the cross validation
    Parameters:
    ----------
    l21_reg:    regularization of l21 norm (Sstep) , 0<values<100
    la:         regularization of l1 and l2 norm (Astep)
    la_ratio:   regularization of l1 and l2 norm (Astep)
    m_p:        MAR model order
    normalize:  Normalize A_i's before Sstep or not
    foldername: Folder where to find:
                    M.dat: EEG/MEG data
                    G.dat: gain matix
                    SC.dat:    structral connectivity
                    A.dat: Initial MAR model, if not None is passed
    o_v:        flag to used old version iSDR or not
    n_Astep:    normalize transfer function in A step
    n_Sstep:    normalize transfer function in S step

    Return:
    -------
    rms: reconstruction error of MEG/EEG measurements
    n: number of active regions/sources
    l21s: l21 norm of the reconstructed sources
    l1a_l1norm: the l1norm of reconstructed MAR model
    l1a_l2norm: the l2norm of the reconstructed MAR model
    cl.l21_ratio: the l21 norm used in the regularization (not in %)
    """
    l21_reg, la, la_ratio, m_p, normalize, foldername, o_v, n_Astep, n_Sstep, includeMNE = args

    G = np.array(load(foldername+'/G.dat', mmap_mode='r'))
    M = np.array(load(foldername+'/M.dat', mmap_mode='r'))
    SC = np.array(load(foldername+'/SC.dat', mmap_mode='r')).astype(int)
    if os.path.isfile(foldername+'/A.dat'):
        A = np.array(load(foldername+'/A.dat', mmap_mode='r'))
    else:
        A = None
    m_p = int(float(m_p))
    if int(o_v):
        if not int(includeMNE):
            cl = linear_model.iSDR(l21_ratio=float(l21_reg), normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))

        else:
            cl = linear_model.iSDRols(l21_ratio=float(l21_reg), normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))

    else:
        if not int(includeMNE):
            cl = linear_model.eiSDR(l21_ratio=float(l21_reg), la=[float(la), float(la_ratio)],
                                normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))
        else:
            cl = linear_model.eiSDRols(l21_ratio=float(l21_reg), la=[float(la), float(la_ratio)],
                                normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))

    cl.solver(G, M, SC, model_p=int(m_p), A=A, normalize=int(float(normalize)))
    R = cl.Scoef_.copy()
    n_c, n_t = M.shape
    rms = np.linalg.norm(M)**2
    n = 0
    l21s = 0
    l1a_l1norm,  l1a_l2norm= 0, 0
    n_a_coef = 0
    stx = 0
    if len(R) > 0 and len(cl.Acoef_) > 0 and len(cl.active_set[-1]) > 0:
        Mx = np.zeros(M.shape)
        n_a_coef = np.sum(np.abs(cl.Acoef_) > 0)
        n = R.shape[0]
        Gx = np.dot(G[:, np.array(cl.active_set[-1])], cl.Acoef_)
        sxy = SC[np.array(cl.active_set[-1]), :]
        stx = np.sum(sxy[:, np.array(cl.active_set[-1])])*m_p
        if not int(includeMNE):
            for j in range(m_p):
                Mx += np.dot(Gx[:, j*n:n*(j+1)], R[:, j:Mx.shape[1]+j])
        else:
            Mx[:,:m_p] = np.dot(G[:, np.array(cl.active_set[-1])], R[:, :m_p])
            for j in range(m_p):
                Mx[:,m_p:] += np.dot(Gx[:, j*n:n*(j+1)], R[:, j:Mx[:,m_p:].shape[1]+j])

        x = min(Mx.shape[1], M.shape[1])
        rms = np.linalg.norm(M[:, :x] - Mx[:, :x])**2
        for i in range(n):
            l21s += np.linalg.norm(R[i, :])
        l1a_l1norm = np.sum(np.abs(cl.Acoef_))
        l1a_l2norm = np.linalg.norm(cl.Acoef_)**2

    return rms/(n_t*n_c), n, l21s, l1a_l1norm, l1a_l2norm, cl.l21_ratio, cl.la[0], n_a_coef, stx

def _runCV(args):
    """
    The core function used to run the cross validation
    Parameters:
    ----------
    l21_reg:    regularization of l21 norm (Sstep) , 0<values<100
    la:         regularization of l1 and l2 norm (Astep)
    la_ratio:   regularization of l1 and l2 norm (Astep)
    m_p:        MAR model order
    normalize:  Normalize A_i's before Sstep or not
    foldername: Folder where to find:
                    M.dat: EEG/MEG data
                    G.dat: gain matix
                    SC.dat:    structral connectivity
                    A.dat: Initial MAR model, if not None is passed
    o_v:        flag to used old version iSDR or not
    n_Astep:    normalize transfer function in A step
    n_Sstep:    normalize transfer function in S step

    Return:
    ------
    rms: reconstruction error of MEG/EEG measurements
    n: number of active regions/sources
    l21s: l21 norm of the reconstructed sources
    l1a_l1norm: the l1norm of reconstructed MAR model
    l1a_l2norm: the l2norm of the reconstructed MAR model
    cl.l21_ratio: the l21 norm used in the regularization (not in %)
    """
    l21_reg, la, la_ratio, m_p, normalize, foldername, o_v, n_Astep, n_Sstep, _, seed, includeMNE, test_data, run_ix  = args
    test_data = np.array(test_data)
    G = np.array(load(foldername+'/G.dat', mmap_mode='r'))
    M = np.array(load(foldername+'/M.dat', mmap_mode='r'))
    SC = np.array(load(foldername+'/SC.dat', mmap_mode='r')).astype(int)
    if os.path.isfile(foldername+'/A.dat'):
        A = np.array(load(foldername+'/A.dat', mmap_mode='r'))
    else:
        A = None
    m_p = int(float(m_p))
    n_c, n_t = M.shape
    np.random.seed(int(seed))
    number_list = np.arange(n_c)
    random.shuffle(number_list)
    rms = []
    nbr = 0
    l21s = 0
    l1a_l1norm = 0
    l1a_l2norm = 0
    l21_ratio = 0
    train_data = np.array([j for j in range(n_c) if not j in test_data])
    if int(o_v):
        if not int(includeMNE):
            cl = linear_model.iSDR(l21_ratio=float(l21_reg), normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))

        else:
            cl = linear_model.iSDRols(l21_ratio=float(l21_reg), normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))

    else:
        if not int(includeMNE):
            cl = linear_model.eiSDR(l21_ratio=float(l21_reg), la=[float(la), float(la_ratio)],
                                normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))
        else:
            cl = linear_model.eiSDRols(l21_ratio=float(l21_reg), la=[float(la), float(la_ratio)],
                                normalize_Astep=int(n_Astep), normalize_Sstep=int(n_Sstep))
    gtmp = G[train_data, :]
    mtmp = M[train_data, :]
    cl.solver(gtmp, mtmp, SC, model_p=int(m_p), A=A, normalize=int(float(normalize)))
    R = cl.Scoef_.copy()
    l21_ratio = cl.l21_ratio
    n_a_coef = 0
    stx = 0
    if len(R) > 0 and len(cl.Acoef_) > 0 and len(cl.active_set[-1]) > 0:
        sxy = SC[np.array(cl.active_set[-1]), :]
        stx = np.sum(sxy[:, np.array(cl.active_set[-1])])*m_p
        n_a_coef = np.sum(np.abs(cl.Acoef_) > 0)
        n = R.shape[0]
        nbr = n
        if not includeMNE:
            Mx = M[test_data, :].copy()
        else:
            Mx = M[test_data, :-1].copy()
        ns = len(cl.active_set[-1])
        if not int(includeMNE):
            gtmp = G[test_data, :]
            gtmp = gtmp[:, np.array(cl.active_set[-1])]
            Mx[:, :m_p] = np.dot(gtmp, R[:, :m_p])
            for k in range(m_p, Mx.shape[1]):
                Mx[:, k] = 0
                for m in range(m_p):
                    x=np.dot(gtmp, cl.Acoef_[:, m*ns:ns*(m+1)])
                    Mx[:, k] += np.dot(x, R[:, k+m])
        else:
            gtmp = G[test_data, :]
            gtmp = gtmp[:, np.array(cl.active_set[-1])]
            Mx[:, :m_p] = np.dot(gtmp, R[:, :m_p])
            for k in range(m_p, Mx.shape[1]):
                Mx[:, k] = 0
                for m in range(m_p):
                    x=np.dot(gtmp, cl.Acoef_[:, m*ns:ns*(m+1)])
                    Mx[:, k] += np.dot(x, R[:, k+m-m_p])

        x = min(Mx.shape[1], M.shape[1])
        rms = np.linalg.norm(M[test_data, :x] - Mx[:, :x])**2
        l = 0
        for i in range(n):
            l += np.linalg.norm(R[i, :])
        l21s = l
        l1a_l1norm = np.sum(np.abs(cl.Acoef_))
        l1a_l2norm = np.linalg.norm(cl.Acoef_)**2
    else:
        rms = np.linalg.norm(M[test_data, :])**2
        nbr= 0
        l21s = 0
        l1a_l1norm = 0
        l1a_l2norm = 0
    rms = rms/(n_t*len(test_data))
    return rms, nbr, l21s, l1a_l1norm, l1a_l2norm, l21_ratio, cl.la[0], n_a_coef, run_ix, stx

def compute_criterion(M, results, criterion='bic', include_S=1):
    sigma2 = np.var(M)
    n_c, n_t = M.shape
    n_samples = n_c * n_t
    if criterion == 'aic':
        K = 2  # AIC
    elif criterion == 'bic':
        K = np.log(n_samples)  # BIC
    else:
        raise ValueError("Wrong value for criterion: %s" %criterion)
    mean_squared_error = results.rms
    df = results['nbr_coef'] + include_S * results['nbr']
    criterion_ = ((n_samples * mean_squared_error) / sigma2 + K * df)
    results[criterion] = criterion_ / n_samples
    return results


def swipeFileData():
    file1=input("Enter the name of the 1st file")
    file2=input("Enter the name of the 2nd file")

    with open(file1,'r') as a:
        data_a=a.read()
    with open(file2,'r') as b:
        data_b=b.read()

    with open(file1,'w+') as a:
        a.write(data_b)
    with open(file2,'w+') as b:
        b.write(data_a)

swipeFileData()
print("Voila!! Your data from the files are swapped!!")


import cv2
import numpy as np

img0= cv2.imread('/home/tanmay/Documents/cvip/proj1_cse573/task1.png', 0)
img=np.asarray(img0)

def normalization(matrix):
    maximum=0
    minimum=matrix[1][1]
    pos_edge_x =[[0 for x in range(len(matrix[0]))] for y in range(len(matrix))]

    for i in range(1,len(matrix)):
        for j in range(1,len(matrix[0])):
            if matrix[i][j]>maximum:
                maximum=matrix[i][j]

    for i in range(1,len(matrix)):
        for j in range(1,len(matrix[0])):
            if matrix[i][j]<minimum:
                minimum=matrix[i][j]

    for i in range(1,len(matrix)):
        for j in range(1,len(matrix[0])):
            pos_edge_x[i][j] = ((matrix[i][j] - minimum) / (maximum - minimum))

    return(np.asarray(pos_edge_x))

def soble_x(imgs):
    col=len(imgs[0])
    row=len(imgs)

    #return(imgs)

    z=[[0 for x in range(col)] for y in range(row)]
    for i in range(1, img0.shape[0]-1):
        for j in range(1, img0.shape[1]-1):
            z1=imgs[i-1][j-1]* -1 + imgs[i-1][j]* 0+ imgs[i+1][j+1]* 1+imgs[i][j-1]* -2+imgs[i][j]* 0+imgs[i-1][j+1]* 2+imgs[i+1][j-1]* -1+imgs[i+1][j]* 0+imgs[i+1][j+1]* 1
            z[i][j]=z1
    return(np.asarray(z))

soble_x_array=soble_x(img)
print(soble_x_array)
pos_edge_x = normalization(soble_x_array)
cv2.imshow('pos_edge_x_dir', pos_edge_x)

def soble_y(imgs):
    col=len(imgs[0])
    row=len(imgs)

    z=[[0 for x in range(col)] for y in range(row)]
    for i in range(1, img0.shape[0]-1):
        for j in range(1, img0.shape[1]-1):
            z1=img0[i-1][j-1]* -1+img0[i-1][j]* -2+img0[i+1][j+1]* -1+img0[i][j-1]* 0+img0[i][j]* 0+img0[i-1][j+1]* 0+img0[i+1][j-1]* 1+img0[i+1][j]* 2+img0[i+1][j+1]* 1

            z[i][j]=z1

    return(np.asarray(z))

soble_y_array=soble_y(img0)
print(soble_y_array)
pos_edge_y = np.asarray(normalization(soble_y_array))
cv2.namedWindow('pos_edge_y_dir', cv2.WINDOW_NORMAL)
cv2.imshow('pos_edge_y_dir', pos_edge_y)
cv2.waitKey(0)
cv2.destroyAllWindows()

'''cv2.namedWindow('sobel_y',cv2.WINDOW_NORMAL)
cv2.imshow('final_edge of y',soble_y_array)
cv2.waitKey(0)
cv2.destroyAllWindows()'''

#res=np.asarray(soble_x(img))

#print(res)


import csv
import json

from oauth2client import client

from dbmclient.models.base import Base

class InsertionOrder(Base):

    def find_by_advertiser(self, advertiser_id):
        service = self.get_service()

        try:
            body = { 'filterType': 'ADVERTISER_ID', 'filterIds': [advertiser_id]}

            req = service.lineitems().downloadlineitems(body=body)
            resp = req.execute()

        except client.AccessTokenRefreshError:
            print ("The credentials have been revoked or expired, please re-run"
                   "the application to re-authorize")

        if 'lineItems' not in resp:
            return None

        lineitems = resp['lineItems']
        first = True
        rval = []
        ids = []
        for raw_lineitem in csv.reader(lineitems.encode('utf-8').split('\n')):
            if len(raw_lineitem) == 0:
                continue

            if first:
                first = False
                continue

            insertionOrder = InsertionOrder(InsertionOrder.connection)
            id = self.encode_for_id(raw_lineitem[4])
            if id in ids:
                continue
            ids.append(id)
            insertionOrder['id'] = id
            insertionOrder['name'] = raw_lineitem[4]
            insertionOrder['advertiser_name'] = raw_lineitem[3]
            insertionOrder['budget'] = raw_lineitem[11]
            insertionOrder['start_date'] = raw_lineitem[8]
            insertionOrder['end_date'] = raw_lineitem[9]
            rval.append(insertionOrder)

        return rval


import csv

def displayList(L):
    if L != []:
        for s in L:
            print (s)
    else:
        print("List is empty")

def loadStudentData():
# start by trying to load our data file.
    try:
        f = open("students.csv", "r")

    except IOError as e:
        print("Failed to open data file")
        return []

    else:
        print("Students data file opened successfully")
        students = []
        for line in csv.reader(f):
            students.append(line)
        f.close()
        return students

def report2(L):
    boys = []
    girls = []

    if L != []:
        for s in L:
            r = []
            r.append(s[1])
            r.append(s[2])
            r.append(s[0])

            if s[6] in ['m','M']:
                boys.append(r)
            elif s[6] in ['f','F']:
                girls.append(r)
            else:
                print ("Missing gender for student with unique ID " + s[0])

        boys = sorted(boys, key = lambda student: student[0])
        girls = sorted(girls, key = lambda student: student[0])

    return boys, girls

# main program starts here
StudentList = loadStudentData()
boys, girls = report2(StudentList)
print("Boys")
displayList(boys)
print("Girls")
displayList(girls)