from django.contrib.auth.models import User, Group
from rest_framework import serializers
from rest_framework.decorators import action
from .models import Profile

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['id', 'name']

class UserSerializer(serializers.HyperlinkedModelSerializer):
    groups = GroupSerializer(many=True)
    profile_url = serializers.CharField(source='profile.get_abstract_url')
    avatar_url = serializers.CharField(source='profile.url_avatar')

    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name',
                  'email', 'last_login', 'profile_url', 'avatar_url', 'groups']

class ProfileSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(
        source="user.first_name", required=False, trim_whitespace=True)
    last_name = serializers.CharField(
        source="user.last_name", required=True, trim_whitespace=True)
    email = serializers.CharField(
        source="user.email", required=True, trim_whitespace=True)

    groups_permission = serializers.SerializerMethodField(
        method_name='get_extra_groups')

    extra = serializers.JSONField()

    class Meta:
        model = Profile
        fields = ['groups_permission', 'first_name', 'last_name', 'email', 'birth_date', 'class_id', 'company_j', 'company_jvn',
                  'company_vn', 'gpa', 'major', 'origin', 'phone_number', 'sex', 'student_id', 'url_avatar', 'rank', 'description','extra']
        related_fields = ['user']
        extra_kwargs = {
            'sex': {'required': True},
            'student_id': {'required': True},
            'birth_date': {'required': True},
            'major': {'required': True},
            'gpa': {'required': True},
            'rank': {'required': True}
        }

    # def update(self, instance, validated_data):
    #     user_data = validated_data['user']
    #     first_name = user_data.get('first_name', instance.user.first_name)
    #     last_name = user_data.get('last_name', instance.user.last_name)
    #     email = user_data.get('email', instance.user.email)
    #     instance.user.first_name = first_name
    #     instance.user.email = email
    #     instance.user.last_name = last_name
    #     instance.user.save()
    #     instance.save()
    #     return instance

    def update(self, instance, validated_data):
        # user_data = validated_data['user']
        user_data = validated_data.get('user', None)
        if user_data:
            first_name = user_data.get('first_name', instance.user.first_name)
            last_name = user_data.get('last_name', instance.user.last_name)
            email = user_data.get('email', instance.user.email)
            instance.user.first_name = first_name
            instance.user.email = email
            instance.user.last_name = last_name
        instance.student_id = validated_data.get(
            'student_id', instance.student_id)
        instance.sex = validated_data.get('sex', instance.sex)
        instance.birth_date = validated_data.get(
            'birth_date', instance.birth_date)
        instance.phone_number = validated_data.get(
            'phone_number', instance.phone_number)
        instance.class_id = validated_data.get('class_id', instance.class_id)
        instance.major = validated_data.get('major', instance.major)
        instance.gpa = validated_data.get('gpa', instance.gpa)
        instance.company_j = validated_data.get(
            'company_j', instance.company_j)
        instance.company_jvn = validated_data.get(
            'company_jvn', instance.company_jvn)
        instance.company_vn = validated_data.get(
            'company_vn', instance.company_vn)
        instance.origin = validated_data.get('origin', instance.origin)
        instance.rank = validated_data.get('rank', instance.rank)
        instance.description = validated_data.get(
            'description', instance.description)
        instance.avatar = validated_data.get('avatar', instance.avatar)
        instance.extra = validated_data.get('extra', instance.extra)
        instance.user.save()
        instance.save()
        return instance

    def get_extra_groups(self, obj):
        serializer = GroupSerializer(obj.user.groups, many=True)
        return serializer.data


"""
File: data.py

Data structores and input.
"""
import random
from typing import NamedTuple, List
from warnings import warn

import numpy as np

class Image(NamedTuple):
    "Represents an image and its value, with a unique identifier."
    data: np.ndarray # The image.
    of: int          # The number of which this is an image.
    id: int = None   # The index of this number in the input files, or None.
    def __str__(self):
        return f"Image(of={self.of}, id={self.id}\n{image2str(self.data)}\n)"

    def oneHot(self) -> np.ndarray:
        """Get the encoded number as a vector.

        For example, Image(..., 5) would become [0,0,0,0,0,1,0,0,0,0].
        """
        array = np.zeros(10, dtype=int)
        array[self.of] = 1
        array.flags.writeable = False
        return array

class Data(object):
    """Represents data for use in a neural network."""

    _default_seed = 20171002
    _randomizer = random.Random(20171002)

    def __init__(self, imagefile, labelfile,
                 *, training=60, validation=15, test=25, seed=None):
        """Use the data in the given files to create a data set.

        The training, validation, and test sets' sizes are given as integer
        percentages. If they do not evenly divide the data, remaining data
        will be added to the test set.
        """
        if training + validation + test != 100:
            raise ValueError("Sum of data sets is not 100")
        images = load_files(imagefile, labelfile)
        onepercent = len(images) // 100
        r = round(onepercent * training)
        v = round(onepercent * validation)
        # s = round(onepercent * test)

        Data._randomizer.seed(Data._default_seed if seed is None else seed)
        random.shuffle(images)

        self._training = images[:r]
        self._validation = images[r:r+v]
        self._test = images[r+v:]

    @property
    def training(self): return self._training
    @property
    def validation(self): return self._validation
    @property
    def test(self): return self._test

def image2str(arr: np.ndarray, char='X', *, columns=28) -> str:
    """Convert image data from an array to a string.

    Data should be given as a 1-d array.

    Nonzero characters will be rendered as the given character, and zeros will
    be rendered as spaces.
    """
    if isinstance(arr, np.ndarray):
        dims = len(arr.shape)
    else:
        dims, a = 0, arr
        while True:
            try:
                a = a[0]
            except TypeError:
                break
            dims += 1
    if dims == 1:
        arr = [arr[i:i+columns] for i in range(0, len(arr), columns)]
    elif dims != 2:
        raise ValueError("Can not convert many-dimensional array to string")
    return '\n'.join(''.join(char if i else ' ' for i in row) for row in arr)

def load_files(imagefile, labelfile) -> List[Image]:
    "Read an image file and a label file into a list of Images."
    result = []
    images = np.load(imagefile)
    labels = np.load(labelfile)
    for i, (image, label) in enumerate(zip(images, labels)):
        image = image.flatten()
        image.flags.writeable = False
        result.append(Image(image.flatten(), label, i))
        i += 1
    return result


#coding=utf-8
from flask import Blueprint,render_template, flash, redirect,url_for,request,jsonify,Response,session,Flask

lg = Blueprint("login",__name__,url_prefix="/login")

@lg.route("/")
def index():
    return "login Index page"

def login_form():
    if request.method == 'POST':
        user_name = request.form['login_username']
        pass_word = request.form['login_password']
        if user_name:
            session['username'] = request.form['login_username']
            session.permanent = True
            app.permanent_session_lifetime = timedelta(minutes=5)
            state = {"user_name":user_name,"login_state":1}
            json_state = jsonify(state)
            return json_state
        else:
            state = {"user_name":user_name,"login_state":0}
            json_state = jsonify(state)
            return json_state


#First, install pywin32 by using "python -m pip install pypiwin32" on Windows Command console

import win32com.client as win32
import datetime,time,os

def sendemail (Tolist,Cclist, Subject, Sentence1):
	outlook = win32.Dispatch('outlook.application')
	mail = outlook.CreateItem(0)
	print(dir())
	mail.To = Tolist
	mail.CC = Cclist
	mail.Subject = Subject
	mail.HTMLBody=Sentence1
	#mail.Attachments.Add(r'C:\Users\g801781\Desktop\python_work\SendEmail.py')
	mail.Display()
	return(0)

def sende_plain_mail (Tolist, Cclist, Subject, Sentence1):
	outlook = win32.Dispatch('outlook.application')
	mail = outlook.CreateItem(0)
	mail.To = Tolist
	mail.CC = Cclist
	mail.Subject = Subject
	mail.Body=Sentence1
	#mail.Attachments.Add(r'C:\Users\g801781\Desktop\python_work\SendEmail.py')
	mail.Display()

def html_line_break(email_body):
	new_email_body=email_body.replace('\n','<br/>')
	return new_email_body

def send_calendar(recipients,start_time,end_time,Subject, Sentence1):
	outlook = win32.Dispatch('outlook.application')
	mail = outlook.CreateItem(1)
	mail.MeetingStatus= 1

	mail.Subject = Subject
	#mail.start=datetime.datetime.now() + datetime.timedelta(hours=8)
	#print(datetime.datetime.now() + datetime.timedelta(hours=8))
	mail.start=start_time
	#mail.Duration=60
	#mail.end=datetime.datetime.now() + datetime.timedelta(hours=8)
	mail.end=end_time
	mail.Body=Sentence1
	mail.location='Null'
	mail.ReminderMinutesBeforeStart = 30

	for recipient in recipients:
		invitee= mail.Recipients.Add(recipient)
		#invitee.Type = OUTLOOK_OPTIONAL_ATTENDEE

	mail.Display()
	return(0)

#send_calendar (['TTAC@syniverse.com','scc@syniverse.com','PS-RCC-AP@syniverse.com','ao-rcc-ap@syniverse.com','DSS_Route_Provision@syniverse.com'],1,2, 'Test Email','This Email is sent using Python script')


from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect
from .forms import ContactForm

def contact(request):
    submitted = False
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            print(cd)

            return HttpResponseRedirect('/contact?submitted=True')

    else:
        form = ContactForm()
        if 'submitted' in request.GET:
            submitted = False

    return render(request,'contact.html',{'form':form,'submitted':submitted})

Handling Forms in Django/Basic/form/form/views.py


from Menu import Menu
from Diner import Diner

"""
Jizhong Wang
ITP 115, Fall 2018
Final project
jizhongw@us.edu
"""

class Waiter(object):
    def __init__(self, menu):
        self.__diners = []
        self.__menu = menu

    def addDiner(self, diner):
        self.__diners.append(diner)

    def getNumDiners(self):
        return len(self.__diners)

    def printDinerStatuses(self):
        print("")
        # loop over status
        for i in range(len(Diner.STATUSES)):
            print("Diners who are " + Diner.STATUSES[i] + ":")
            for j in range(len(self.__diners)):
                diner = self.__diners[j]
                if diner.getStatus() == i:
                    print("\t", diner, sep="")

    def takeOrders(self):
        # loop over diner list
        for i in range(len(self.__diners)):
            diner = self.__diners[i]
            # if diner is ordering
            if diner.getStatus() == 1:
                order = []
                # loop over all types
                for j in range(len(Menu.MENU_ITEM_TYPES)):
                    type = Menu.MENU_ITEM_TYPES[j]
                    self.__menu.printMenuItemsByType(type)

                    print(diner.getName() + ", please select a " + type + " menu item number.")
                    # get order
                    choice = -1
                    while choice < 0 or choice >= self.__menu.getNumMenuItemsByType(type):
                        choice = int(input("> "))
                    item = self.__menu.getMenuItem(type, choice)
                    order.append(item)
                # set order for customer
                diner.setOrder(order)
                # print order
                print("")
                diner.printOrder()

    def ringUpDiners(self):
        # loop over diner list
        for i in range(len(self.__diners)):
            diner = self.__diners[i]
            # if diner is paying
            if diner.getStatus() == 3:
                cost = diner.calculateMealCost()
                print("\n"+diner.getName()+", your meal cost $"+str(cost))

    def removeDoneDiners(self):
        # loop over diner list
        for i in range(len(self.__diners)):
            diner = self.__diners[i]
            # if diner is leaving
            if diner.getStatus() == 4:
                print("\n"+diner.getName()+", thank you for dining with us! Come again soon!")
        # loop over diner list to delete diner
        for i in range(len(self.__diners)):
            diner = self.__diners[len(self.__diners)-i-1]
            if diner.getStatus() == 4:
                del self.__diners[len(self.__diners)-i-1]

    def advanceDiners(self):
        self.printDinerStatuses()
        self.takeOrders()
        self.ringUpDiners()
        self.removeDoneDiners()
        for i in range(len(self.__diners)):
            self.__diners[i].updateStatus()


# encoding: utf-8
"""
View which can render and send email from a contact form.

"""
from django.utils.encoding import smart_str
from django.core.mail import send_mail
from django.contrib.auth.views import redirect_to_login
from django.core.mail.message import BadHeaderError

from django.http.response import Http404, HttpResponseRedirect,\
    JsonResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.views.generic import FormView
from django.http.response import HttpResponse

from .forms import ContactFormCaptcha, DownloadForm
from .models import Contact, File, Order

import os

def contact_form(request, form_class=ContactFormCaptcha,
                 template_name='contact_form/contact_form.html',
                 success_url='/contact/sent/', login_required=False, fail_silently=False):
    """
    Renders a contact form, validates its input and sends an email
    from it.

    To specify the form class to use, pass the ``form_class`` keyword
    argument; if no ``form_class`` is specified, the base
    ``ContactForm`` class will be used.

    To specify the template to use for rendering the form (*not* the
    template used to render the email message sent from the form,
    which is handled by the form class), pass the ``template_name``
    keyword argument; if not supplied, this will default to
    ``contact_form/contact_form.html``.

    To specify a URL to redirect to after a successfully-sent message,
    pass the ``success_url`` keyword argument; if not supplied, this
    will default to ``/contact/sent/``.

    To allow only registered users to use the form, pass a ``True``
    value for the ``login_required`` keyword argument.

    To suppress exceptions raised during sending of the email, pass a
    ``True`` value for the ``fail_silently`` keyword argument. This is
    **not** recommended.

    Template::

        Passed in the ``template_name`` argument.

    Context::

        form
            The form instance.

    """
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    if request.method == 'POST':
        form = form_class(request.POST, request=request)
        if form.is_valid():
            form.save(fail_silently=fail_silently)
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(request=request)
    return render(request, template_name, {'form': form})

def contact_tags_form(request):
    if not request.is_ajax():
        raise Http404
    template = 'contact_form/{0}'
    is_valid = False
    if request.method == 'POST':
        form = ContactFormCaptcha(request.POST, request=request)
        is_valid = form.is_valid()
        if is_valid:
            form.save()
    else:
        form = ContactFormCaptcha()

    if is_valid:
        clean_data = form.cleaned_data
        Contact.objects.create(
            name=clean_data['name'],
            email=clean_data['email'],
            text=clean_data['body']
        )
        html = render_to_string(
            template.format('contact_form_ajax_sent.html'),
            {'form': form}
        )
    else:
        html = render_to_string(
            template.format('contact_form_ajax.html'),
            {'form': form}
        )

    return JsonResponse({'html': html, 'is_valid': is_valid})

text = u'''
Email: {Email},
Завантаження файлу
'''

class DownloadView(FormView):
    form_class = DownloadForm
    template_name = 'contact_form/download.html'
    template_name_success = 'contact_form/download_success.html'

    def form_valid(self, form):
        clean_data = form.cleaned_data
        self.object = Order.objects.create(
            email=clean_data.get('email', ''),
        )
        self.send_email()
        file_ = File.objects.last()
        response = HttpResponse(content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(
            file_.file.url
        )
        response['X-Sendfile'] = smart_str(file_.file.url)
        return response

    def send_email(self):
        from constance import config

        msg_data = {
            'Email': self.object.email
        }

        msg_text = text.format(**msg_data)
        from_email = config.DEFAULT_FROM_EMAIL
        recipient_list = [config.MANAGERS_EMAIL]

        if msg_text:
            try:
                send_mail(
                    u"Завантажено програму з сайту",
                    msg_text,
                    from_email,
                    recipient_list,
                    fail_silently=False,
                )
            except BadHeaderError:
                return HttpResponse('Invalid header found.')


from neurolight.match.preprocess import (
    mouselight_preprocessing,
    add_fallback,
    add_precomputed_edges,
    assignments_from_matched,
)
from neurolight.match.costs_vectorized import wrapped_costs as get_costs

from funlib.match import GraphToTreeMatcher

import networkx as nx

import time
import logging

logger = logging.getLogger(__file__)

def match(
    consensus,
    skeletonization,
    pre_solved,
    node_offset,
    max_new_edge,
    penalty_attr,
    location_attr,
    target_attr,
    expected_edge_len,
    max_match_dist,
):
    skeletonization = skeletonization.to_undirected()
    start_time = time.time()

    if len(consensus.nodes) == 0:
        logger.info(f"No consensus nodes. Skipping")
        return ([], [], skeletonization)

    logger.info("PreProcess...")
    start_time = time.time()

    logger.info(
        f"Skeletoniation has {len(skeletonization.nodes)} nodes and "
        f"{len(skeletonization.edges)} edges before preprocessing"
    )

    mouselight_preprocessing(
        skeletonization,
        max_dist=max_new_edge,
        penalty_attr=penalty_attr,
        location_attr=location_attr,
        expected_edge_len=expected_edge_len,
    )

    logger.info(f"Preprocessing took {time.time() - start_time} seconds")
    logger.info(
        f"Skeletoniation has {len(skeletonization.nodes)} nodes and "
        f"{len(skeletonization.edges)} edges after preprocessing"
    )

    start_time = time.time()
    add_fallback(
        skeletonization,
        consensus,
        node_offset=node_offset,
        max_new_edge=max_match_dist,
        expected_edge_len=expected_edge_len,
        penalty_attr=penalty_attr,
        location_attr=location_attr,
    )

    logger.info(f"Adding fallback took {time.time() - start_time} seconds")
    logger.info(
        f"Skeletoniation has {len(skeletonization.nodes)} nodes and "
        f"{len(skeletonization.edges)} edges after adding fallback"
    )
    start_time = time.time()

    add_precomputed_edges(skeletonization, pre_solved)

    logger.info(f"Adding precomputed edges took {time.time() - start_time} seconds")

    start_time = time.time()

    node_costs, edge_costs = get_costs(
        skeletonization,
        consensus,
        location_attr,
        penalty_attr,
        max_match_dist,
        max_match_dist,
        expected_edge_len,
    )

    # edge_costs = [((a, b), (c, d), e) for a, b, c, d, e in edge_costs]

    logger.info(f"Getting costs took {time.time() - start_time} seconds")

    node_assignments, edge_assignments = assignments_from_matched(
        pre_solved, target_attr
    )
    logger.info(
        f"Input contains {len(node_assignments)} node assignments "
        + f"and {len(edge_assignments)} edge assignments"
    )
    filtered_node_assignments, filtered_edge_assignments = [], []
    missing_target_nodes = []
    for source, target in node_assignments:
        assert (
            source in skeletonization.nodes
        ), f"prematched source {source} not in skeletonization"
        if target is not None:
            # skeletonization nodes may match to a target node which is outside
            # the current context. These will/can not be enforced
            if target not in consensus.nodes:
                missing_target_nodes.append(target)
            else:
                filtered_node_assignments.append((source, target))
        else:
            filtered_node_assignments.append((source, target))
    missing_target_edges = []
    for source, target in edge_assignments:
        assert (
            source in skeletonization.edges
        ), f"prematched source {source} not in skeletonization"
        if target is not None:
            u, v = target
            # skeletonization edges may match to a target edge, one node
            # of which is outside the current context. These can/will not be enforced
            if (u - node_offset, v - node_offset) not in consensus.nodes:
                missing_target_edges.append(target)
            else:
                filtered_edge_assignments.append((source, target))
        else:
            filtered_node_assignments.append((source, target))

    logger.info(f"{len(missing_target_nodes)} node assignments could not be enforced")
    logger.info(f"{len(missing_target_edges)} edge assignments could not be enforced")

    start_time = time.time()

    matcher = GraphToTreeMatcher(
        skeletonization, consensus, node_costs, edge_costs, timeout=2000
    )
    matcher.enforce_expected_assignments(filtered_node_assignments)
    matcher.enforce_expected_assignments(filtered_edge_assignments)
    logger.info(f"Initializing took {time.time() - start_time} seconds")

    try:
        start_time = time.time()
        node_matchings, edge_matchings, _ = matcher.match()

        logger.info("Solving took %s seconds" % (time.time() - start_time))
    except ValueError as e:
        logger.warning(e)
        return skeletonization

    return node_matchings, edge_matchings, skeletonization


import cv2
import numpy as np

o = cv2.imread('img10.jpg')
img = o

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)
k = np.ones((10,10), dtype=np.uint8)
binaryo = cv2.morphologyEx(binary, cv2.MORPH_OPEN, k)

contours, hierarchy = cv2.findContours(binaryo, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

cnt = contours[0]
hull = cv2.convexHull(cnt, returnPoints=False)
defects = cv2.convexityDefects(cnt, hull)
print('defects = \n', defects)

for i in range(defects.shape[0]):
    s,e,f,d = defects[i, 0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img, start, end, [0,0,255], 2)
    cv2.circle(img, far, 5, (255,255,0), -1)

cv2.imshow('result', img)
cv2.waitKey()
cv2.destroyAllWindows()


# encoding UTF-8
# Autor: Siham El Khoury Caviedes, A01374764

# Descripción: Cálculo del perímetro y área de dos rectángulos.

import turtle

# Calcular y guardar en la variable area el area de un rectángulo.
def calcularArea(base, altura):
    area = base * altura
    return area

# Calcular y guardar en la variable perimetro el perimetro de un rectángulo.
def calcularPerimetro(base, altura):
    perimetro = (2*base) + (2*altura)
    return perimetro

# Comparar ambas áreas y guardar la mayor en la variable mayor.
def compararAreas (area1, area2):
    if area1 > area2:
        mayor = area1
    else:
        mayor = area2

# Dibujar un rectángulo con la tortuga.
def dibujarRectangulo (base, altura):
    turtle.forward(base)
    turtle.left(90)
    turtle.forward(altura)
    turtle.left(90)
    turtle.forward(base)
    turtle.left(90)
    turtle.forward(altura)
    turtle.left(90)

# Función principal:
def main():
    base1 = float(input("Teclea la base del primer rectángulo: "))
    altura1 = float(input("Teclea la altura del primer rectángulo: "))
    base2 = float(input("Teclea la base del segundo rectángulo: "))
    altura2 = float(input("Teclea la altura del segundo rectángulo: "))
    if base1 <= 0 or altura1 <= 0 or base2 <= 0 or altura2 <= 0:
        print ("Error, no insertes 0 ó números negativos. Inténtalo de nuevo.")
        return
    area1 = calcularArea(base1, altura1)
    area2 = calcularArea(base2, altura2)
    perimetro1 = calcularPerimetro(base1, altura1)
    perimetro2 = calcularPerimetro(base2, altura2)
    print ("El primer rectángulo tiene un área de %.2f y un perímetro de %.2f unidades." % (area1, perimetro1))
    print ("El segundo rectángulo tiene un área de %.2f y un perímetro de %.2f unidades." % (area2, perimetro2))
    if area1 == area2:
        print ("Ambas áreas son iguales.")
    else:
        mayor = compararAreas (area1, area2)
        print ("De ambos, es el", mayor, "el que tiene mayor área.")
    turtle.pencolor("red")
    dibujarRectangulo(base1, altura1)
    turtle.penup()
    turtle.forward(2*base1)
    turtle.pendown()
    turtle.pencolor("blue")
    dibujarRectangulo(base2, altura2)
    turtle.exitonclick()

# Ejecutar función principal.
main()


import torch
import torch.nn as nn

class SkipGramModel(nn.Module):
    def __init__(self, emb_size, emb_dimension):
        super(SkipGramModel, self).__init__()
        self.emb_size = emb_size
        self.emb_dimension = emb_dimension
        self.u_embeddings = nn.Embedding(self.emb_size,
                                         self.emb_dimension,
                                         sparse=True)
        self.v_embeddings = nn.Embedding(self.emb_size,
                                         self.emb_dimension,
                                         sparse=True)
        self.init_values()

    def init_values(self):
        init_range = 0.5 / self.emb_dimension
        self.u_embeddings.weight.data.uniform_(-init_range, init_range)
        self.v_embeddings.weight.data.uniform_(-0, 0)

    def forward(self, u, pos_v):
        emb_u = self.u_embeddings(u)
        emb_pos_v = self.v_embeddings(pos_v)
        score = torch.mul(emb_pos_v, emb_u).squeeze()
        score = torch.sum(score, dim=1)
        score = torch.nn.functional.logsigmoid(score)
        return -torch.sum(score)


import json
import re
from datetime import datetime

class JsonHelper:

    DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"

    @staticmethod
    def to_json(obj):
        return json.dumps(obj, default=JsonHelper.__date_serializer)

    @staticmethod
    def to_json_file(obj, filename):
        with open(filename, 'w') as f:
            json.dump(obj, f, sort_keys=True, indent=4, default=JsonHelper.__date_serializer)

    @staticmethod
    def from_json(json_str):
        return json.loads(json_str, object_hook=JsonHelper.__deserializer_helper)

    @staticmethod
    def from_json_file(filename):
        with open(filename, 'r') as f:
            return json.load(f, object_hook=JsonHelper.__deserializer_helper)

    @staticmethod
    def __date_serializer(obj):
        if isinstance(obj, datetime):
            serial = obj.isoformat()
            return serial

    @staticmethod
    def __deserializer_helper(dct):
        for k, v in dct.items():
            if isinstance(v, basestring) and len(v) == 19:
                try:
                    dct[k] = datetime.strptime(v, JsonHelper.DATE_FORMAT)
                except:
                    dct[k] = v
        return dct


import numpy as np
import cv2
from supporting_functions import get_coords
from supporting_functions import to_polar_coords

# Identify pixels above and/or below given thresholds
def color_thresh(img, lo=(0, 0, 0), hi=(255, 255, 255)):
    color_select = np.zeros_like(img[:,:,0])
    mask = (img[:,:,0] >= lo[0]) & (img[:,:,1] >= lo[1]) & (img[:,:,2] >= lo[2]) & \
           (img[:,:,0] <= hi[0]) & (img[:,:,1] <= hi[1]) & (img[:,:,2] <= hi[2])
    color_select[mask] = 1
    return color_select

# Define a function to convert from image coords to rover coords
def rover_coords(binary_img):
    # Identify nonzero pixels
    ypos, xpos = binary_img.nonzero()
    # Calculate pixel positions with reference to the rover position being at the
    # center bottom of the image.
    x_pixel = -(ypos - binary_img.shape[0]).astype(np.float)
    y_pixel = -(xpos - binary_img.shape[1]/2).astype(np.float)
    return x_pixel, y_pixel

# The inverse of rover_coords
def img_coords(img, x_pixel, y_pixel):
    ypos = (img.shape[0] - x_pixel).astype(int)
    xpos = (img.shape[1]/2 - y_pixel).astype(int)
    return xpos, ypos

# Define a function to map rover space pixels to world space
def rotate_pix(xpix, ypix, yaw):
    # Convert yaw to radians
    yaw_rad = yaw * np.pi / 180
    xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad))

    ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))
    # Return the result
    return xpix_rotated, ypix_rotated

def translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale):
    # Apply a scaling and a translation
    xpix_translated = (xpix_rot / scale) + xpos
    ypix_translated = (ypix_rot / scale) + ypos
    # Return the result
    return xpix_translated, ypix_translated

# Define a function to apply rotation and translation (and clipping)
# Once you define the two functions above this function should work
def pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):
    # Apply rotation
    xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)
    # Apply translation
    xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)
    # Perform rotation, translation and clipping all at once
    x_pix_world = np.clip(xpix_tran.astype(int), 0, world_size - 1)
    y_pix_world = np.clip(ypix_tran.astype(int), 0, world_size - 1)
    # Return the result
    return x_pix_world, y_pix_world

# Define a function to perform a perspective transform
def perspect_transform(img, src, dst):
    M = cv2.getPerspectiveTransform(src, dst)
    warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0])) # keep same size as input image
    return warped

# Helper class to encompass information about the rover and the world
class Perspective:
    def __init__(self, xpos, ypos, yaw, world_size, dst_size, img_shape):
        # position and orientation of the rover
        self.xpos = xpos
        self.ypos = ypos
        self.yaw = yaw
        # needed for transforming to world coordinates
        self.world_size = world_size
        self.scale = 2 * dst_size
        # needed for perspective transform
        bottom_offset = 6
        self.source = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])
        self.destination = np.float32([[img_shape[1]/2 - dst_size, img_shape[0] - bottom_offset],
                                       [img_shape[1]/2 + dst_size, img_shape[0] - bottom_offset],
                                       [img_shape[1]/2 + dst_size, img_shape[0] - 2*dst_size - bottom_offset],
                                       [img_shape[1]/2 - dst_size, img_shape[0] - 2*dst_size - bottom_offset]])
        # don't trust camera pixels too close to the horizon
        self.trust_area = ((0.0, -70.0), (70.0, 70))
        # we will use this enlarged box to keep track of unexplored areas
        self.mask_area = ((-10.0, -90.0), (80.0, 90))

# Helper class to calculate information about a subset of the terrain
class TerrainSet():
    def __init__(self, persp, camera_thresh_img):
        # apply transformation to rover coordinates
        self.threshed = camera_thresh_img
        self.x_rover, self.y_rover = rover_coords(perspect_transform(self.threshed, persp.source, persp.destination))
        # clip points far away close to the horizon (they're too far anyway and they mess up fidelity)
        self.x_rover = np.clip(self.x_rover.astype(int), persp.trust_area[0][0], persp.trust_area[1][0])
        self.y_rover = np.clip(self.y_rover.astype(int), persp.trust_area[0][1], persp.trust_area[1][1])
        self.x_img, self.y_img = img_coords(camera_thresh_img, self.x_rover, self.y_rover)
        self.warped = np.zeros_like(camera_thresh_img)
        self.warped[self.y_img, self.x_img] = 1
        self.x_world, self.y_world = pix_to_world(self.x_rover, self.y_rover, persp.xpos, persp.ypos, persp.yaw, persp.world_size, persp.scale)

# Helper class to calculate a mask over a given area relative to the rover
class TerrainMask():
    def __init__(self, persp, rover_area):
        self.x_rover, self.y_rover = get_coords(rover_area, 1.0)
        self.x_world, self.y_world = pix_to_world(self.x_rover, self.y_rover,
                                                  persp.xpos, persp.ypos, persp.yaw,
                                                  persp.world_size, persp.scale)

# Apply the above functions in succession and update the Rover state accordingly
def perception_step(Rover):

    img = Rover.img

    dst_size = 5

    rock_thresh_lo, rock_thresh_hi = (126, 106, 0), (255, 233, 84)
    navigable_thresh_lo = (170, 170, 170)

    persp = Perspective(xpos = Rover.pos[0], ypos = Rover.pos[1], yaw = Rover.yaw,
                        world_size = Rover.worldmap.shape[0], dst_size = dst_size, img_shape = img.shape)

    # Navigable terrain
    nav_terrain = TerrainSet(persp, color_thresh(img, lo=navigable_thresh_lo))

    # Obstacles
    obs_terrain = TerrainSet(persp, color_thresh(img, hi=navigable_thresh_lo))

    # Rock samples
    rock_terrain = TerrainSet(persp, color_thresh(img, lo=rock_thresh_lo, hi=rock_thresh_hi))

    if (rock_terrain.warped.any()):
        rock_dist, rock_ang = to_polar_coords(rock_terrain.x_rover, rock_terrain.y_rover)
        rock_idx = np.argmin(rock_dist)
        rock_x, rock_y = rock_terrain.x_world[rock_idx], rock_terrain.y_world[rock_idx]
        Rover.goal_distance, Rover.goal_angle, Rover.goal_last_seen = rock_dist[rock_idx], rock_ang[rock_idx], Rover.total_time
        Rover.worldmap[rock_y, rock_x, 1] = 255
        Rover.add_goal(np.array([rock_x, rock_y], dtype=float))
        print("ROCK IS IN SIGHT!", Rover.goal_distance, Rover.goal_angle)
    else:
        Rover.goal_distance, Rover.goal_angle = -1.0, 0.0
        print("CANT SEE ROCK!")

    # Calculate unexplored area
    # These masks are used to get a small unexplored area around the current view, to reduce the number of points in the distance graph
    current_view = TerrainSet(persp, np.ones_like(img[:,:,0]))
    extended_view = TerrainMask(persp, persp.mask_area)

    Rover.explored[current_view.x_world, current_view.y_world] = 1
    Rover.unexplored[extended_view.x_world, extended_view.y_world] = 1
    Rover.unexplored = (Rover.unexplored > 0) & (Rover.explored == 0)
    Rover.navigable[nav_terrain.x_world, nav_terrain.y_world] += 4
    Rover.navigable[obs_terrain.x_world, obs_terrain.y_world] -= 1

    # Polar coordinates for decision step
    dists, angles = to_polar_coords(nav_terrain.x_rover, nav_terrain.y_rover)
    obs_dists, obs_angles = to_polar_coords(obs_terrain.x_rover, obs_terrain.y_rover)
    obs_angles_ahead = obs_angles[np.nonzero(obs_dists < 10.0)]

    # Update the Rover worldmap
    Rover.worldmap[obs_terrain.y_world, obs_terrain.x_world, 0] += 1
    Rover.worldmap[nav_terrain.y_world, nav_terrain.x_world, 2] += 10

    # Update image to be displayed o the side
    Rover.vision_image[:, :, 0] = obs_terrain.warped * 255
    Rover.vision_image[:, :, 1] = rock_terrain.warped * 255
    Rover.vision_image[:, :, 2] = nav_terrain.warped * 255

    # Output for decision step
    Rover.nav_angles = np.setdiff1d(angles, obs_angles_ahead)

    return Rover


import math

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

def calc(x):
  return str(math.log(abs(12*math.sin(int(x)))))

link = "http://suninjuly.github.io/explicit_wait2.html"
browser = webdriver.Chrome()
browser.get(link)

WebDriverWait(browser, 12).until(
        EC.text_to_be_present_in_element((By.ID, "price"), '10000 RUR')
    )

browser.find_element_by_id("book").click()
browser.find_element_by_id('answer').send_keys(calc(browser.find_element_by_id('input_value').text))
browser.find_element_by_id('solve').click()

browser.quit()


'''
Python: 你不知道的 super
http://python.jobbole.com/86787/
----------------------------------------------
如果你认为 super 代表『调用父类的方法』，那你很可能会疑惑为什么 enter A 的下一句不是 enter Base 而是 enter B。
原因是，super 和父类没有实质性的关联，现在让我们搞清 super 是怎么运作的。
----------------------------------------------
super(cls, inst)
其中，cls 代表类，inst 代表实例，上面的代码做了两件事：

获取 inst 的 MRO 列表
查找 cls 在当前 MRO 列表中的 index, 并返回它的下一个类，即 mro[index + 1]
当你使用 super(cls, inst) 时，Python 会在 inst 的 MRO 列表上搜索 cls 的下一个类。

事实上，super 和父类没有实质性的关联。
super(cls, inst) 获得的是 cls 在 inst 的 MRO 列表中的下一个类。
'''
'''
Python:super函数
http://gohom.win/2016/02/23/py-super/
Python3中,super函数多了一种用法是直接super(),相当于super(type,首参), 这个首参就是一般的传入的self实例本身啦.
'''

class Base(object):
    def __init__(self):
        print("enter Base")
        print("leave Base")

class A(Base):
    def __init__(self):
        print("enter A")
        super(A, self).__init__()
        print("leave A")

class B(Base):
    def __init__(self):
        print("enter B")
        super(B, self).__init__()
        print("leave B")

class C(A, B):
    def __init__(self):
        print("enter C")
        super(C, self).__init__()
        print("leave C")

if __name__ == '__main__':
    c = C()


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the maxMin function below.
def maxMin(k, i_arr):
    # sliding window approach
    arr = sorted(i_arr)
    i = 0
    j = i + k - 1
    min_unfairness = 1000000000
    while j < len(i_arr):
        min_unfairness = min(min_unfairness, arr[j] - arr[i])
        i += 1
        j += 1

    return min_unfairness

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    k = int(input())

    arr = []

    for _ in range(n):
        arr_item = int(input())
        arr.append(arr_item)

    result = maxMin(k, arr)

    fptr.write(str(result) + '\n')

    fptr.close()


#!/usr/bin/env python
# coding: utf-8

# ## Weitere Matrix operationen

# In[2]:

import numpy as np

# In[3]:

A = np.array([
    [2, 5],
    [1, 3]
])

# #### Berechnen der Inverse
#
# Die Inverse von $A\in R^{n\times n}$ ist $A^{-1} \in R^{n\times n}$. Die Berechnung der Inverse ist sehr komplex und kann unter folgenden Link nachvollzogen werden.
# https://de.wikipedia.org/wiki/Inverse_Matrix

# In[4]:

A_inv = np.linalg.inv(A)
A_inv

# Um zu überprüfen, ob die Inverse korrekt ist, kann folgende Operation durchgeführt werden: $A\cdot A^{-1}=A^{-1}\cdot A=I$

# In[5]:

A.dot(A_inv)

# In[6]:

A_inv.dot(A)

# #### Berechnung der Determinante
#
# Die $0 \times 0$-Matrix hat die Determinante 1.
#
# Für eine nur aus einem Koeffizienten bestehende $1 \times 1$-Matrix $A$ ist: $\det A = \det \begin{pmatrix}
#  a_{11}
#  \end{pmatrix} = a_{11}.$
#
# Ist $A$ eine $2 \times 2$-Matrix, dann ist:
# $\det A=\det
#  \begin{pmatrix}
#  a_{11} & a_{12} \\
#  a_{21} & a_{22}
#  \end{pmatrix}
# = a_{11} a_{22} - a_{12} a_{21}.$
#
# Für eine $3 \times 3$-Matrix $A$ gilt die Formel:
# $\begin{align}
# \det A &= \det
#  \begin{pmatrix}
#  a_{11} & a_{12} & a_{13} \\
#  a_{21} & a_{22} & a_{23} \\
#  a_{31} & a_{32} & a_{33}
#  \end{pmatrix}
# \\ &= a_{11} a_{22} a_{33} +a_{12} a_{23} a_{31} + a_{13} a_{21} a_{32} - a_{13} a_{22} a_{31} - a_{12} a_{21} a_{33} - a_{11} a_{23} a_{32}.
# \end{align}$

# In[7]:

np.linalg.det([[1]])

# In[8]:

np.linalg.det([
    [1, 2],
    [3, 4]
])

# In[9]:

np.linalg.det([
    [1, 2, 3],
    [3, 2, 1],
    [2, 1, 3]
])

# #### Andere Operationen

# In[10]:

A = np.array([
    [2, 5],
    [1, 3]
])

# In[11]:

np.diag(A)

# In[12]:

np.diag([2, 3])

# In[13]:

np.diag(A).sum()

# In[14]:

np.trace(A)

Python/Tài liệu/Udemy/Kurs-Struktur mit Lösung/3 - NumPy/6 - Weitere Matrix operationen/Weitere_Matrix_operationen_instructor.py


import networkx as nx
import numpy as np
import itertools as it
import scipy.sparse as ssp

def count_subgraphs(B, nodes_U=None, nodes_O=None):
    """Counts subgraphs of a bipartite user-object graph.

   Returns
   - subgraphs[0]: o-u-o
   - subgraphs[1]: u-o-u
   - subgraphs[2]: o-u-o u
   - subgraphs[3]: o-u-o-u (path)
   - subgraphs[4]: cycle
   - subgraphs[5]: cycle + u
   - subgraphs[6]: cycle + o
   - subgraphs[7]: 3 users picking the same 2 objects (complete 3+2 bipartite)

    Keyword arguments:
    B -- networkx bipartite graph
    nodes_U -- the first set of nodes (default None)
    nodes_O -- the second set of nodes (default None)

    Reference used:
    [1] Filter values from a scipy sparse matrix, https://stackoverflow.com/questions/22074163/filter-values-from-a-scipy-sparse-matrix
    """
    subgraphs = np.zeros(8,dtype=np.int64)

    # if list of nodes is not given, it is assumed that the nodes are labeled according to set
    if (nodes_U==None and nodes_O==None):
        nodes_U = [u for u,d in B.nodes_iter(data=True) if d['bipartite']==0 or d['bipartite']=='u']
        nodes_O = [o for o,d in B.nodes_iter(data=True) if d['bipartite']==1 or d['bipartite']=='o']

    # get numbers of nodes
    num_U = len(nodes_U)
    num_O = len(nodes_O)

    B = nx.relabel_nodes(B, dict(zip(nodes_U+nodes_O,np.arange(num_U+num_O))), copy=True) # relabel nodes to integers
    del nodes_U, nodes_O # clear lists of node labels
    k_U,k_O = nx.bipartite.degrees(B,np.arange(num_U,num_U+num_O)) # get node degrees

    # use sparse matrix to store counts of possible pairs of objects that were bought by each user
    row = []
    col = []
    for u in xrange(num_U):
        if k_U[u] >= 2:
            objs = B.neighbors(u)
            objs.sort()
            o1,o2 = zip(*it.combinations(objs,2)) # all possible pairs of objects bought by user u
            row.extend(o1)
            col.extend(o2)
    pairs_O = ssp.coo_matrix((np.ones(len(row)),(row,col)),shape=(num_O+num_U,num_O+num_U)).tocsr()

    # build the sparse matrices for intermediate results in other subgraph computations
    row,col = pairs_O.nonzero()
    matrix_numU = ssp.coo_matrix(([num_U]*len(row),(row,col)),shape=(num_O+num_U,num_O+num_U)).tocsr()
    data_ksum = [ k_O[row[i]] + k_O[col[i]] for i in xrange(len(row)) ]
    pairsO_ksum = ssp.coo_matrix((data_ksum,(row,col)),shape=(num_O+num_U,num_O+num_U)).tocsr()
    ones = ssp.coo_matrix((np.ones(len(row)),(row,col)),shape=(num_O+num_U,num_O+num_U)).tocsr()
    twos = ssp.coo_matrix(([2]*len(row),(row,col)),shape=(num_O+num_U,num_O+num_U)).tocsr()
    squares = (pairs_O.multiply(pairs_O-ones)) / 2
    unique_neighbors = pairsO_ksum - 2*pairs_O

    # counting subgraphs
    subgraphs[0] = pairs_O.sum()
    subgraphs[2] = (matrix_numU - (pairsO_ksum - pairs_O)).sum()
    subgraphs[3] = unique_neighbors.sum()
    subgraphs[4] = squares.sum()
    subgraphs[5] = (squares.multiply(unique_neighbors)).sum()
    subgraphs[7] = ( (pairs_O.multiply(pairs_O-ones).multiply(pairs_O-twos)) / 6 ).sum()
    del pairs_O,twos

    # use sparse matrix to store counts of possible pairs of users who bought each object
    row = []
    col = []
    for o in xrange(num_U,num_U+num_O):
        if k_O[o] >= 2:
            usr = B.neighbors(o)
            usr.sort()
            u1,u2 = zip(*it.combinations(usr,2)) # all possible pairs of users who bought o
            row.extend(u1)
            col.extend(u2)
        B.remove_node(o)
    B.remove_nodes_from(B.nodes()) # clear graph to clear some memory

    pairs_U = ssp.coo_matrix((np.ones(len(row)),(row,col)),shape=(num_U,num_U)).tocsr()

    subgraphs[1] = pairs_U.sum() # count u-o-u subgraphs

    # intermediate results needed for subgraph 6 computation
    pairs_U = pairs_U.multiply(pairs_U > 1) # "filter out" all object pairs with 0 to 1 common users [1]
    row,col = pairs_U.nonzero()
    data_ksum = [ k_U[row[i]] + k_U[col[i]] for i in xrange(len(row)) ]
    pairsU_ksum = ssp.coo_matrix((data_ksum,(row,col)),shape=(num_U,num_U)).tocsr()
    ones = ssp.coo_matrix((np.ones(len(row)),(row,col)),shape=(num_U,num_U)).tocsr()
    squares = (pairs_U.multiply(pairs_U-ones)) / 2
    unique_neighbors = pairsU_ksum - 2*pairs_U

    subgraphs[6] = (squares.multiply(unique_neighbors)).sum() # counting cycle + o subgraphs

    return subgraphs


from PySide2 import QtCore
from PySide2.QtCore import Qt, QAbstractItemModel, QModelIndex, QSize, QTimer
from PySide2.QtGui import QPalette, QFontMetricsF
from PySide2.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget, QStyle, QSplitter, QLabel

import threading

import binaryninja
import binaryninjaui
from binaryninja import BinaryView, PythonScriptingInstance
from binaryninja.enums import InstructionTextTokenType
from binaryninjaui import View, ViewType, UIAction, UIActionHandler, LinearView, DisassemblyContainer, ViewFrame, DockHandler, TokenizedTextView

from . import widget, ControlsWidget
from .. import binjaplug

class DebugView(QWidget, View):
	def __init__(self, parent, data):
		if not type(data) == binaryninja.binaryview.BinaryView:
			raise Exception('expected widget data to be a BinaryView')

		self.bv = data

		self.debug_state = binjaplug.get_state(data)
		memory_view = self.debug_state.memory_view
		self.debug_state.ui.debug_view = self

		QWidget.__init__(self, parent)
		self.controls = ControlsWidget.DebugControlsWidget(self, "Controls", data, self.debug_state)
		View.__init__(self)

		self.setupView(self)

		self.current_offset = 0

		self.splitter = QSplitter(Qt.Orientation.Horizontal, self)

		frame = ViewFrame.viewFrameForWidget(self)
		self.memory_editor = LinearView(memory_view, frame)
		self.binary_editor = DisassemblyContainer(frame, data, frame)

		self.binary_text = TokenizedTextView(self, memory_view)
		self.is_raw_disassembly = False

		# TODO: Handle these and change views accordingly
		# Currently they are just disabled as the DisassemblyContainer gets confused
		# about where to go and just shows a bad view
		self.binary_editor.getDisassembly().actionHandler().bindAction("View in Hex Editor", UIAction())
		self.binary_editor.getDisassembly().actionHandler().bindAction("View in Linear Disassembly", UIAction())
		self.binary_editor.getDisassembly().actionHandler().bindAction("View in Types View", UIAction())

		self.memory_editor.actionHandler().bindAction("View in Hex Editor", UIAction())
		self.memory_editor.actionHandler().bindAction("View in Disassembly Graph", UIAction())
		self.memory_editor.actionHandler().bindAction("View in Types View", UIAction())

		small_font = QApplication.font()
		small_font.setPointSize(11)

		bv_layout = QVBoxLayout()
		bv_layout.setSpacing(0)
		bv_layout.setContentsMargins(0, 0, 0, 0)

		bv_label = QLabel("Loaded File")
		bv_label.setFont(small_font)
		bv_layout.addWidget(bv_label)
		bv_layout.addWidget(self.binary_editor)

		self.bv_widget = QWidget()
		self.bv_widget.setLayout(bv_layout)

		disasm_layout = QVBoxLayout()
		disasm_layout.setSpacing(0)
		disasm_layout.setContentsMargins(0, 0, 0, 0)

		disasm_label = QLabel("Raw Disassembly at PC")
		disasm_label.setFont(small_font)
		disasm_layout.addWidget(disasm_label)
		disasm_layout.addWidget(self.binary_text)

		self.disasm_widget = QWidget()
		self.disasm_widget.setLayout(disasm_layout)

		memory_layout = QVBoxLayout()
		memory_layout.setSpacing(0)
		memory_layout.setContentsMargins(0, 0, 0, 0)

		memory_label = QLabel("Debugged Process")
		memory_label.setFont(small_font)
		memory_layout.addWidget(memory_label)
		memory_layout.addWidget(self.memory_editor)

		self.memory_widget = QWidget()
		self.memory_widget.setLayout(memory_layout)

		self.splitter.addWidget(self.bv_widget)
		self.splitter.addWidget(self.memory_widget)

		# Equally sized
		self.splitter.setSizes([0x7fffffff, 0x7fffffff])

		layout = QVBoxLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setSpacing(0)
		layout.addWidget(self.controls)
		layout.addWidget(self.splitter, 100)
		self.setLayout(layout)

		self.needs_update = True
		self.update_timer = QTimer(self)
		self.update_timer.setInterval(200)
		self.update_timer.setSingleShot(False)
		self.update_timer.timeout.connect(lambda: self.updateTimerEvent())

		self.add_scripting_ref()

	def add_scripting_ref(self):
		# Hack: The interpreter is just a thread, so look through all threads
		# and assign our state to the interpreter's locals
		for thread in threading.enumerate():
			if type(thread) == PythonScriptingInstance.InterpreterThread:
				thread.locals["dbg"] = self.debug_state

	def getData(self):
		return self.bv

	def getCurrentOffset(self):
		return self.binary_editor.getDisassembly().getCurrentOffset()

	def getFont(self):
		return binaryninjaui.getMonospaceFont(self)

	def navigate(self, addr):
		return self.binary_editor.getDisassembly().navigate(addr)

	def notifyMemoryChanged(self):
		self.needs_update = True

	def updateTimerEvent(self):
		if self.needs_update:
			self.needs_update = False

			# Refresh the editor
			if not self.debug_state.connected:
				self.memory_editor.navigate(0)
				return

			self.memory_editor.navigate(self.debug_state.stack_pointer)

	def showEvent(self, event):
		if not event.spontaneous():
			self.update_timer.start()
			self.add_scripting_ref()

	def hideEvent(self, event):
		if not event.spontaneous():
			self.update_timer.stop()

	def shouldBeVisible(self, view_frame):
		if view_frame is None:
			return False
		else:
			return True

	def setRawDisassembly(self, raw=False, lines=[]):
		if raw != self.is_raw_disassembly:
			self.splitter.replaceWidget(0, self.disasm_widget if raw else self.bv_widget)
			self.is_raw_disassembly = raw

		# terrible workaround for libshiboken conversion issue
		for line in lines:
			# line is LinearDisassemblyLine
			last_tok = line.contents.tokens[-1]
			#if last_tok.type != InstructionTextTokenType.PossibleAddressToken: continue
			#if last_tok.width != 18: continue # strlen("0xFFFFFFFFFFFFFFF0")
			if last_tok.size != 8: continue
			#print('fixing: %s' % line)
			last_tok.value &= 0x7FFFFFFFFFFFFFFF

		self.binary_text.setLines(lines)

class DebugViewType(ViewType):
	def __init__(self):
		super(DebugViewType, self).__init__("Debugger", "Debugger")

	def getPriority(self, data, filename):
		return 1

	def create(self, data, view_frame):
		return DebugView(view_frame, data)


# -*- coding: utf-8 -*-
from odoo import api, fields, models
from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import datetime
from dateutil.relativedelta import relativedelta

DATE_FORMAT = "%Y-%m-%d"

class Booking(models.Model):
    _name = 'booking.booking'

    name = fields.Many2one('appointment.appointment', string='Appointment')
    state = fields.Selection([
        ('pending', 'Pending'),
        ('draft', 'Draft'),
        ('approved', 'Approved'),
        ('done', 'Complete')
    ], default='draft')
    init_date = fields.Date('Initial Date', default=datetime.today())
    init_time_from = fields.Float('Time From', default=0.0)
    init_time_to = fields.Float('Time To', default=0.0)
    new_date = fields.Date('New Date')
    new_time_from = fields.Float('New Time From')
    new_time_to = fields.Float('New Time To')
    contract_id = fields.Many2one('wedding.contract')
    belong_vendor = fields.Boolean('Belongs to Vendor?', compute="_compute_belong_vendor")
    vendor_job_lines = fields.One2many('vendor.job.line', 'booking_id', 'Vendor Jobs')
    staff_job_lines = fields.One2many('staff.job.line', 'booking_id', 'Staff Jobs')
    request_by = fields.Selection([
        ('customer', 'Customer'),
        ('system', 'System'),
    ], default='customer')
    contract_state = fields.Selection(related='contract_id.state')
    @api.depends('name')
    @api.multi
    def _compute_belong_vendor(self):
        for record in self:
            aptmnt = record.name
            if aptmnt.staff:
                record.belong_vendor = False
            else:
                record.belong_vendor = True

    @api.model
    def get_flexible_time(self, appointment_obj, date):
        if appointment_obj:
            BOOKING = self.env['booking.booking']
            TIME_AVAILBLE = self.env['time.available']
            flexible_time = []
            counter_hour = appointment_obj.duration_hour + appointment_obj.duration_minutes / 60.0
            name_date = date.strftime("%a")
            for line in appointment_obj.flexible_time:
                if line.name.upper() == name_date.upper():
                    count_time = line.start_time
                    while count_time < line.to_time:
                        booking_id1 = BOOKING.search([
                            ('init_date', '=', datetime.strftime(date, "%Y-%m-%d")),
                            ('init_time_from', '<=', count_time),
                            ('init_time_to', '>=', count_time + counter_hour), ('state','!=','draft')
                        ], limit=1)
                        booking_id2 = BOOKING.search([
                            ('init_date', '=', datetime.strftime(date, "%Y-%m-%d")),
                            ('init_time_from', '>', count_time) , ('init_time_from', '<',  count_time + counter_hour), ('state','!=','draft')
                        ], limit=1)
                        booking_id3 = BOOKING.search([
                            ('init_date', '=', datetime.strftime(date, "%Y-%m-%d")),
                            ('init_time_to', '>', count_time), ('init_time_to', '<', count_time + counter_hour), ('state','!=','draft')
                        ], limit=1)
                        if not booking_id1 and not booking_id2 and not booking_id3:
                            vals = {
                                'name': '{0:02.0f}:{1:02.0f}'.format(*divmod(count_time * 60, 60)),
                                'value': count_time
                            }
                            flexible_time.append(TIME_AVAILBLE.create(vals))
                        count_time += counter_hour
            return flexible_time

    def booking_approve(self):
        self = self.sudo()
        if self.new_time_to and self.new_time_from and self.new_date:
            self.init_date = self.new_date
            self.init_time_from = self.new_time_from
            self.init_time_to = self.new_time_to
            self.new_date = self.new_time_from = self.new_time_to = False
        self.state = 'approved'
        self.send_mail_approver_appointment()
        appointment = self.name
        for job in appointment.vendor_job:
            vals={
                'booking_id' : self.id,
                'name' : job.id,
                'employee_ids' : [(6, 0, job.employee_ids.ids)],
                'state' : 'draft',
            }
            self.env['vendor.job.line'].create(vals)
        return True

    def send_mail_approver_appointment(self):
        receivers =  self.contract_id.responsibility_partner_id.user_id.partner_id
        for receiver in receivers:
            base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
            url = base_url + '/web#id=%s&view_type=form&model=wedding.contract' % (self.contract_id.id)
            subject = 'Appointment Approved'
            message = """

                                       Dear %s,

                                        The Appointment of this Contract (%s) was approved.

                                       Appointment name : %s

                                       Date : %s

                                       From %s to %s

                                       Thank you

                                   """ % (
                receiver.name, url, self.contract_id.name, self.name.name, self.init_date,self.convert_float_time(self.init_time_from),self.convert_float_time(self.init_time_to)
            )
            self.mail_template_content(receiver, subject, message)
    def booking_complete(self):
        self.state = 'done'

    def send_mail_booking_system_schedule(self):
        receiver = self.contract_id.responsibility_partner_id.user_id.partner_id
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = base_url + '/web#id=%s&view_type=form&model=wedding.contract' % (self.contract_id.id)
        subject = 'Appointment Schedule Request'
        message = """

                           Dear %s,

                           You have a new Appointment of this Contract (%s) waiting for your approval.

                           Appointment name : %s

                           Date : %s

                           From %s to %s

                           Customer : %s

                           Thank you

                       """ % (receiver.name, url, self.contract_id.name, self.name.name, self.new_date,self.convert_float_time(self.new_time_from),self.convert_float_time(self.new_time_to)
                                    , self.contract_id.partner_id.name)
        self.mail_template_content(receiver, subject, message)
    def convert_float_time(self, number):
        return '{0:02.0f}:{1:02.0f}'.format(*divmod(number * 60, 60))

    def send_mail_booking_customer_schedule(self):
        receiver = self.contract_id.partner_id
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = base_url + '/web#id=%s&view_type=form&model=wedding.contract' % (self.contract_id.id)
        subject = 'Appointment Schedule Request'
        message = """

                           Dear %s,

                           You have a new Appointment of this Contract (%s) waiting for your approval.

                           Appointment name : %s

                           Date : %s

                           From %s to %s

                           Thank you

                       """ % (receiver.name, url, self.contract_id.name, self.name.name, self.new_date,self.convert_float_time(self.new_time_from),self.convert_float_time(self.new_time_to)
                                   )
        self.mail_template_content(receiver, subject, message)

    def send_mail_booking_system_reschedule(self):
        receiver =  self.contract_id.responsibility_partner_id.user_id.partner_id
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = base_url + '/web#id=%s&view_type=form&model=wedding.contract' % (self.contract_id.id)
        subject = 'Appointment Re-Schedule Request'
        message = """

                           Dear %s,

                           You have a new request for re-schedule Appointment of this Contract (%s) waiting for your approval.

                           Appointment name : %s

                           Date : %s

                           From %s to %s

                           Customer : %s

                           Thank you

                       """ % (
        receiver.name, url, self.contract_id.name, self.name.name, self.new_date,self.convert_float_time(self.new_time_from),self.convert_float_time(self.new_time_to)
        , self.contract_id.partner_id.name)
        self.mail_template_content(receiver, subject, message)

    def send_mail_booking_customer_reschedule(self):
        receiver = self.contract_id.partner_id
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = base_url + '/web#id=%s&view_type=form&model=wedding.contract' % (self.contract_id.id)
        subject = 'Appointment Schedule Request'
        message = """

                           Dear %s,

                            You have a new request for re-schedule Appointment of this Contract (%s) waiting for your approval.

                           Appointment name : %s

                           Date : %s

                           From %s to %s

                           Thank you

                       """ % (
        receiver.name, url, self.contract_id.name, self.name.name, self.new_date,self.convert_float_time(self.new_time_from),self.convert_float_time(self.new_time_to)
        )
        self.mail_template_content(receiver, subject, message)

    def mail_template_content(self, receiver, subject, message):
        receiver = receiver
        email_from = self.env.user.company_id.email
        email_to = receiver.email
        subject = subject
        message = message

        vals = {
            'state': 'outgoing',
            'subject': subject,
            'body_html': '
%s
' % message,
            'email_to': email_to,
            'email_from': email_from,
        }
        partner_id = receiver
        mail_message = {
            'subject': subject,
            'body': '
%s
' % message,
            'partner_ids': [(6, 0, [partner_id.id])],
            'needaction_partner_ids': [(6, 0, [partner_id.id])]
        }
        thread_pool = self.env['mail.message'].create(mail_message)
        thread_pool.needaction_partner_ids = [(6, 0, [partner_id.id])]
        # if vals:
        #     self = self.with_context(default_state='outgoing')
        #     email_id = self.with_context(default_state='outgoing').env['mail.mail'].create(vals)
        #     if email_id:
        #         email_id.send()

class VendorJobLine(models.Model):
    _name = 'vendor.job.line'

    booking_id = fields.Many2one('booking.booking')
    name = fields.Many2one('vendor.job', 'Job')
    employee_ids = fields.Many2many('hr.employee', string='Employees')
    state = fields.Selection([
        ('draft', 'Draft'),
        ('pending', 'Pending'),
        ('approved', 'Approve'),
        ('refuse', 'Refuse'),
    ] , default='draft')

    @api.onchange('name')
    def _onchange_name(self):
        if self.name:
            employee_ids = self.name.employee_ids.ids
            return {
                'domain': {
                    'employee_ids': [('id', 'in', employee_ids)]
                }
            }
        else:
            appointment = self.booking_id.name
            return {
                'domain': {
                    'name' : [('id','in', appointment.vendor_job.ids)],
                    'employee_ids': [('id', 'in', [])]
                }
            }

    @api.onchange('employee_ids')
    def _onchange_employee_ids(self):
        if self.name:
            employee_ids = self.name.employee_ids.ids
            return {
                'domain': {
                    'employee_ids': [('id', 'in', employee_ids)]
                }
            }

    def action_send_request(self):
        appointment_obj = self.booking_id.name
        contract_obj = self.booking_id.contract_id
        VendorJobRequest = self.env['vendor.job.request']
        for employee in self.employee_ids:
            vals = {
                'appointment': appointment_obj.name,
                'contract_id': contract_obj.id,
                'name': self.name.name,
                'date': self.booking_id.init_date,
                'time_from': self.booking_id.init_time_from,
                'time_to': self.booking_id.init_time_to,
                'employee_id': employee.id,
                'vendor_job_line_id': self.id,
            }
            job_request = VendorJobRequest.create(vals)
            self.send_mail_employee_job_request(job_request.employee_id.user_id.partner_id , job_request)
        self.state = 'pending'

    def send_mail_employee_job_request(self, receiver, job):
        receiver = receiver
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = base_url + '/web#id=%s&view_type=form&model=vendor.job.request' % (job.id)
        subject = 'Job Request'
        message = """

                                   Dear %s,

                                    You have a new request for this job (%s) waiting for your approval.

                                   Job name : %s

                                   Date : %s

                                   From %s to %s

                                   Thank you

                               """ % (
            receiver.name, url, job.name, job.name, job.date,
            self.booking_id.convert_float_time(job.time_from), self.booking_id.convert_float_time(job.time_to)
        )

        self.booking_id.mail_template_content(receiver, subject, message)

class StaffJobLine(models.Model):
    _name = 'staff.job.line'

    booking_id = fields.Many2one('booking.booking')
    name = fields.Many2one('staff.job', 'Job')
    employee_ids = fields.Many2many('hr.employee', string='Employees')

    @api.onchange('name')
    def _onchange_name(self):
        if self.name:
            employee_ids = self.name.employee_ids.ids
            return {
                'domain': {
                    'employee_ids': [('id', 'in', employee_ids)]
                }
            }

class Employee(models.Model):
    _inherit = 'hr.employee'

    staff_job_ids = fields.Many2many('staff.job.line', string="Staff Job Line")
    vendor_job_ids = fields.Many2many('vendor.job.line', string="Vendor Job Line")
    is_saleteam = fields.Boolean('Sale Team')

    def name_get(self):
        if not self._context.get('job_name'):
            return super(Employee, self).name_get()
        res = []
        employees = self.sudo().search([('job_id','=',self._context.get('job_name', False))])
        for record in self:
            if record.id in employees.ids:
                name = record.name
                res.append((record.id, name))
        return res


# http://bigocoder.com/courses/OBLUE01/OBLUE01_LEC06/BLUE_L06P01/statement

n = int(input())

graph = [[] for i in range(n)]

for i in range(n-1):
    x = list(map(int,input().split()))
    x[0],x[1] = x[0]-1,x[1]-1
    graph[x[0]].append(x[1])
    graph[x[1]].append(x[0])

q = int(input())

girls = []

for i in range(q):
    x = int(input())
    girls.append(x-1)

visited = [False] * n
path = [-1] * n

def DFS(s):
    visited[s] = True
    stack = []
    stack.append(s)
    while len(stack)>0:
        u = stack.pop()
        for i in graph[u]:
            if not visited[i]:
                visited[i] = True
                stack.append(i)
                path[i] = u

DFS(0)

pos = [0] * n

for i in girls:
    count = 0
    mark = i
    while mark != -1:
        mark = path[mark]
        count += 1
    pos[i] = count

_min = n*n
mark = 0

for i in range(n):
    if _min > pos[i] and pos[i] != 0:
        _min = pos[i]
        mark = i

print(mark + 1)


class exchangeRates:
    """This class is used to establish the formula used to convert the value"""
    def __init__(self, amount, rate):
        self.amount = amount
        self.rate = rate

    def exchangeEquation(self):
        return self.amount * self.rate

def importFile(valToEquate):
    """ This method inputs file and splits data into list"""
    infileName = input("Please enter the name of the file: ")
    infile = open(infileName, "r")
    for line in infile:
        valToEquate.append(line)
    return valToEquate

def outputFile(curVal):
    """This method pushes the newly converted amount to the output file"""
    outfileName = input("Please enter file name to output the new value to: ")
    outfile = open(outfileName, "w")
    print(curVal.exchangeEquation(), file=outfile)

def main ():
    valToEquate = []
    importFile(valToEquate)
    b4Val = valToEquate[1]
    b4Val = float(b4Val)
    """These if-else statements are used to determine which exchange rate should be applied
        to create an object using the exchangeRates class"""
    if "usd" in valToEquate[0] and "gbp" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 0.75)

    elif "gbp" in valToEquate[0] and "usd" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 1.34)

    elif "usd" in valToEquate[0] and "euro" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 0.83)

    elif "euro" in valToEquate[0] and "usd" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 1.21)

    elif "usd" in valToEquate[0] and "yuan" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 6.54)

    elif "yuan" in valToEquate[0] and "usd" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 0.15)

    elif "usd" in valToEquate[0] and "ruble" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 73.83)

    elif "ruble" in valToEquate[0] and "usd" in valToEquate[2]:
        curVal = exchangeRates(b4Val, 0.014)
    else:
        print("That was the incorrect format. Please review your input file and try again.")

    outputFile(curVal)
main()


from scipy.ndimage import convolve
from sklearn import datasets
import numpy as np
from sklearn.datasets import fetch_mldata

##############################
#            DATA            #
##############################

def load_data():
    """
    Charge les digits avec convolution et normalisation 0-1

    Output :
        - X digits
        - Y labels
    """
    print("hopla")
    # mnist = fetch_mldata('MNIST original', data_home='../data')
    # print(mnist.data.shape)
    digits = datasets.load_digits()
    # X = mnist.data
    # Y = mnist.Y
    X = np.asarray(digits.data, 'float32')
    X, Y = nudge_dataset(X, digits.target)
    X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001)
    return X, Y

def nudge_dataset(X, Y):
    """
    Multiplie la taille de X par 5 en translatant les images

    Input :
        - X digits
        - Y labels

    Input :
        - X digits
        - Y labels
    """
    direction_vectors = [
        [[0, 1, 0],
         [0, 0, 0],
         [0, 0, 0]],

        [[0, 0, 0],
         [1, 0, 0],
         [0, 0, 0]],

        [[0, 0, 0],
         [0, 0, 1],
         [0, 0, 0]],

        [[0, 0, 0],
         [0, 0, 0],
         [0, 1, 0]]]

    shift = lambda x, w: convolve(x.reshape((8, 8)), mode='constant',
                                  weights=w).ravel()
    X = np.concatenate([X] +
                       [np.apply_along_axis(shift, 1, X, vector)
                        for vector in direction_vectors])
    Y = np.concatenate([Y for _ in range(5)], axis=0)
    return X, Y


from jawbone import Jawbone
import csv
import datetime
import urllib

code = 'aV1SI82xvTp7yNo9mcqXNzAMdEzLI7j65MDz9woxiPz7xAtMk3eVufj10-ItJz4R9WnvKI-GaClbU4JadEd7yCHvFlpwU6ifgf1sDnoQ8zQXdB24evV0_J9g7lSkKu4wpmp8xnxzsxVNWa81PUm-HX1RJ4nRH1zRl5cyeb8zhWTk8lNHm2EhXTlQUbAogm-8'

jb = Jawbone()

url = jb.doAuth()
print(url)

access_token = jb.getAccessToken(code)
print(access_token)

#me = jb.api_call(access_token, '/nudge/api/users/@me')
#print(me)

#xid = jb.getUserId(access_token)
#print(xid)

moves = jb.doApiCall(access_token, '/nudge/api/users/@me/moves')

move_items = moves['data']['items']
move_counts = moves['data']['size']

x = []

print(move_counts)
for move in move_items:
    for day_hour_id in move['details']['hourly_totals']:
        x.append({'time_updated': datetime.datetime.fromtimestamp(move['time_updated']).strftime('%Y-%m-%d %H:%M:%S'),
              'xid': move['xid'],
              'title': move['title'],
              'type': move['type'],
              'time_created': datetime.datetime.fromtimestamp(move['time_created']).strftime('%Y-%m-%d %H:%M:%S'),
              'time_completed': datetime.datetime.fromtimestamp(move['time_completed']).strftime('%Y-%m-%d %H:%M:%S'),
              'date': move['date'],
              'snapshot_image':move['snapshot_image'],
              'distance': move['details']['distance'],
              'wo_active_time': move['details']['wo_active_time'], #datetime.datetime.fromtimestamp(move['details']['wo_active_time']).strftime('%H:%M:%S'),
              'tz': move['details']['tz'],
              'active_time': datetime.datetime.fromtimestamp(move['details']['active_time']).strftime('%H:%M:%S'),
              'inactive_time': datetime.datetime.fromtimestamp(move['details']['inactive_time']).strftime('%H:%M:%S'),
              'longest_idle': datetime.datetime.fromtimestamp(move['details']['longest_idle']).strftime('%H:%M:%S'),
              'calories': move['details']['calories'],
              'wo_count': move['details']['wo_count'],
              'wo_longest': move['details']['wo_longest'],
              'bmr': move['details']['bmr'],
              'bg_calories': move['details']['bg_calories'],
              'steps': move['details']['steps'],
              'km': move['details']['km'],
              'wo_calories': move['details']['wo_calories'],
              'bmr_day': move['details']['bmr_day'],
              'day_hour_id': day_hour_id,
              'hourly_distance': move['details']['hourly_totals'][day_hour_id]['distance'],
              'hourly_active_time': datetime.datetime.fromtimestamp(move['details']['hourly_totals'][day_hour_id]['active_time']).strftime('%H:%M:%S'),
              'hourly_calories': move['details']['hourly_totals'][day_hour_id]['calories'],
              'hourly_steps': move['details']['hourly_totals'][day_hour_id]['steps'],
              'hourly_longest_idle_time': datetime.datetime.fromtimestamp(move['details']['hourly_totals'][day_hour_id]['longest_idle_time']).strftime('%H:%M:%S'),
              'hourly_inactive_time': datetime.datetime.fromtimestamp(move['details']['hourly_totals'][day_hour_id]['inactive_time']).strftime('%H:%M:%S'),
              'hourly_longest_active_time': datetime.datetime.fromtimestamp(move['details']['hourly_totals'][day_hour_id]['longest_active_time']).strftime('%H:%M:%S')
              }
             )

f = csv.writer(open('data/csv/moves.csv', 'wb+'))

f.writerow(x[0].keys())
x = sorted(x)

print(x[0].keys())
for item in x:
    f.writerow(item.values())
    print(item.values())
    urllib.urlretrieve('https://jawbone.com/' + item['snapshot_image'], 'images/'+str(item['date'])+'.png')

#moves_detail = jb.api_call(j['access_token'], '/nudge/api/moves/q2ECdXazI-46Lmf4bhJQGA')
#print(moves_detail)

#moves_graph =  jb.api_call(j['access_token'], '/nudge/api/moves/q2ECdXazI-46Lmf4bhJQGA/image')
#print(moves_graph)

#moves_ticks =  jb.api_call(j['access_token'], '/nudge/api/moves/q2ECdXazI-46Lmf4bhJQGA/ticks')
#print(moves_ticks)


# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
"""Cloud Pub/Sub subscriptions update command."""

from apitools.base.py import exceptions as api_ex

from googlecloudsdk.api_lib.util import exceptions
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.pubsub import util
from googlecloudsdk.core import log

DEFAULT_MESSAGE_RETENTION_VALUE = 'default'

def _Duration():
  """Returns a function that can parse time duration args.

  This is an extension of googlecloudsdk.calliope.arg_parsers.Duration() to
  a) Format the result as expected for a Duration proto field, and
  b) Allow for a special default string value.

  Raises:
    An ArgumentTypeError if the input cannot be parsed.

  Returns:
    A function that accepts a single time duration as input to be parsed.
  """
  def ParseWithDefault(value):
    if value == DEFAULT_MESSAGE_RETENTION_VALUE:
      return DEFAULT_MESSAGE_RETENTION_VALUE
    return str(arg_parsers.Duration()(value)) + 's'

  return ParseWithDefault

@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(base.UpdateCommand):
  """This feature is part of an invite-only release of the Cloud Pub/Sub API.

  Updates an existing Cloud Pub/Sub subscription.
  This feature is part of an invitation-only release of the underlying
  Cloud Pub/Sub API. The command will generate errors unless you have access to
  this API. This restriction should be relaxed in the near future. Please
  contact cloud-pubsub@google.com with any questions in the meantime.
  """

  @staticmethod
  def Args(parser):
    """Registers flags for this command."""

    parser.add_argument('subscription',
                        help='Name of the subscription to update.')

    parser.add_argument(
        '--ack-deadline', type=int,
        help=('The number of seconds the system will wait for a subscriber to'
              ' acknowledge receiving a message before re-attempting'
              ' delivery.  If set to 0, the system default to be used.'))

    parser.add_argument(
        '--push-endpoint',
        help=('A URL to use as the endpoint for this subscription.'
              ' This will also automatically set the subscription'
              ' type to PUSH.'))

    parser.add_argument(
        '--retain-acked-messages',
        action='store_true',
        default=None,
        help=('Whether or not to retain acknowledged messages.  If true,'
              ' messages are not expunged from the subscription\'s backlog'
              ' until they fall out of the --message-retention-duration'
              ' window.'))

    parser.add_argument(
        '--message-retention-duration',
        type=_Duration(),
        help=('How long to retain unacknowledged messages in the'
              ' subscription\'s backlog, from the moment a message is'
              ' published.  If --retain-acked-messages is true, this also'
              ' configures the retention of acknowledged messages.  Specify'
              ' "default" to use the default value.  Valid values are strings'
              ' of the form INTEGER[UNIT] or "default", where UNIT is one of'
              ' "s", "m", "h", and "d" for seconds, minutes, hours, and days,'
              ' respectively.  If the unit is omitted, seconds is assumed.'))

  def Collection(self):
    return util.SUBSCRIPTIONS_COLLECTION

  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.

    Raises:
      An HttpException if there was a problem calling the
      API subscriptions.Patch command.
    """
    msgs = self.context['pubsub_msgs']
    pubsub = self.context['pubsub']

    name = util.SubscriptionFormat(args.subscription)

    mask = []
    subscription = msgs.Subscription(name=name)
    if args.ack_deadline is not None:
      mask.append('ackDeadlineSeconds')
      subscription.ackDeadlineSeconds = args.ack_deadline
    if args.push_endpoint is not None:
      mask.append('pushConfig')
      subscription.pushConfig = msgs.PushConfig(pushEndpoint=args.push_endpoint)
    if args.retain_acked_messages is not None:
      mask.append('retainAckedMessages')
      subscription.retainAckedMessages = args.retain_acked_messages
    if args.message_retention_duration is not None:
      mask.append('messageRetentionDuration')
      if args.message_retention_duration != DEFAULT_MESSAGE_RETENTION_VALUE:
        subscription.messageRetentionDuration = args.message_retention_duration

    patch_req = msgs.PubsubProjectsSubscriptionsPatchRequest(
        updateSubscriptionRequest=msgs.UpdateSubscriptionRequest(
            subscription=subscription,
            updateMask=','.join(mask)),
        name=name)

    # TODO(b/32275310): Conform to gcloud error handling guidelines.  This is
    # currently consistent with the rest of the gcloud pubsub commands.
    try:
      result = pubsub.projects_subscriptions.Patch(patch_req)
      failed = None
    except api_ex.HttpError as error:
      result = subscription
      exc = exceptions.HttpException(error)
      failed = exc.payload.status_message

    result = util.SubscriptionDisplayDict(result, failed)
    log.UpdatedResource(name, kind='subscription', failed=failed)
    return result


# Sample program made by Filip Petrovic / fpetrovicc on github.
# Available on PythonLearn repository on github.
# It is for practice exclusively.

import os

os.system('cls')
input('Welcome to my bar!')

os.system('cls')
playerName = input('What\'s your name? ')
os.system('cls')
playerAge = int(input('And how old are you, %s? ' % playerName))
os.system('cls')

minimalAge = int(18)

if (playerAge >= minimalAge):
	os.system('cls')
	print('Hey! Come on in, %s!' % playerName)
else:
    print('Get out of here before i call the police!')

def pressAnyKey():
	input('Press any key to exit.')
	os.system('cls')

pressAnyKey()
raise SystemExit


# minifileset.py - a simple language to select files
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import absolute_import

from .i18n import _
from . import (
    error,
    fileset,
)

def _compile(tree):
    if not tree:
        raise error.ParseError(_("missing argument"))
    op = tree[0]
    if op in {'symbol', 'string', 'kindpat'}:
        name = fileset.getpattern(tree, {'path'}, _('invalid file pattern'))
        if name.startswith('**'): # file extension test, ex. "**.tar.gz"
            ext = name[2:]
            for c in ext:
                if c in '*{}[]?/\\':
                    raise error.ParseError(_('reserved character: %s') % c)
            return lambda n, s: n.endswith(ext)
        elif name.startswith('path:'): # directory or full path test
            p = name[5:] # prefix
            pl = len(p)
            f = lambda n, s: n.startswith(p) and (len(n) == pl or n[pl] == '/')
            return f
        raise error.ParseError(_("unsupported file pattern: %s") % name,
                               hint=_('paths must be prefixed with "path:"'))
    elif op == 'or':
        func1 = _compile(tree[1])
        func2 = _compile(tree[2])
        return lambda n, s: func1(n, s) or func2(n, s)
    elif op == 'and':
        func1 = _compile(tree[1])
        func2 = _compile(tree[2])
        return lambda n, s: func1(n, s) and func2(n, s)
    elif op == 'not':
        return lambda n, s: not _compile(tree[1])(n, s)
    elif op == 'group':
        return _compile(tree[1])
    elif op == 'func':
        symbols = {
            'all': lambda n, s: True,
            'none': lambda n, s: False,
            'size': lambda n, s: fileset.sizematcher(tree[2])(s),
        }

        name = fileset.getsymbol(tree[1])
        if name in symbols:
            return symbols[name]

        raise error.UnknownIdentifier(name, symbols.keys())
    elif op == 'minus':     # equivalent to 'x and not y'
        func1 = _compile(tree[1])
        func2 = _compile(tree[2])
        return lambda n, s: func1(n, s) and not func2(n, s)
    elif op == 'negate':
        raise error.ParseError(_("can't use negate operator in this context"))
    elif op == 'list':
        raise error.ParseError(_("can't use a list in this context"),
                               hint=_('see hg help "filesets.x or y"'))
    raise error.ProgrammingError('illegal tree: %r' % (tree,))

def compile(text):
    """generate a function (path, size) -> bool from filter specification.

    "text" could contain the operators defined by the fileset language for
    common logic operations, and parenthesis for grouping.  The supported path
    tests are '**.extname' for file extension test, and '"path:dir/subdir"'
    for prefix test.  The ``size()`` predicate is borrowed from filesets to test
    file size.  The predicates ``all()`` and ``none()`` are also supported.

    '(**.php & size(">10MB")) | **.zip | (path:bin & !path:bin/README)' for
    example, will catch all php files whose size is greater than 10 MB, all
    files whose name ends with ".zip", and all files under "bin" in the repo
    root except for "bin/README".
    """
    tree = fileset.parse(text)
    return _compile(tree)


import sys

sys.setrecursionlimit(10 ** 6)
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")

t = int(input())

while t:
    t -= 1
    n = input()
    arr = list(map(int,input().split()))
    k = int(input())
    ele = arr[k-1]
    sort_arr = sorted(arr)
    print(sort_arr.index(ele) + 1)


from load_django_settings import CURRENT_DIR, TEST_DATA_DIR, load_local_settings
load_local_settings()

import json, time
from os.path import isfile, join

from opendp_project.celery import hello_task
from django.core.serializers.json import DjangoJSONEncoder
from opendp_apps.profiler.tasks import ProfileHandler
from opendp_apps.profiler import tasks as profiler_tasks
from opendp_apps.dataset.models import DataSetInfo
from opendp_apps.dataset.models import DataverseFileInfo
from opendp_apps.dataverses.dataverse_download_handler import DataverseDownloadHandler

def test_downloader(dataverse_file_id=3):
    """Test profiler with file"""

    print('get object')
    dfi = DataverseFileInfo.objects.get(pk=dataverse_file_id)
    print('dfi: ', dfi)

    # ---------------------------
    # download check!
    # ---------------------------
    print('-' * 40)
    print('Download Info')
    print('-' * 40)
    dhandler = DataverseDownloadHandler(dfi)
    if dhandler.has_error():
        print('error: ', dhandler.get_err_msg())
        return
    else:
        print('looks good!')

    # ---------------------------
    # profile it!
    # ---------------------------
    print('-' * 40)
    print('Profile it')
    print('-' * 40)
    profile_handler = profiler_tasks.run_profile_by_filefield(dfi.object_id)
    if profile_handler.has_error():
        print('error: ', profile_handler.get_err_msg())
        return
    else:
        print(profile_handler.data_profile)
        print(json.dumps(profile_handler.data_profile, cls=DjangoJSONEncoder, indent=4))
        print('profiled!')

if __name__=='__main__':
    test_downloader(dataverse_file_id=5)

"""
docker-compose run server python scripts_dev/test_downloader.py
docker-compose run server python scripts_dev/test_profiler.py

docker-compose run server python manage.py dumpdata dataverses.registereddataverse --indent=4 --pks=1
docker-compose run server python manage.py dumpdata dataset.datasetinfo --indent=4 --pks=3
docker-compose run server python manage.py dumpdata analysis.depositorsetupinfo --indent=4 --pks=3

docker-compose run server python manage.py dumpdata dataset.dataversefileinfo  --indent=4 --pks=3

"""


'''docstring'''
import os, sys
import traceback
#from datetime import date
#sys.path.append('c:\\greg\\code\\python')
#from PathExists import PathExists

class UserFileOpen(object):
    #This class simply prompts a user to select a file
    filename_with_path = ''
    path_only = ''

    '''
	def file_data_and_path(self, filename):
        print('\n' + 'File: ' + filename + '... File? ' + str(os.path.isfile(filename)) + ' ... Folder? ' + str(os.path.isdir(filename)))
        #print('\n' + 'File: ' + string.replace(filename, "\", "\\\") + '... File? ' + str(os.path.isfile(filename)) + ' ... Folder? ' + str(os.path.isdir(filename)))
        self.filename_with_path = filename
        if os.path.isfile(filename) or os.path.isdir(filename):
            if os.path.isfile(filename):
                self.path_only = os.path.dirname(filename)
                with open(filename,"rU") as f:          #Open the file in uninversal Newline mode -- http://stackoverflow.com/questions/6726953/open-the-file-in-universal-newline-mode-using-csv-module-django
                    lines = f.readlines()
                return lines,self.path_only
            elif os.path.isdir(filename):
                #Display a full tree of files under this folder
                for dirname, dirnames, filenames in os.walk('.'):
                    # print path to all subdirectories first.
                    for subdirname in dirnames:
                        print(os.path.join(dirname, subdirname))
                    # print path to all filenames.
                    for filename in filenames:
                        print(os.path.join(dirname, filename))
                self.path_only = filename
                print('\n' + 'File: ' + filename + '... File? ' + str(os.path.isfile(filename)) + ' ... Folder? ' + str(os.path.isdir(filename)))
                return 'Folder contents', self.path_only
        else:
            print("Invalid File Path, File Doesn't exist")
            return None,None
    '''

    def prompt_user_for_path(self, return_path_before_filename=True):
        '''Wait for user to input the file path and name'''
        msg = '\n' + 'Enter path to the CSV folder: '
        filename = input(msg).strip()
        if os.path.isfile(filename) or os.path.isdir(filename):
            self.filename_with_path = filename
            if os.path.isfile(filename):
                self.path_only = os.path.dirname(filename)
            elif os.path.isdir(filename):
                self.path_only = filename
        #lines,path = self.file_data_and_path(filename)
        #if lines != None and path != None:
            #for line in lines:
            #    print(lines)
            #print('\n' + 'Path:',path)
        print('\n' + 'File: ' + self.filename_with_path + '... File? ' + str(os.path.isfile(self.filename_with_path)) + ' ... Folder? ' + str(os.path.isdir(self.filename_with_path)))
        if return_path_before_filename:
            return self.path_only, self.filename_with_path
        else:
            return self.filename_with_path

#------------------------------------------------------------------------------------
if __name__ == '__main__':
    print('About to create an instance of UserFileOpen class.')
    fo = UserFileOpen()
    fo.prompt_user_for_path()


print("********** Aliquat Function **********")
def aliquat(args):
    aliquats=[]
    for i in range(1,args+1):
        if args%i==0:
            aliquats.append(i)
    return aliquats
while True:
    while True:
     x=input("Please enter a number you would like to find the aliquots.\n")
     if x.isdigit():
        x=int(x)
        print(*aliquat(x))
        break
     else:
        print("You made an incorrect entry. Please enter only positive number!!!")
        continue
    while True:
     q=input("""Would you like to quit? If yes please press "q", if no please press "ENTER".
""")
     if q.lower()=="q":
        print("Program terminated.")
        exit()
     elif not q:
        break
     else:
        print("You made an incorrect entry. Please check and read instructions!!!")


# -*- coding: utf-8 -*-
# Copyright 2015 Vince Veselosky and contributors.
#
# 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.
from __future__ import absolute_import, print_function
from jinja2 import BaseLoader, TemplateNotFound
from botocore.exceptions import ClientError
import boto3
from gzip import GzipFile
from io import BytesIO
import posixpath as path

def gzip(content, filename=None, compresslevel=9):
    gzbuffer = BytesIO()
    gz = GzipFile(filename, 'wb', compresslevel, gzbuffer)
    gz.write(content)
    gz.close()
    return gzbuffer.getvalue()

def gunzip(gzcontent):
    gzbuffer = BytesIO(gzcontent)
    return GzipFile(None, 'rb', fileobj=gzbuffer).read()

class S3loader(BaseLoader):

    def __init__(self, bucket, prefix='', s3=None):
        self.bucket = bucket
        self.prefix = prefix
        self.s3 = s3 or boto3.client('s3')
        super(S3loader, self).__init__()

    def get_source(self, environment, template):
        if self.prefix:
            template = path.join(self.prefix, template)
        try:
            resp = self.s3.get_object(Bucket=self.bucket, Key=template)
        except ClientError as e:
            if "NoSuchKey" in e.__str__():
                raise TemplateNotFound(template)
            else:
                raise e
        if 'ContentEncoding' in resp and 'gzip' in resp['ContentEncoding']:
            body = gunzip(resp['Body'].read())
        else:
            body = resp['Body'].read()
        return (body.decode('utf-8'), None, lambda: True)