import math

from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import messages

from . import api

def _exp_range(exp, start, end):
    return map(lambda x: exp ** x,
        range(int(math.log(start, exp)), int(math.ceil(math.log(end, exp)))))

def _build_freq_choices():
    freq_choices = map(lambda x: (60 * x, "Every %d minutes" % x),
                    range(10, 60, 10))
    freq_choices.append((60*60, "Every hour"))
    freq_choices.extend(map(lambda x: (60*60 * x, "Every %d hours" % x),
                            _exp_range(2, 2, 24)))
    freq_choices.append((60*60*24, "Every day"))
    freq_choices.extend(map(lambda x: (60*60*24 * x, "Every %d days" % x),
                            range(2, 7)))
    freq_choices.append((60*60*24*7, "Every week"))
    return freq_choices

def _build_ret_choices():
    ret_choices = [(60*60, "For the last hour")]
    ret_choices.extend(map(lambda x: (60*60 * x, "For the last %d hours" % x),
                            _exp_range(2, 2, 24)))
    ret_choices.append((60*60*24, "For the last day"))
    ret_choices.extend(map(lambda x: (60*60*24 * x, "For the last %d days" % x),
                            range(2, 7)))
    ret_choices.append((60*60*24*7, "For the last week"))
    ret_choices.extend(map(
        lambda x: (60*60*24*7 * x, "For the last %d weeks" % x), range(2, 6)))
    return ret_choices

class CreateSchedule(forms.SelfHandlingForm):
    instance_id = forms.CharField(label=_("Instance ID"),
                                  widget=forms.HiddenInput())
    frequency = forms.ChoiceField(choices=_build_freq_choices())
    retention = forms.ChoiceField(choices=_build_ret_choices())

    def clean(self):
        data = super(CreateSchedule, self).clean()
        if int(data['frequency']) >= int(data['retention']):
            raise ValidationError(
                _("Retention must be greater than Frequency"))
        else:
            return data

    def handle(self, request, data):
        try:
            schedules = api.schedule_create(request,
                                            data['instance_id'],
                                            int(data['frequency']),
                                            int(data['retention']))
            messages.success(request, _('Schedule created'))
            return True
        except:
            redirect = reverse("horizon:project:veta:index")
            exceptions.handle(request,
                              _('Unable to create schedule.'),
                              redirect=redirect)

class EditSchedule(forms.SelfHandlingForm):
    instance_id = forms.CharField(label=_("Instance ID"),
                                  widget=forms.HiddenInput())
    schedule_id = forms.CharField(label=_("Schedule ID"),
                                  widget=forms.HiddenInput())
    frequency = forms.ChoiceField(choices=_build_freq_choices())
    retention = forms.ChoiceField(choices=_build_ret_choices())

    def clean(self):
        data = super(EditSchedule, self).clean()
        if int(data['frequency']) >= int(data['retention']):
            raise ValidationError(
                _("Retention must be greater than Frequency"))
        else:
            return data

    def handle(self, request, data):
        try:
            schedules = api.schedule_update(request,
                                            data['instance_id'],
                                            data['schedule_id'],
                                            int(data['frequency']),
                                            int(data['retention']))
            messages.success(request, _('Schedule updated'))
            return True
        except:
            redirect = reverse("horizon:project:veta:schedules",
                kwargs={"instance_id" : data['instance_id']})
            exceptions.handle(request,
                              _('Unable to update schedule.'),
                              redirect=redirect)


#/!/usr/bin/env python

#import os
#os.environ['HOME'] = '/Library/WebServer/mpl_home'
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
from matplotlib.figure import SubplotParams
#from matplotlib import pyplot as plt
from numpy import *
import matplotlib.dates as mdates
import StringIO
import Image
import urllib
try:
   import ephem3 as ephem
except:
   import ephem
from models import genMWO

colors = {'c':'blue','ab':'red'}

def plot_alt_map(objs, date=None, toff=0, new_window=False):
   '''Plots the altitude for a given night for the given objects (expected to
   be of type Objects).  Returns two strings:  the first is the binary
   PNG file that is the graph, the second is the <map> HTML that will be used
   to make the points in the graph "hot spots"'''
   if date is None:
      date = ephem.now()
   toff = toff/24.
   sun = ephem.Sun()
   MWO = genMWO(date=date)
   sun.compute(MWO)

   # Figure out the start and stop time for the night.
   sunset = MWO.next_setting(sun)    # In DJD
   sunrise = MWO.next_rising(sun)
   if sunset > sunrise:
      sunset = MWO.previous_setting(sun)
   #MWO.date = sunset

   # Setup the graph
   fig = Figure(subplotpars=SubplotParams(left=0.07, right=0.99))
   canvas = FigureCanvasAgg(fig)
   ax = fig.add_subplot(111)
   ax.xaxis.set_major_locator(mdates.HourLocator(interval=2))
   ax.xaxis.set_minor_locator(mdates.MinuteLocator(byminute=[0,60]))
   ax.set_xlabel('UTC time')
   ax.set_ylabel('Altitude')
   ax.grid(True, which='both', linestyle='-', color='gray')
   lines = []
   names = []
   ids = []

   sunset = sunset - 60*ephem.minute
   sunrise = sunrise + 60*ephem.minute

   for obj in objs:
      eobj = obj.genobj()
      t0 = obj.rise_time()
      if t0 is None or t0 < sunset: t0 = sunset
      if t0 > sunrise: continue
      t1 = obj.set_time()
      if t1 is None or t1 > sunrise: t1 = sunrise
      if t1 < sunset:
         continue

      tt = date
      if tt < t0:  tt = t0
      if tt > t1:  tt = t1
      tt = tt*1 + 693595.5
      saved_epoch = obj.epoch
      obj.epoch = date
      aa = obj.altitude()
      ts = arange(t0,t1+ephem.minute,10*ephem.minute)
      alts = []
      for t in ts:
         #obj.epoch = t
         #alts.append(obj.altitude())
         MWO.date = t
         eobj.compute(MWO)
         alts.append(eobj.alt*180.0/pi)
      alts = array(alts)
      mid = argmax(alts)
      merid = ephem.Date(ts[mid]+toff)
      maxalt = alts[mid]
      ts = ts + 693595.5   # convert to matplotlib epochs
      title = "Meridian @ %s (%.1fd)" % (str(merid).split()[1], maxalt)
      ax.text(0.5, 1.1, title, transform=ax.transAxes, ha='center',
            va='top', fontsize=18)
      ax.plot_date(ts+toff, alts, '-')
      pobj = ax.plot_date([tt+toff],[aa], 'o', mfc='k')
      lines.append(pobj[0])
      names.append(obj.name)
      ids.append(obj.pk)
      obj.epoch = saved_epoch

   ax.set_ylim(0, 90.)

   ax.set_xlim(sunset*1+693595.5+toff, sunrise*1+693595.5+toff)
   ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
   for tick in ax.xaxis.get_major_ticks():
      tick.label2On = True
   ax.axvline(date*1+693595.5+toff, color='red')
   ax.axvline(sunset+60*ephem.minute+693595.5+toff, linestyle='--',
         linewidth=2, color='red')
   ax.axvline(sunrise-60*ephem.minute+693595.5+toff, linestyle='--',
         linewidth=2, color='red')
   ax.fill_between([sunset*1+693595.5+toff,sunrise*1+1+693595.5+toff], 0, 30,
         color='0.7', zorder=0)

   # Now we save to a string and also convert to a PIL image, so we can get
   #  the size.
   output = StringIO.StringIO()
   canvas.print_figure(output)
   img_str = 'data:image/png,' + urllib.quote(output.getvalue())
   output.seek(0)
   img = Image.open(output)
   output.close()
   xsize,ysize = img.size

   # Get the window coordinates of the points
   bboxes = [o.get_window_extent(0).inverse_transformed(fig.transFigure) \
         for o in lines]
   coords = [(b.x0, 1-b.y1, b.x1, 1-b.y0) for b in bboxes]

   HTML = "<img src=\"%s\" style=\"width: 280px\" usemap=\"#map\" >" % img_str
   HTML += "<map name=\"map\">\n"
   for i in range(len(names)):
      HTML += "<area shape=rect coords=\"%d %d %d %d\" title=\"%s\" href=\"../object/%d/\"" \
            % (int(coords[i][0]*xsize),
               int(coords[i][1]*ysize),
               int(coords[i][2]*xsize),
               int(coords[i][3]*ysize),
               names[i], ids[i])
      if new_window:
         HTML += " target=\"object_window\">\n"
      else:
         HTML += ">\n"
   HTML += '''
   </map>
   </body>
   </html>'''

   return(HTML)


from xml.etree import ElementTree as ET

from opennsa import constants as cnt
from opennsa.shared import xmlhelper, modifiableresource
from opennsa.discovery.bindings import discovery

ET.register_namespace('nsi', discovery.NSI_DISCOVERY_NS)
ET.register_namespace('gns', discovery.GNS_NS)

class DiscoveryService:

    def __init__(self, nsa_id, version=None, name=None, software_version=None, start_time=None,
                 network_ids=None, interfaces=None, features=None, provider_registry=None,
                 link_vector=None):

        self.nsa_id                 = nsa_id                # string
        self.version                = version               # datetime
        self.name                   = name                  # string
        self.software_version       = software_version      # string
        self.start_time             = start_time            # datetime
        self.network_ids            = network_ids           # [ string ]
        self.interfaces             = interfaces            # [ (type, url, described_by) ]
        self.features               = features              # [ (type, value) ]
        self.provider_registry      = provider_registry     # provreg.ProviderRegistry
        self.link_vector            = link_vector           # linkvector.LinkVector

    def xml(self):

        # location not really supported yet
        interface_types = [ discovery.InterfaceType(i[0], i[1], i[2]) for i in self.interfaces ]
        feature_types   = [ discovery.FeatureType(f[0], f[1]) for f in self.features ]

        peers_with = self.provider_registry.providers.keys()
        peers_with.remove(self.nsa_id)

        topology_vectors = [ (cnt.URN_OGF_PREFIX + tv, cost) for tv, cost in self.link_vector.listVectors().items() ]
        other = discovery.HolderType( [ discovery.Topology(t,c) for (t,c) in topology_vectors ] )

        nsa_element = discovery.NsaType(
            self.nsa_id,
            xmlhelper.createXMLTime(self.version),
            None,
            self.name,
            self.software_version,
            xmlhelper.createXMLTime(self.start_time),
            self.network_ids,
            interface_types,
            feature_types,
            peers_with,
            other,
           )

        e = nsa_element.xml(discovery.nsa)
        payload = ET.tostring(e, 'utf-8')
        return payload

    def resource(self):

        r = modifiableresource.ModifiableResource('DiscoveryService', 'application/xml')
        r.updateResource(self.xml())
        return r


from machine import ADC

class SoilMoistureSensor:
    def __init__(self, pin):
        self._pin = ADC(pin)
        self.MAX = 20000
        self.MIN = 65535
        self.READ_COUNTER = 50

    def read(self):
        raw = 0.0
        for i in range(self.READ_COUNTER):
            raw += self._pin.read_u16()
            delay(1)
        raw_average = raw/self.READ_COUNTER
        return raw_average

    def read_percentage(self):
        old_value = self.read()
        old_range = (self.MAX - self.MIN)
        new_range = (100 - 0)
        new_value = (((old_value - self.MIN) * new_range) / old_range) + 0
        if new_value > 100:
            new_value = 100
        return new_value


# USAGE
# python object_tracker.py --prototxt deploy.prototxt --model res10_300x300_ssd_iter_140000.caffemodel

# import the necessary packages
from pyimagesearch.centroidtracker import CentroidTracker
from imutils.video import VideoStream
import numpy as np
import argparse
import imutils
import time
import cv2
from matplotlib import pyplot as plt
import io
import pandas as pd

# construct the argument parse and parse the arguments
# ap = argparse.ArgumentParser()
# ap.add_argument("-p", "--prototxt", required=True,
# 	help="path to Caffe 'deploy' prototxt file")
# ap.add_argument("-m", "--model", required=True,
# 	help="path to Caffe pre-trained model")
# ap.add_argument("-c", "--confidence", type=float, default=0.5,
# 	help="minimum probability to filter weak detections")
# args = vars(ap.parse_args())

# face recognition coefficients
prototxt = "deploy.prototxt"
model = "res10_300x300_ssd_iter_140000.caffemodel"
confidence = 0.5

# file name that you are saving the data to
table_name = "hrv_your_name.xlsx"

# heartbeat setup
heartbeat_count = 128
heartbeat_values = [0]*heartbeat_count
heartbeat_times = [time.time()]*heartbeat_count

# Matplotlib graph surface
fig = plt.figure()
ax = fig.add_subplot(111)
heart = []

# initialize our centroid tracker and frame dimensions
ct = CentroidTracker()
(H, W) = (None, None)

# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(prototxt, model)

# initialize the video stream and allow the camera sensor to warmup
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)

# loop over the frames from the video stream
while True:
	# read the next frame from the video stream and resize it
	frame = vs.read()
	frame = imutils.resize(frame, width=400)

	# if the frame dimensions are None, grab them
	if W is None or H is None:
		(H, W) = frame.shape[:2]

	# construct a blob from the frame, pass it through the network,
	# obtain our output predictions, and initialize the list of
	# bounding box rectangles
	blob = cv2.dnn.blobFromImage(frame, 1.0, (W, H),
		(104.0, 177.0, 123.0))
	net.setInput(blob)
	detections = net.forward()
	rects = []

	# loop over the detections
	for i in range(0, detections.shape[2]):
		# filter out weak detections by ensuring the predicted
		# probability is greater than a minimum threshold
		if detections[0, 0, i, 2] > confidence:
			# compute the (x, y)-coordinates of the bounding box for
			# the object, then update the bounding box rectangles list
			box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
			rects.append(box.astype("int"))

			# draw a bounding box surrounding the object so we can
			# visualize it
			(startX, startY, endX, endY) = box.astype("int")
			# cv2.rectangle(frame, (startX, startY), (endX, endY),
			# 	(0, 255, 0), 2)

			# get heartbeat reading area - left eye
			# TODO: you can adjust it based on your face
			startXhrv = int(startX + (endX - startX)/3)
			endXhrv = int(endX - (endX - startX)/8)
			startYhrv = int(startY + (endY - startY)/4)
			endYhrv = int(endY - (endY - startY)/2)
			cv2.rectangle(frame, (startXhrv, startYhrv), (endXhrv, endYhrv),
				(0, 255, 0), 2)

			#Prepare for heartbeat update
			img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
			crop_img = img[startYhrv:endYhrv, startXhrv:endXhrv]

			# Update heartbeat data
			heartbeat_values = heartbeat_values[1:] + [np.average(crop_img)]
			heartbeat_times = heartbeat_times[1:] + [time.time()]
			heart.append(heartbeat_values)

    		# Draw matplotlib graph to numpy array
			ax.plot(heartbeat_times, heartbeat_values)
			fig.canvas.draw()
			plot_img_np = np.fromstring(fig.canvas.tostring_rgb(),
				dtype=np.uint8, sep='')
			ncols, nrows = fig.canvas.get_width_height()
			plot_img_np = plot_img_np.reshape(nrows*2, ncols*2, 3)
			plt.cla()

			cv2.imshow('Graph', plot_img_np)

	# update our centroid tracker using the computed set of bounding
	# box rectangles
	objects = ct.update(rects)

	# loop over the tracked objects
	# for (objectID, centroid) in objects.items():
	# 	# draw both the ID of the object and the centroid of the
	# 	# object on the output frame
	# 	text = "ID {}".format(objectID)
	# 	cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
	# 		cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
	# 	cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)

	# stop the program if we are having another face
	# since we are only reading one person
	if len(objects) > 1:
		heart_df = pd.DataFrame(heart)
		heart_df.to_excel(table_name)
		break

	# show the output frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF

	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		heart_df = pd.DataFrame(heart)
		heart_df.to_excel(table_name)
		break

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()


import requests
import json

# API URL
base_url = "https://reqres.in/api/users/"

# Read Input From Json File
file = open('/home/srinii/PycharmProjects/Excersise/Users.json')
json_input = file.read()
json_request = json.loads(json_input)
#print(json_request)

# Create POST
response = requests.post(base_url, json_request)
print(response.content)


import inspect

import math
import time
import warnings

import django
from django import template
from django.core.cache import cache
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_text
from django.utils.html import escape
from django.utils.translation import ugettext as _, ungettext
from django.utils import dateformat
from django.utils.timezone import timedelta
from django.utils.timezone import now as tznow

from pybb.models import TopicReadTracker, ForumReadTracker, PollAnswerUser, Topic, Post
from pybb.permissions import perms
from pybb import defaults, util, compat

register = template.Library()
if django.VERSION >= (1, 9):
    register.assignment_tag = register.simple_tag

#noinspection PyUnusedLocal
@register.tag
def pybb_time(parser, token):
    try:
        tag, context_time = token.split_contents()
    except ValueError: # pragma: no cover
        raise template.TemplateSyntaxError('pybb_time requires single argument')
    else:
        return PybbTimeNode(context_time)

@register.assignment_tag(takes_context=True)
def pybb_get_time(context, context_time):
    return pybb_user_time(context_time, context['user'])

class PybbTimeNode(template.Node):
    def __init__(self, time):
    #noinspection PyRedeclaration
        self.time = template.Variable(time)

    def render(self, context):
        context_time = self.time.resolve(context)
        return pybb_user_time(context_time, context['user'])

def pybb_user_time(context_time, user):
    delta = tznow() - context_time
    today = tznow().replace(hour=0, minute=0, second=0)
    yesterday = today - timedelta(days=1)
    tomorrow = today + timedelta(days=1)

    if delta.days == 0:
        if delta.seconds < 60:
            msg = ungettext('%d second ago', '%d seconds ago', delta.seconds)
            return msg % delta.seconds
        elif delta.seconds < 3600:
            minutes = int(delta.seconds / 60)
            msg = ungettext('%d minute ago', '%d minutes ago', minutes)
            return msg % minutes
    if user.is_authenticated:
        if time.daylight: # pragma: no cover
            tz1 = time.altzone
        else: # pragma: no cover
            tz1 = time.timezone
        tz = tz1 + util.get_pybb_profile(user).time_zone * 60 * 60
        context_time = context_time + timedelta(seconds=tz)
    if today < context_time < tomorrow:
        return _('today, %s') % context_time.strftime('%H:%M')
    elif yesterday < context_time < today:
        return _('yesterday, %s') % context_time.strftime('%H:%M')
    else:
        return dateformat.format(context_time, 'd M, Y H:i')

@register.simple_tag
def pybb_link(object, anchor=''):
    """
    Return A tag with link to object.
    """

    url = hasattr(object, 'get_absolute_url') and object.get_absolute_url() or None
    #noinspection PyRedeclaration
    anchor = anchor or smart_text(object)
    return mark_safe('%s' % (url, escape(anchor)))

@register.filter
def pybb_topic_moderated_by(topic, user):  # pragma: no cover
    """
    Check if user is moderator of topic's forum.
    """
    warnings.warn("pybb_topic_moderated_by filter is deprecated and will be removed in later releases. "
                  "Use pybb_may_moderate_topic(user, topic) filter instead",
                  DeprecationWarning)
    return perms.may_moderate_topic(user, topic)

@register.filter
def pybb_editable_by(post, user):  # pragma: no cover
    """
    Check if the post could be edited by the user.
    """
    warnings.warn("pybb_editable_by filter is deprecated and will be removed in later releases. "
                  "Use pybb_may_edit_post(user, post) filter instead",
                  DeprecationWarning)
    return perms.may_edit_post(user, post)

@register.filter
def pybb_posted_by(post, user):
    """
    Check if the post is writed by the user.
    """
    return post.user == user

@register.filter
def pybb_is_topic_unread(topic, user):
    if not user.is_authenticated:
        return False

    last_topic_update = topic.updated or topic.created

    unread = not ForumReadTracker.objects.filter(
        forum=topic.forum,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    unread &= not TopicReadTracker.objects.filter(
        topic=topic,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    return unread

@register.filter
def pybb_topic_unread(topics, user):
    """
    Mark all topics in queryset/list with .unread for target user
    """
    topic_list = list(topics)

    if user.is_authenticated:
        for topic in topic_list:
            topic.unread = True

        forums_ids = [f.forum_id for f in topic_list]
        forum_marks = dict([(m.forum_id, m.time_stamp)
                            for m
                            in ForumReadTracker.objects.filter(user=user, forum__in=forums_ids)])
        if len(forum_marks):
            for topic in topic_list:
                topic_updated = topic.updated or topic.created
                if topic.forum.id in forum_marks and topic_updated <= forum_marks[topic.forum.id]:
                    topic.unread = False

        qs = TopicReadTracker.objects.filter(user=user, topic__in=topic_list).select_related('topic')
        topic_marks = list(qs)
        topic_dict = dict(((topic.id, topic) for topic in topic_list))
        for mark in topic_marks:
            if topic_dict[mark.topic.id].updated <= mark.time_stamp:
                topic_dict[mark.topic.id].unread = False
    return topic_list

@register.filter
def pybb_forum_unread(forums, user):
    """
    Check if forum has unread messages.
    """
    forum_list = list(forums)
    if user.is_authenticated:
        for forum in forum_list:
            forum.unread = forum.topic_count > 0
        forum_marks = ForumReadTracker.objects.filter(
            user=user,
            forum__in=forum_list
        ).select_related('forum')
        forum_dict = dict(((forum.id, forum) for forum in forum_list))
        for mark in forum_marks:
            curr_forum = forum_dict[mark.forum.id]
            if (curr_forum.updated is None) or (curr_forum.updated <= mark.time_stamp):
                if not any((f.unread for f in pybb_forum_unread(curr_forum.child_forums.all(), user))):
                    forum_dict[mark.forum.id].unread = False
    return forum_list

@register.filter
def pybb_topic_inline_pagination(topic):
    page_count = int(math.ceil(topic.post_count / float(defaults.PYBB_TOPIC_PAGE_SIZE)))
    if page_count <= 5:
        return range(1, page_count+1)
    return list(range(1, 5)) + ['...', page_count]

@register.filter
def pybb_topic_poll_not_voted(topic, user):
    if user.is_anonymous:
        return True
    return not PollAnswerUser.objects.filter(poll_answer__topic=topic, user=user).exists()

@register.filter
def endswith(str, substr):
    return str.endswith(substr)

@register.assignment_tag
def pybb_get_profile(*args, **kwargs):
    try:
        return util.get_pybb_profile(kwargs.get('user') or args[0])
    except:
        return None

@register.assignment_tag(takes_context=True)
def pybb_get_latest_topics(context, cnt=5, user=None):
    qs = Topic.objects.all().order_by('-updated', '-created', '-id')
    if not user:
        user = context['user']
    qs = perms.filter_topics(user, qs)
    return qs[:cnt]

@register.assignment_tag(takes_context=True)
def pybb_get_latest_posts(context, cnt=5, user=None):
    qs = Post.objects.all().order_by('-created', '-id')
    if not user:
        user = context['user']
    qs = perms.filter_posts(user, qs)
    return qs[:cnt]

def load_perms_filters():
    def partial(func_name, perms_obj):
        def newfunc(user, obj_or_qs):
            return getattr(perms_obj, func_name)(user, obj_or_qs)
        return newfunc

    def partial_no_param(func_name, perms_obj):
        def newfunc(user):
            return getattr(perms_obj, func_name)(user)
        return newfunc

    for method_name, method in inspect.getmembers(perms):
        if not inspect.ismethod(method):
            continue  # pragma: no cover - only methods are used to dynamically build templatetags
        if not method_name.startswith('may') and not method_name.startswith('filter'):
            continue  # pragma: no cover - only (may|filter)* methods are used to dynamically build templatetags
        method_args = inspect.getargspec(method).args
        args_count = len(method_args)
        if args_count not in (2, 3):
            continue  # pragma: no cover - only methods with 2 or 3 params
        if method_args[0] != 'self' or method_args[1] != 'user':
            continue  # pragma: no cover - only methods with self and user as first args
        if len(inspect.getargspec(method).args) == 3:
            register.filter('%s%s' % ('pybb_', method_name), partial(method_name, perms))
        elif len(inspect.getargspec(method).args) == 2:
            register.filter('%s%s' % ('pybb_', method_name), partial_no_param(method_name, perms))
load_perms_filters()

@register.filter
def check_app_installed(app_name):
    return compat.is_installed(app_name)

@register.filter
def pybbm_calc_topic_views(topic):
    cache_key = util.build_cache_key('anonymous_topic_views', topic_id=topic.id)
    return topic.views + cache.get(cache_key, 0)


"""
Palindrome dates
http://www.rosettacode.org/wiki/Palindrome_dates
"""

import datetime

def is_valid(strdate: str):
    """Check if the given string date is valid"""
    try:
        _ = datetime.datetime.strptime(strdate, "%Y%m%d")
    except ValueError:
        return False
    else:
        return True

def get_next_palindrome_date():
    """Generate palidrome dates after 2020"""
    year = 2021
    while True:
        syr = str(year)[::-1]  # string year reversed
        chk_date = f"{year}{syr}"
        if is_valid(chk_date):
            yield f"{year}-{syr[:2]}-{syr[2:]}"
        year += 1

def main():
    palindrome_date = get_next_palindrome_date()
    for _ in range(15):
        print(next(palindrome_date))

if __name__ == "__main__":
    main()


"""HTTP SERVER"""
from sys import getsizeof
from http.server import HTTPServer, BaseHTTPRequestHandler, ThreadingHTTPServer
from stat_and_enti2 import *

class RequestHeandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)

    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.data_string = ''
    def _html(self, message):
        """This just generates an HTML document that includes `message`
        in the body. Override, or re-write this do do more interesting stuff.
        """
        content = f"
{message}
"
        return content.encode("utf8")  # NOTE: must return a bytes object!

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        tmp = []
        content_length = int(self.headers['Content-Length'])
        self.data_string = self.rfile.read(content_length)
        tmp = read(tmp, self.data_string)
        self._set_headers()
        tmp = handler(tmp)
        string = ''
        for res in tmp:
            string += res
        self.wfile.write((string.encode("ISO8859-1")))

def read(buf, string):
    string = string.decode("ISO8859-1")
    buf.append(string)
    return buf

def handler(buf):
    tmp = ''.join(buf)
    str1 = buf[len(buf)-1]
    if str1[len(str1)-len('all_end')-1:len(str1)-1] == 'all_end':
        buf[len(buf)-1] = buf[len(buf)-1][0:len(str1)-len(' all_end ')-1]
        i = tmp.find('endtweet')
        buf.clear()
        while i!=-1:
            buf.append(tmp[0:i])
            tmp = tmp[i+len('endtweet'):len(tmp)]
            i = tmp.find('endtweet')
    cmd = buf.pop(0)
    lst = []
    for i in buf:
        j = eval(i)
        lst.append(j)
    for i in lst:
        buf.append(' '.join(i)+'\n')
    if cmd == 'ENTI':
        res = enti_fun(buf)
    elif cmd == 'STAT':
        res = stat_fun(lst)
    return res

def run(server_class=ThreadingHTTPServer, handler_class=RequestHeandler, addr="localhost", port=8000):
    try:
        server_address = (addr, port)
        httpd = server_class(server_address, handler_class)
        print('Press ctrl-C to stop')
        print(f"Starting httpd server on {addr}:{port}")
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
        print('\nStop server.')
run()


import camelot
import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_row', None)
pd.set_option('display.width', None)

def table_trim(path):
    tables = camelot.read_pdf(path, pages="all", kind= "line")
    keys, result = [], []
    print(tables)
    # # 테이블 수 만큼 반복
    # for table in tables:
    #     title_idx = []
    #     frame = table.df
    #     print(frame)
    # return result

def extract(frame):
    result = {}
    for f in frame:
        if f.iloc[0][0] == '표제부':
            val = f.iloc[2][2].replace('\n', ' ')
            if '[도로명주소]' in val:
                result['소재지'] = val.split(' [도로명주소] ')[0]
                result['도로명주소'] = val.split(' [도로명주소] ')[1]

            if f.iloc[1][2] == '건 물 번 호':
                result['소재지'] = "%s %s" % (result['소재지'], f.iloc[2][2])
                result['도로명주소'] = "%s %s" % (result['도로명주소'], f.iloc[2][2])

            if f.iloc[1][4] == '권리자 및 기타사항':
                owners = f.iloc[2][4]
                if '지분' in owners:
                    owners = owners.split('\n')
                    extract_owners, name, share = [], '', ''

                    for o in owners:
                        if '지분' in o:
                            share = o.split('지분 ')[1]
                        elif '*' in o:
                            name = '%s/%s' % (o.split('  ')[0], o.split('  ')[1].split('-')[0])
                        if name and share:
                            extract_owners.append("%s/%s" % (name, share))
                            name, share = '', ''

                    result['소유자'] = extract_owners
                else:
                    result['소유자'] = owners.split('소유자  ')[1].split('-')[0].replace('  ', '/')

        if f.iloc[0][0] == '대지권의목적인토지의표시':
            for i, s in enumerate(f.iloc[1]):
                if s == '대지권종류': result['대지권종류'] = f.iloc[2][i]
                elif s == '대지권비율': result['대지권비율'] = f.iloc[2][i]

    print(result['소유자'])

file_name = 'bd_test.pdf'
table_trim(file_name)


#!/usr/bin/python3

import sys
import re

lines = []

for line in sys.stdin:
    if not re.search('#',line):
        lines.append(line.strip().split(','))

nrows = (len(lines)+1)//2

# The name-generating hack below doesn't work well in all cases,
# so supply some explicit replacements.
replacements = { 'unity:DetectorChannel': 'channel',
                 'qudt:DegreeAngle': 'degree (angle)',
                 'unity:DistributionBin': 'bin',
                 'qudt:Gram': 'gramme',
                 'unity:MilliArcSecond': 'milliarcsecond',
                 'qudt:MinuteTime': 'minute (time)',
                 'qudt:SecondTime': 'second (time)',
                 'unity:SolarLuminosity': 'luminosity',
                 'unity:StellarMagnitude': 'magnitudes',
                 'qudt:UnifiedAtomicMassUnit': 'AMU',
                 }

all_uppercase = re.compile('^[A-Z]+$')
initial_capital = re.compile('[A-Z][^A-Z]*')

def fmtname(uname):
    if uname in replacements:
        rval = replacements[uname]
    else:
        nameparts = uname.split(':')
        if len(nameparts) != 2:
            print("name {} malformed".format(uname), file=sys.stderr)
            rval ='XXX'
        else:
            tname = nameparts[1]
            if all_uppercase.match(tname):
                rval = tname
            elif initial_capital.match(tname):
                rval = " ".join(s.lower()
                	        for s in initial_capital.findall(tname))
            else:
                rval = tname
    return [rval]

def fmtrow(r):
    s = "&".join([r[0]] + fmtname(r[1]) + (["$\\cdot$" if s=="1" else s[1:] for s in r[2:]]))
    return s.replace("%", "\\%") # one of the units is '%' (ie, the TeX comment character)

for r in range(nrows):
    r2 = r+nrows
    if r2 >= len(lines):
        print("{}\\\\".format(fmtrow(lines[r])))
    else:
        print("{}\n\t& {}\\\\".format(fmtrow(lines[r]), fmtrow(lines[r2])))


# encoding: utf-8

# Package Selector example
from yast import import_module
import_module('UI')
import_module('Pkg')
from yast import *
class PackageSelectorMultiSrcClient:
    def main(self):
      Pkg.SourceCreate("file:/srv/sles-10-i386/CD1/", "")
      Pkg.SourceCreate("file:/srv/10.1-i386/CD1/", "")
      # Pkg::SourceCreate( "http://ftp.uni-erlangen.de/pub/mirrors/packman/suse/10.0/", "" );
      # Pkg::SourceCreate( "ftp://ftp.gwdg.de/pub/linux/misc/packman/suse/10.0/", "" );
      Pkg.TargetInit("/", False) # installed system

      UI.OpenDialog(
        Opt("defaultsize"),
        PackageSelector(
          Id("selector"),
          Opt("repoMode"),
          # `opt(`testMode),
          "/dev/fd0"
        )
      )
      input = UI.RunPkgSelection(Id("selector"))
      UI.CloseDialog()

      ycpbuiltins.y2milestone("Input: %1", input)

PackageSelectorMultiSrcClient().main()


from tempfile import mkdtemp
from excel_sheet_integrator import LocalExcelSheetIntegrator

from flask import (
    Flask,
    flash,
    redirect,
    render_template,
    request,
    safe_join,
    send_file,
)
from werkzeug.exceptions import NotFound, BadRequest
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = mkdtemp()

NO_FILE_MSG = "Missing file in request"
NO_FILE_SELECTED_MSG = "No file selected for uploading"
SUCCESSFUL_UPLOAD = "File successfully uploaded"

app = Flask(__name__)
app.secret_key = "setec astronomy"
app.config["SESSION_TYPE"] = "filesystem"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

@app.route("/")
def index():
    return render_template("upload.html")

@app.route("/upload", methods=["POST"])
def upload_file_locally():
    if request.method == "POST":
        file_path = handle_local_file(request.files["file"])
        master_file = request.form["master_sheet"]

        excel_sheet_integrator = LocalExcelSheetIntegrator(file_path)
        excel_sheet_integrator.create_new_excel_sheet(master_file)

        return redirect("/download/{0}".format(file_path))
    return redirect('/')

@app.route("/download/<path:file_path>", methods=["GET"])
def download_file(file_path):
    try:
        return send_file(file_path)
    except (NotFound, BadRequest):
        return redirect("/")

def handle_local_file(file):
    file_name = get_file_name(file)

    file_path = safe_join(app.config["UPLOAD_FOLDER"], file_name)
    file.save(file_path)
    flash(SUCCESSFUL_UPLOAD)
    return file_path

def get_file_name(file):
    return secure_filename(file.filename)

if __name__ == "__main__":
    app.run(debug=False, port=8080)


"""
client.py module scrapes sport results from the site https://www.fonbet.ru/results/
The results are stored in Redis.
"""
import asyncio
import aiohttp
import datetime
import redis

now = round(datetime.datetime.now().timestamp())
req = {
    'url': 'https://clientsapi31.bkfon-resource.ru/results/results.json.php',
    'params': {
        'locale': 'en',
        'lastUpdate': 0,
        '_': now,
    }
}
redis_events = redis.Redis(host='localhost', port=6379, db=1)
redis_sections = redis.Redis(host='localhost', port=6379, db=2)

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.post(req['url'], params=req['params']) as response:
            results = await response.json()
            # store events to redis
            for event in results['events']:
                event_id = event['id']
                del event['id']
                redis_events.hmset(event_id, event)
            # store sections to redis
            for section in results['sections']:
                section_name = section['name']
                redis_sections.delete(section_name)
                redis_sections.rpush(section_name, *section['events'])

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


from baseProgram import compute, COVERAGE_MAX, APPROVAL_MAX, compute_pav
from baseProgram import COMPUTE_PJR, COMPUTE_EJR, computeEJRorPJR
from gmpy2 import mpq
import sys
import tools

class JRCommittee(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.minJRCov, stats.maxJRCov, stats.minJRApp, stats.maxJRApp)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
      toOut='.'
#      print(lc, uc, la, ua )
      if compute(candidates, voters, la, ua, lc, uc, committeeSize)[0]:
        toOut=existenceSymbol
      mesh.setValueOfCell(cell, toOut)

class PJRCommittee(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.minJRCov, stats.maxJRCov, stats.minJRApp, stats.maxJRApp)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
      toOut='.'
      if computeEJRorPJR(candidates, voters, la, ua, lc, uc, committeeSize, COMPUTE_PJR)[0]:
        toOut=existenceSymbol
      mesh.setValueOfCell(cell, toOut)

class AnyCommittee(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.minCov, stats.maxCov, stats.minApp, stats.maxApp)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
      toOut='.'
#      print(lc, uc, la, ua )
      if compute(candidates, voters, la, ua, lc, uc, committeeSize, goal =
          APPROVAL_MAX, requireJR = False)[0]:
        toOut=existenceSymbol
      mesh.setValueOfCell(cell, toOut)

class MaxApprovalCommittee(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.minCov, stats.maxCov, stats.maxApp, stats.maxApp)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
      toOut='.'
#      print(lc, uc, la, ua )
      if compute(candidates, voters, la, ua, lc, uc, committeeSize, goal =
          COVERAGE_MAX, requireJR = False)[0]:
        toOut=existenceSymbol
      mesh.setValueOfCell(cell, toOut)

class ChambelinCourantCommittee(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.maxCov, stats.maxCov, stats.minApp, stats.maxApp)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
      toOut='.'
#      print(lc, uc, la, ua )
      if compute(candidates, voters, la, ua, lc, uc, committeeSize, requireJR = False)[0]:
        toOut=existenceSymbol
      mesh.setValueOfCell(cell, toOut)

class PAV(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    mesh.clipMeshByValues(stats.minJRCov, stats.maxJRCov, stats.minJRApp, stats.maxJRApp)

    maxSatisfaction = SinglePAV().compute(candidates, voters, mesh, stats, existenceSymbol)

    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
#      print(lc, uc, la, ua )
      if compute_pav(candidates, voters, la, ua, lc, uc, committeeSize,
          satisfactionLevel=maxSatisfaction)[0]:
        mesh.setValueOfCell(cell, existenceSymbol)

class SinglePAV(object):
  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committeeSize = mesh.committeeSize
    success, satisfaction, _, coverage, approval = compute_pav(candidates, voters,
        stats.minJRApp, stats.maxJRApp, stats.minJRCov, stats.maxJRCov,
        committeeSize)
    if success:
      mesh.setValueOfCell(mesh.getCellFromValues(coverage, approval), existenceSymbol)
    return satisfaction

class SequentialPhragmen(object):

  def compute(self, candidates, voters, mesh, stats, existenceSymbol):
    committees = self.computeAllCommittees(candidates, voters, mesh.committeeSize)
    committeesWithAppAndCoverage = []
    for committee in committees:
      approvals, coverage = tools.committeApprovalAndCoverage(candidates, voters, committee)
      committeesWithAppAndCoverage.append((committee, approvals, coverage))
    self.depictMesh(committeesWithAppAndCoverage, existenceSymbol, mesh)

  def depictMesh(self, committees, existenceSymbol, mesh):
    for cell in mesh.getUnclippedCells():
      lc, uc, la, ua = cell
 #     print(lc, uc, la, ua )
      for _, coverage, approvalScore in committees:
        if coverage >= lc and coverage <= uc and approvalScore >= la and approvalScore <= ua:
          mesh.setValueOfCell(cell, existenceSymbol)
          break

  def computeAllCommittees(self, candidates, preferences, committeeSize):

    def __enough_approved_candiates():
      appr = set()
      for pref in preferences.values():
        appr.update(set(pref))
      if len(appr) < committeeSize:
        print("committeesize is larger than number of approved candidates")
        exit()

    __enough_approved_candiates()

    load = {vnr:0 for vnr in preferences.keys()}
    com_loads = {():load}

    approvers_weight = {}
    for c in candidates:
        approvers_weight[c] = sum(1 for v in preferences.values() if c in v)

#
    for _ in range(0, committeeSize):  # size of partial committees currently under consideration
        com_loads_next = {}
        for committee, load in iter(com_loads.items()):
            approvers_load = {}
            for c in candidates:
                approvers_load[c] = sum(load[vnr] for vnr, v in preferences.items() if c in v)
            new_maxload = [mpq(approvers_load[c] + 1, approvers_weight[c])
                            if approvers_weight[c] > 0 else len(candidates)*len(preferences)
                            for c in candidates]
            for c in candidates:
                if c in committee:
                    new_maxload[c] = sys.maxsize
            for c in candidates:
                if new_maxload[c] <= min(new_maxload):
                    new_load = {}
                    for vnr, v in preferences.items():
                        if c in v:
                            new_load[vnr] = new_maxload[c]
                        else:
                            new_load[vnr] = load[vnr]
                    com_loads_next[tuple(sorted(committee + (c,)))] = new_load
        # remove suboptimal committees, leave only the best branching_factor many (subject to ties)
        com_loads = {}
        cutoff = min([max(load) for load in com_loads_next.values()])
        for com, load in iter(com_loads_next.items()):
            if max(load) <= cutoff:
                com_loads[com] = load
    return [set(comm) for comm in com_loads.keys()]


import json
import random
import string

import aiohttp
import time

from app import app
from slim.retcode import RETCODE
from slim.support.peewee import PeeweeView
from aioauth_client import GithubClient
import peewee
from slim.utils import to_hex, to_bin

import config
from model import db
from model._post import POST_STATE
from model.user_model import UserModel
from model.user_oauth import UserOAuth
from api.user import UserViewMixin

@app.route.view('user/oauth')
class UserOAuthView(UserViewMixin, PeeweeView):
    model = UserOAuth

    github = GithubClient(
        client_id='config.CLIENT_ID',
        client_secret='config.CLIENT_SECRET'
    )

    @app.route.interface('GET')
    async def get_oauth_url(self):
        authorize_url = self.github.get_authorize_url(scope="user:email")
        self.finish(RETCODE.SUCCESS, {'state': 0, 'url': authorize_url})

    @app.route.interface('GET')
    async def get_user_data(self):
        code = self.params
        print(code)
        code = code['code']
        if code == 'undefined':
            self.finish(RETCODE.FAILED)
            return
        otoken, _ = await self.github.get_access_token(code)
        github = GithubClient(
            client_id=config.CLIENT_ID,
            client_secret=config.CLIENT_SECRET,
            access_token=otoken,
        )
        response = await github.request('GET', 'user')
        # response = json.loads(response)
        if response['id']:
            try:
                account = UserOAuth.get(UserOAuth.login_id == response['id'], UserOAuth.platform == 'github')
            except UserOAuth.DoesNotExist:
                account = None

            if account:
                if account.user_id:  # 返回用户已有信息
                    u = UserModel.get_by_pk(account.user_id)
                    if u:
                        expires = 30
                        u.refresh_key()
                        self.setup_user_key(u.key, expires)
                        self.finish(RETCODE.SUCCESS, {'oauthcode': 0, 'user_id': account.user_id,
                                                      'state': account.state, 'access_token': u.key})
                else:
                    self.finish(RETCODE.SUCCESS, {'oauthcode': 1, 'state': account.state, 'oauth_id': account.id,
                                                  'login_id': account.login_id, 'platform': account.platform})
            else:
                ins = [{'login_id': response['id'], 'time': time.time(), 'platform': 'github',
                        'state': POST_STATE.APPLY}]
                if not isinstance(config.LONG_ID_GENERATOR, config.SQLSerialGenerator):
                    ins[0]['id'] = config.LONG_ID_GENERATOR().to_bin()

                UserOAuth.insert_many(ins).execute()
                self.finish(RETCODE.SUCCESS, {'oauthcode': 1, 'oauth_id': ins[0]['id'], 'state': ins[0]['state'],
                                              'login_id': ins[0]['login_id'], 'platform': ins[0]['platform']})
        else:
            self.finish(RETCODE.NOT_FOUND)

    @app.route.interface('POST')
    async def update(self):
        post = await self.post_data()
        print('提交的更新内容', post)

        try:
            account = UserOAuth.get(UserOAuth.login_id == post['loginId'], UserOAuth.platform == post['platform'])
        except UserOAuth.DoesNotExist:
            account = None
        except KeyError:
            account = None
            print('keyerror')

        if account:
            if post['state'] == str(POST_STATE.APPLY):
                # 该post['id']是user表中的id
                post_user_id = to_bin(post['id'])
                UserOAuth.update(user_id=post_user_id, state=POST_STATE.NORMAL).where(
                                                        UserOAuth.login_id == post['loginId']).execute()
                self.finish(RETCODE.SUCCESS)
            else:
                print('非法参数')
                self.finish(RETCODE.FAILED)
        else:
            self.finish(RETCODE.FAILED)
            print('failed')

"""
通过 access_token 拿到的数据字段
{
    'login': 'ly-nina',
    'id': 17906006,
    'avatar_url': 'https://avatars1.githubusercontent.com/u/17906006?v=4',
    'gravatar_id': '',
    'url': 'https://api.github.com/users/ly-nina',
    'html_url': 'https://github.com/ly-nina',
    'followers_url': 'https://api.github.com/users/ly-nina/followers',
    'following_url': 'https://api.github.com/users/ly-nina/following{/other_user}',
    'gists_url': 'https://api.github.com/users/ly-nina/gists{/gist_id}',
    'starred_url': 'https://api.github.com/users/ly-nina/starred{/owner}{/repo}',
    'subscriptions_url': 'https://api.github.com/users/ly-nina/subscriptions',
    'organizations_url': 'https://api.github.com/users/ly-nina/orgs',
    'repos_url': 'https://api.github.com/users/ly-nina/repos', 'events_url': https://api.github.com/users/ly-nina/events{/privacy}',
    'received_events_url': 'https://api.github.com/users/ly-nina/received_events',
    'type': 'User',
    'site_admin': False,
    'name': None,
    'company': None,
    'blog': '',
    'location': None,
    'email': None,
    'hireable': None,
    'bio': None,
    'public_repos': 11,
    'public_gists': 0,
    'followers': 0,
    'following': 0,
    'created_at': '2016-03-17T13:49:08Z',
    'updated_at': '2018-05-07T11:09:03Z'
}
"""


# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
list = []
count = 0
total = float(0)
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    line = line[20:]
    count = count + 1
    total = total + float(line)
    avg = total / count
print('Average spam confidence:', avg)


"""
Python'da kullanabileceğimiz 2 tane döngü tipinden biri for'dur.
Tekrarlayacak işlemlerimizde döngüleri kullanırız.
"for" döngüsü bir eleman her elemana sırayla ulaşmak için kullanılır.
"""

# öğrenci isimlerinden oluşan bir liste oluşturalım
ogrenciler = ["Eren", "Mustafa", "Zeynep"]

# Her öğrencinin adını ekrana yazdıralım
# ÖRNEK: Öğrencinin adı: Eren
for ogrenci in ogrenciler:
    print(f"Öğrencinin adı: {ogrenci}")

# İçinde ikili sayılardan oluşan tuple verilerinin olduğu bir liste oluşturalım
sayilar = [(1, 2), (3, 4), (5, 6)]
for a, b in sayilar:
    print(f"1.sayı: {a}, 2. sayı: {b}")

# Okulumuzun adının yer aldığı bir değişkeni kelimelere
# bölüp her kelimeyi döngü içinde ekrana yazdıralım.
okul = "Sancaktepe Teknoloji Anadolu İmam Hatip Lisesi"
for kelime in okul.split():
    print(kelime)

# öğrencilerin yer aldığı bir dict veri tipi oluşturalım
ogrenciler = {
    1: {
        "ad": "Eren",
        "soyad": "Özdal",
        "cinsiyet": True,
        "dersler": ["Türkçe", "Matematik", "Hayat Bilgisi"]
    },
    45: {
        "ad": "Zeynep",
        "soyad": "Özdal",
        "cinsiyet": False,
        "dersler": ["Görsel Sanatlar", "Matematik", "Fen Bilimleri"]
    }
}

# öğrencilerin numaralarını ve adlarını yazdıralım
for no, ogrenci in ogrenciler.items():
    print(f"{no} numaralı öğrenci: {ogrenci['ad']}")


import sqlalchemy as sa

from core.db import metadata, register_tables_creator

post = sa.Table(
    'posts',
    metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('content', sa.String(255)),
    sa.Column('author_id', sa.ForeignKey('authors.id')),
)

author = sa.Table(
    'authors',
    metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('name', sa.String(255), unique=True),
)

comment = sa.Table(
    'comments', metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('content', sa.String, nullable=False)
)

comments_posts = sa.Table(
    'comments_posts', metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('comment_id', sa.ForeignKey('comments.id'), primary_key=True),
    sa.Column('post_id', sa.ForeignKey('posts.id'), primary_key=True)
)

@register_tables_creator
async def create_authors(conn):
    await conn.execute('DROP TABLE IF EXISTS authors CASCADE')
    await conn.execute('''
        CREATE TABLE authors (
            id serial PRIMARY KEY,
            name varchar(255) UNIQUE
        )
    ''')

@register_tables_creator
async def create_posts(conn):
    await conn.execute('DROP TABLE IF EXISTS posts CASCADE')
    await conn.execute('''
        CREATE TABLE posts (
            id serial PRIMARY KEY,
            content varchar(255),
            author_id integer REFERENCES authors
        )
    ''')

@register_tables_creator
async def create_comment(conn):
    await conn.execute('DROP TABLE IF EXISTS comments CASCADE')
    await conn.execute('''
        CREATE TABLE comments(
            id SERIAL PRIMARY KEY,
            content text NOT NULL
        )
    ''')

@register_tables_creator
async def create_comments_posts(conn):
    await conn.execute('DROP TABLE IF EXISTS comments_posts')
    await conn.execute('''
        CREATE TABLE comments_posts (
            id SERIAL PRIMARY KEY,
            post_id integer REFERENCES posts,
            comment_id integer REFERENCES comments
        )
    ''')


from collections import deque

H, W = map(int, input().split())
r, c = map(lambda x: int(x)-1, input().split())
s = "".join([input() for _ in range(H)])
N = H * W
E = [[] for _ in range(N)]

for i in range(H):
    for j in range(W):
        x = i*W+j
        if i < H-1 and s[x+W] in ".^": E[x].append(x+W)
        if i >   0 and s[x-W] in ".v": E[x].append(x-W)
        if j < W-1 and s[x+1] in ".<": E[x].append(x+1)
        if j >   0 and s[x-1] in ".>": E[x].append(x-1)

reachable = [False]*N
Q = deque([r*W+c])
while Q:
    id = Q.popleft()

    if reachable[id]: continue
    reachable[id] = True

    for nid in E[id]:
        if reachable[nid]: continue
        Q.append(nid)

for i in range(H):
    for j in range(W):
        x = i*W+j
        if s[x] == "#":
            print("#", end="")
        elif reachable[x]:
            print("o", end="")
        else:
            print("x", end="")
    print()


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

# Script to run some or all PyGeodesy tests with Python 2 or 3.

# Tested with 64-bit Python 2.6.9, 2.7,13, 3.5.3 and 3.6.2 on
# macOS 10.12.5 and 10.12.6 Sierra and with Pythonista 3.1 on
# iOS 10.3.2 and 10.3.3.

from glob import glob
from os import environ, linesep as NL
from os.path import abspath, dirname, join
from time import time
import sys

_test_dir = dirname(abspath(__file__))
# extend sys.path to include the .. directory
if _test_dir not in sys.path:
    sys.path.insert(0, _test_dir)

from base import isiOS, PyGeodesy_dir, Python_O, \
          runner, secs2str, tilde, versions  # PYCHOK expected

__all__ = ()
__version__ = '17.08.10'

# command line options
_failedonly = False
_raiser     = False
_results    = False
_verbose    = False

if __name__ == '__main__':  # MCCABE 28

    def _write(text):
        _results.write(text.encode('utf-8'))

    argv0, args = tilde(sys.argv[0]), sys.argv[1:]

    if isiOS and not args:
        # allow this script to be used
        # with options inside Pythonista
        try:
            _input = raw_input  # old name
        except NameError:  # Python 3+
            _input = input
        args = _input('enter %s args: ' % (argv0,)).split()

    while args and args[0].startswith('-'):
        arg = args.pop(0)
        if '-help'.startswith(arg):
            print('usage: %s [-failedonly] [-raiser] [-results] [-verbose] [test/test...py ...]' % (argv0,))
            sys.exit(0)
        elif '-failedonly'.startswith(arg):
            _failedonly = True
        elif '-raiser'.startswith(arg):
            _raiser = True  # break on error
        elif '-results'.startswith(arg):
            _results = True
        elif '-verbose'.startswith(arg):
            _verbose = True
        else:
            print('%s invalid option: %s' % (argv0, arg))
            sys.exit(1)

    # replace home dir with ~
    Python_O = Python_O.replace(environ.get('HOME', '~'), '~')

    # shorten Python path [-OO]
    if len(Python_O) > 32:
        Python_O = Python_O[:16] + '...' + Python_O[-16:]

    # PyGeodesy and Python versions, size, OS name and release
    v = versions()

#   import pygeodesy
#   v = ' '.join((v, tilde(pygeodesy.__file__)))

    if _results:  # save all test results
        t = '-'.join(['testresults'] + v.split()) + '.txt'
        t = join(PyGeodesy_dir, 'testresults', t)
        _results = open(t, 'wb')  # note, 'b' not 't'!
        _write('%s typical test results (%s)%s' % (argv0, v, NL))

    if not args:  # no tests specified, get all test*.py
        # scripts in the same directory as this one
        args = sorted(glob(join(_test_dir, 'test*.py')))

    T, X, s = 0, 0, time()
    for arg in args:

        t = 'running %s %s' % (Python_O, tilde(arg))
        print(t)

        x, r = runner(arg)
        X += x  # failures, excluding KNOWN ones

        if _results:
            _write(NL + t + NL)
            _write(r)

        if not X:  # count the tests
            T += r.count(NL + '    test ')

        if 'Traceback' in r:
            print(r + NL)
            if not x:  # count as failure
                X += 1
            if _raiser:
                break

        elif _failedonly:
            for t in r.split(NL):
                # print failures, KNOWN ones and totals
                if 'FAILED,' in t or 'passed' in t:
                    print(t.rstrip())
            print('')

        elif _verbose:
            print(r + NL)

    if X:
        x = '%d FAILED' % (X,)
    elif T > 0:
        x = 'all %s tests OK' % (T,)
    else:
        x = 'all OK'

    s = secs2str(time() - s)
    t = '%s %s %s (%s) %s' % (argv0, Python_O, x, v, s)
    print(t)
    if _results:
        _write(NL + t + NL)
        _results.close()


import random
n=int(input("Введите колличество чисел в последовательности: "))
min=int(input("Введите минимальное число последователности: "))
max=int(input("Введите максимальное число последователности: "))

def funk():
    print ("Случайно сгенерированная последовательность:")
    a = [random.randint(min,max) for _ in range(n)]
    print(a)
    print("Первое число последовательности : ", a[0])
    print("Последнее число последовательности : ", a[-1])

funk()

ДЗ_6_Первый и Последний!.py

ДЗ_6_Первый и Последний!.py


import sys
sys.stdin = open('sw3819.txt', 'r')

for tc in range(1, int(input())+1):
    N = int(input())
    arr = [0 for _ in range(N)]
    sum_arr = [0 for _ in range(N)]
    res = 0
    minnum = 0
    maxnum = 0
    for n in range(N):
        arr[n] = int(input()) # arr에 각 데이터 입력
        if n==0:  # n이 0인 경우 이전 sum값이 없으므로 별도처리
            sum_arr[n] = arr[n]
        else:  # sum_arr에 index n번째 까지의 sum값 저장
            sum_arr[n] = sum_arr[n - 1] + arr[n]
            if sum_arr[n-1] < minnum:
                minnum = sum_arr[n-1]
        if sum_arr[n]-minnum > maxnum:
            maxnum = sum_arr[n]-minnum
    print("#%d %d" % (tc, maxnum))

# ## 런타임에러
# for tc in range(1, int(input())+1):
#     N = int(input())
#     arr = [0 for _ in range(N)]
#     res = 0
#     for n in range(N):
#         arr[n] = int(input())
#     for i in range(N):
#         for j in range(i, N):
#             temp = sum(arr[i:j+1])
#             # print(arr[i:j+1])
#             if temp > res:
#                 res = temp
#                 # print(res)
#     print("#%d %d" % (tc, res))


from transaction.models import Transaction
from users.models import User
from account.models import Account
from django.db import transaction
from transaction.constant import DEPOSIT, WITHDRAW
from django.db.utils import OperationalError
from transaction.error import ExitsError, AccountAuthError, BalanceError, LockError

class TransactionService:

    # 거래 내역 생성
    def create_transaction(self, amount: int, description: str, account: Account, transaction_type: str):
        transaction_history = Transaction.objects.create(
            account=account,
            amount=amount,
            balance=account.balance,
            transaction_type=transaction_type,
            description=description
        )
        return transaction_history

    # 계좌 존재 및 권한 확인
    def check_auth(self, user: Account, account_number: str):
        if not Account.objects.filter(account_number=account_number).exists():
            raise ExitsError

        account = Account.objects.filter(
            account_number=account_number, user=user)
        if not account.exists():
            raise AccountAuthError

        return account[0]

    # 입금 (트랜잭션)
    @transaction.atomic
    def deposit(self, account_number: str, amount: int, description: str) -> Transaction:
        try:
            # 계좌 잔액 수정
            account: Account = Account.objects.select_for_update(
                nowait=False).get(account_number=account_number)
            account.balance = account.balance + amount
            account.save()
            # 거래 내역 생성
            transaction_history: Transaction = self.create_transaction(
                amount, description, account, DEPOSIT)

            return transaction_history
        except OperationalError:
            raise LockError

    # 출금 (트랜잭션)
    @transaction.atomic
    def withdraw(self, account_number: str, amount: int, description: str) -> Transaction:
        try:
            # 계좌 잔액 수정
            account: Account = Account.objects.select_for_update(
                nowait=False).get(account_number=account_number)
            account.balance = account.balance - amount
            account.save()
            # 거래 내역 생성
            transaction_history: Transaction = self.create_transaction(
                amount, description, account, WITHDRAW)  # 거래 내역 생성

            return transaction_history
        except OperationalError:
            raise LockError

    # 거래 내역 조회
    def get_transaction_list(self, account: Account, started_date, end_date, transaction_type: str, offset: int, limit: int) -> list:
        # 필터링
        filters = self.transaction_list_filter(
            account, started_date, end_date, transaction_type)

        # 리스트 갯수
        list_count: int = Transaction.objects.filter(**filters).count()

        # 거래 내역 조회
        transaction_list: Transaction = Transaction.objects.filter(
            **filters).order_by("id")[offset:limit]

        transaction_history: list = self.obj_to_list(transaction_list, account)

        return transaction_history, list_count

    # 데이터 필터링 함수
    def transaction_list_filter(self, account: Account, start_date: str, end_date: str, transaction_type: str) -> dict:
        filters: dict = {'account': account}

        if transaction_type == WITHDRAW:
            filters['transaction_type'] = WITHDRAW
        elif transaction_type == DEPOSIT:
            filters['transaction_type'] = DEPOSIT

        if start_date and end_date:
            filters['created_at__gte'] = start_date
            filters['created_at__lt'] = end_date

        return filters

    def obj_to_data(self, transaction_history: Transaction) -> dict:
        result: dict = {
            "거래 계좌": transaction_history.account.account_number,
            "거래 금액": transaction_history.amount,
            "거래 후 금액": transaction_history.balance,
            "거래 종류": transaction_history.transaction_type,
            "거래 일시": transaction_history.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            "적요": transaction_history.description
        }
        return result

      # 데이터 변환
    def obj_to_list(self, transaction_list: Transaction, account: Account) -> list:
        results: list = [{
            '계좌 번호': account.account_number,
            '거래 후 잔액': transaction.balance,
            '금액': transaction.amount,
            '적요': transaction.description,
            '거래 종류': transaction.transaction_type,
            '거래 일시': transaction.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }for transaction in transaction_list]

        return results


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

import numpy as np

# Explicit Midpoint (2nd order RK Method) for 1st order ODE
# Inputs
#   f :  input function
#   t0: initial time condition
#   y0: initial condition
#   h : step size
# Outputs
#   y : array containing num approximations of each step (final index = soln)
def explicitMDPT(f, t0, y0, h):
    # calc num steps from inverse of step size
    N = int(1 / h)
    # initialize time array
    t = t0 + np.arange(N+1)*h
    # initialize output array
    y = np.zeros((N+1, np.size(y0)))
    # store initial condition
    y[0] = y0
    # Apply eMDPT iteratively
    for i in range(N):
        # 1st intermediate stage and approximation
        xi1 = y[i]
        f1 = f(t[i], xi1)
        # 2nd intermediate stage and approximation
        xi2 = y[i] + h/2 * f1
        f2 = f(t[i+1] + h/2, xi2)
        # final approximation and storage
        y[i+1] = y[i] + h * f2
    # return array of num approximations
    return y

# Sample ODE for approximation
def model(t,y):
    dydt = y
    return dydt
# Sample IVP for approximation
t0 = 0
y0 = 1


import cv2
import sys
import time
import os
import rospy
import numpy as np
from datetime import datetime
from collections import namedtuple
from digit_device import Device
import multiprocessing as mp
from test_hd.msg import state
from get_height.msg import Odometer_result
from get_height.msg import Height

class Odometer:
    R, R_sum, R_selected = np.eye(2), np.eye(2), np.eye(2)
    T, T_sum, T_selected = np.zeros((2,)), np.zeros((2,)), np.zeros((2,))
    is_visualize = True
    is_plot = True
    is_report = False
    is_ros = True
    is_gpu = False

    R_log, T_log = [], []

    def __init__(self):
        border = 0
        self.roi = [0 + border, 240 - border, 0 + border, 320 - border]
        self.feature_params = dict(maxCorners=100, qualityLevel=0.5, minDistance=5, blockSize=2)
        self.lk_params = dict(
            winSize=(20, 20), maxLevel=4, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 1, 0.03)
        )
        self.cms = "Odometer_Init"

    def __ros_callback(self, data):
        self.cms = data.state

    def __ros_listener(self):
        rospy.Subscriber("Cloth_Maipulation_State", state, self.__ros_callback)

    def __ros_publisher(self, height):
        pub = rospy.Publisher("current_height", Height, queue_size=10)
        pub_2 = rospy.Publisher("odometer_result", Odometer_result, queue_size=10)
        rospy.init_node("odometer", anonymous=True)
        rate = rospy.Rate(30)
        while not rospy.is_shutdown():
            rospy.loginfo(f"Odometer | Publishing current height {height.value}")
            pub.publish(height.value)
            rospy.loginfo(f"Odometer | Publishing odometer result {self.T_shared}")
            pub_2.publish([self.T_shared[0], self.T_shared[1]])
            rate.sleep()

    def crop_anything(self, thing, roi):
        return thing[roi[0] : roi[1], roi[2] : roi[3]]

    def reg_svd(self, A, B):
        centroid_A = np.mean(A, axis=0)
        centroid_B = np.mean(B, axis=0)
        AA = A - centroid_A
        BB = B - centroid_B
        H = np.dot(AA.T, BB)
        U, S, Vt = np.linalg.svd(H)
        R = np.dot(Vt.T, U.T)
        if np.linalg.det(R) < 0:
            Vt[1, :] *= -1
            R = np.dot(Vt.T, U.T)
        T = centroid_B.T - np.dot(R, centroid_A.T)
        return R, T

    def odometer(self, frame_queue, result_queue, visualize_queue, T_shared):
        if self.is_plot:
            import matplotlib.pyplot as plt
            import matplotlib.patches as patches

            fig, ax = plt.subplots(figsize=(10, 10), num="Odometer | View Port")
            plt.title("Odometer | View Port")
            plt.xlabel("Pixels")
            plt.ylabel("Pixels")
            ax.set_xlim([-500, 500])
            ax.set_ylim([-500, 500])
            rect_cloth = patches.Rectangle((-400, -400), 800, 800, color="green")
            rect_gelsight = patches.Rectangle((-74, -90), 147, 180, alpha=0.5, color="red", rotation_point="center")
            ax.add_patch(rect_cloth)
            ax.add_patch(rect_gelsight)

        from gelsight import gs3drecon  # import outside will cause error

        model_file_path = "/home/ratiomiith/Development/DigitCloth/ros_workspace/src/get_height/scripts/"
        net_file_path = "nnmini.pt"
        net_path = os.path.join(model_file_path, net_file_path)

        gpuorcpu = "cuda" if self.is_gpu else "cpu"

        Device_Alias = namedtuple("GelSightMini", ["imgw", "imgh"])  # gelsight sdk requires this
        dev_alias = Device_Alias(240, 320)
        nn = gs3drecon.Reconstruction3D(gs3drecon.Finger.R15, dev_alias)
        nn.load_nn(net_path, gpuorcpu)

        frame_count = 0

        try:
            while True:
                tic = time.time()

                frame = frame_queue.get()
                frame_count += 1
                depthmap = nn.get_depthmap(frame, mask_markers=False)
                frame = self.crop_anything(frame, self.roi)  # Discard the Markers area
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                if frame_count < 60:
                    prev_gray = gray
                    prev_corners = None
                    continue

                depth_mask = np.zeros_like(depthmap, dtype=np.uint8)
                depth_mask[depthmap < -1.5] = 1
                depth_mask = self.crop_anything(depth_mask, self.roi)

                contact_check = np.sum(depth_mask)
                self.contact_check.value = contact_check

                if (
                    contact_check != 0 and prev_corners is None
                ):  # Set current frame as previous frame if contact is detected
                    prev_corners = cv2.goodFeaturesToTrack(prev_gray, mask=depth_mask, **self.feature_params)
                    prev_gray = gray
                elif contact_check != 0 and prev_corners is not None and len(prev_corners) > 2:
                    # Do odometer
                    curr_corners, _, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, prev_corners, None, **self.lk_params)
                    curr_corners = curr_corners.squeeze()
                    prev_corners = prev_corners.squeeze()

                    # Registartion
                    R, T = self.reg_svd(prev_corners, curr_corners)

                    self.R_sum = np.matmul(self.R_sum, R)
                    self.T_sum = self.T_sum + T
                    T_shared[0] = self.T_sum[0]
                    T_shared[1] = self.T_sum[1]

                    if self.cms == "turnL_clock":
                        self.R_selected = np.matmul(self.R_selected, R)
                        self.T_selected = self.T_selected + T

                    if self.is_visualize:
                        self.visualize(frame, prev_corners, curr_corners, depth_mask, visualize_queue)
                    if self.is_plot:
                        # T_scaled = self.T_sum / 17.13  # T_sum counts in pixel, Visualize in mm
                        rect_gelsight.set_angle(np.rad2deg(np.arctan2(self.R_sum[1, 0], self.R_sum[0, 0])))
                        rect_gelsight.set_xy((-74 - self.T_sum[1], -90 - self.T_sum[0]))
                        center_gelsight = rect_gelsight.get_center()
                        # ax.scatter(center_gelsight[0], center_gelsight[1], s=2, c="yellow")  # This causes slow down
                        plt.pause(0.001)

                    prev_corners = cv2.goodFeaturesToTrack(prev_gray, mask=depth_mask, **self.feature_params)
                    prev_gray = gray
                else:
                    prev_corners = None

                packed_results = {"Process": "Odometer", "R": self.R_sum, "T": self.T_sum}
                result_queue.put(packed_results)

                sys.stdout.write(f"FPS: {1/(time.time()-tic):.2f}, Contact Check: {contact_check}, T: {self.T_sum}\r")
        except KeyboardInterrupt:
            print("Odometer | KeyboardInterrupt")

    def visualize(self, frame, prev_corners, curr_corners, depth_mask, output_queue=None):
        canvas = np.zeros_like(frame)
        for i, (new, old) in enumerate(zip(curr_corners, prev_corners)):
            a, b = new.ravel()
            c, d = old.ravel()
            a, b, c, d = int(a), int(b), int(c), int(d)
            cv2.line(canvas, (a, b), (c, d), (0, 255, 0), 2)
            cv2.circle(canvas, (a, b), 5, (0, 0, 255), -1)
        frame_masked = frame.copy()
        frame_masked[depth_mask != 1] = [0, 0, 0]
        result = cv2.add(frame_masked, canvas)

        packed_frames = {
            "Process": "Odometer",
            "result": result,
        }
        output_queue.put(packed_frames)

    def run(self, frame_queue, result_queue, visualize_queue):
        self.processes = []
        manager = mp.Manager()
        self.T_shared = manager.Array("d", [0, 0])  # Shared memory for T
        self.contact_check = manager.Value("d", 0)  # Shared memory for contact check

        if self.is_ros:
            self.processes.append(mp.Process(target=self.__ros_listener))
            self.processes.append(mp.Process(target=self.__ros_publisher, args=(self.contact_check,)))
        self.processes.append(
            mp.Process(target=self.odometer, args=(frame_queue, result_queue, visualize_queue, self.T_shared))
        )

        [p.start() for p in self.processes]

    def save(self):
        self.T_log.append(np.array(self.T_shared))
        sys.stdout.write(f"\nSaved T: {self.T_shared}")

    def stop(self):
        [p.terminate() for p in self.processes]

def main():
    gsmini = Device()
    odometer = Odometer()

    frame_queue = mp.Queue()
    result_queue = mp.Queue()
    visualize_queue = mp.Queue()

    gsmini.run(frame_queue)
    odometer.run(frame_queue, result_queue, visualize_queue)

    time = datetime.now()

    # Visualize
    try:
        while True:
            # packed_results = result_queue.get()
            packed_frames = visualize_queue.get()
            if packed_frames["Process"] == "Odometer":
                cv2.imshow("Odometer | Tracking", packed_frames["result"])
                odometer.save()

            getKey = cv2.waitKey(1)
            if getKey & 0xFF == ord("q"):
                break
            elif getKey == 32:  # Spacebar
                odometer.save()
    finally:
        gsmini.stop()
        odometer.stop()
        time_str = time.strftime("%Y%m%d-%H%M%S")
        np.save("output/T_log_exp_odometer_" + time_str + ".npy", odometer.T_log)

if __name__ == "__main__":
    main()


from __future__ import print_function, division
import numpy as np
import time

"""
Stochastic Primal-Dual Hybrid Gradient (SPDHG) algorithms
"""

def spdhg(x, proximal_x, proximal_y, A, Ablk, Atblk, index, tau, sigma, if_average, niter, **kwargs):
    """Computes a saddle point with a stochastic PDHG.
    This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that
    (x*, y*) in arg min_x max_y sum_i=1^m <y_i, A_i x> - f*_i(y_i) + g(x),
    where A in R^m*n, A_i is the ith row of A.
    g and f*_i are convex functions.
    For this algorithm, they all may be non-smooth and no strong convexity is assumed.
    Parameters
    ----------
    x : primal variable.
    proximal_x : proximal operator of objective function g of x
    proximal_y : proximal operator of objective function f* of y
    A : matrix in R^m*n
    Ablk: a list whose element is matrix. It define the partition of A
    Atblk: a list whose element is the transpose of the element of Ablk
    index: a list whose element is index. It define the partition of x
    tau : scalar, step size for primal variable.
    sigma : vector in R^m, step size for dual variable.
    if_average: if use the average of the output.
    niter : int, number of iterations
    Other Parameters
    ----------------
    y : dual variable. By default equals 0.
    z : intermediate variable, represents At*y.
    primal_obj_func : primal objective function.
    dual_obj_func : dual objective function.
    verbose: True or False. Print the information of each step if true, don't print otherwise.
    print_dist : int. Print information after every print_dist iterations
    theta : scalar. extrapolation factor for y.
    extra: scalar. local extrapolation parameters for y. By default extra = 1.
    References
    ----------
    [CERS2017] A. Chambolle, M. J. Ehrhardt, P. Richtarik and C.-B. Schoenlieb,
    *Stochastic Primal-Dual Hybrid Gradient Algorithm with Arbitrary Sampling
    and Imaging Applications*. ArXiv: http://arxiv.org/abs/1706.04957 (2017).
    [E+2017] M. J. Ehrhardt, P. J. Markiewicz, P. Richtarik, J. Schott,
    A. Chambolle and C.-B. Schoenlieb, *Faster PET reconstruction with a
    stochastic primal-dual hybrid gradient method*. Wavelets and Sparsity XVII,
    58 (2017) http://doi.org/10.1117/12.2272946.
    """

    # get the dimension
    m, n = A.shape

    # Dual variable
    y = kwargs.pop('y', None)
    if y is None:
        y = np.zeros(m)

    # Adjoint of dual variable
    z = kwargs.pop('z', None)
    if z is None:
        z = A.transpose().dot(y)

    # primal objective value of x
    # dual objective value of y
    primal_obj_func = kwargs.pop('primal_obj_func', None)
    if primal_obj_func is None:
        def primal_obj_func(x):
            return 0
    dual_obj_func = kwargs.pop('dual_obj_func', None)
    if dual_obj_func is None:
        def dual_obj_func(x):
            return 0

    # print setup
    verbose = kwargs.pop('verbose', None)
    print_dist = kwargs.pop('print_dist', 1)

    # Global extrapolation factor theta
    theta = kwargs.pop('theta', 1)

    # Second extrapolation factor
    extra = kwargs.pop('extra', 1)

    # Initialize variables
    xx = x = x.copy()
    z_bar = z
    blk_r = len(Ablk)
    At = A.transpose()
    primal_obj_val = []
    dual_obj_val = []
    gap = []
    each_time = []
    total_time = 0

    # Print initial information
    if verbose:
        print('Start SPDHG...')
        print(
            '{message:{fill}{align}{width}}'.format(message='', fill='=', align='^', width=100, ), '\n',
            '{message:{fill}{align}{width}}'.format(message='Epoch', fill=' ', align='^', width=13, ), '|',
            '{message:{fill}{align}{width}}'.format(message='Primal Obj', fill=' ', align='^', width=13, ), '|',
            '{message:{fill}{align}{width}}'.format(message='Dual Obj', fill=' ', align='^', width=13, ), '|',
            '{message:{fill}{align}{width}}'.format(message='Gap', fill=' ', align='^', width=13, ), '|',
            '{message:{fill}{align}{width}}'.format(message='Each Time', fill=' ', align='^', width=13, ), '|',
            '{message:{fill}{align}{width}}'.format(message='Total Time', fill=' ', align='^', width=13, ), '\n',
            '{message:{fill}{align}{width}}'.format(message='', fill='-', align='^', width=100, )
        )

    # run the iterations
    for k in range(niter):

        # record the start time of each iteration
        start_time = time.time()

        # update primal variable
        # z_bar = A.adjoint * y_bar
        # temp = x - tau * z_bar
        temp = x - tau * z_bar

        # fully update x
        x = proximal_x(temp, tau)

        # save old yi
        mask = index[k % blk_r]
        y_old = y[mask]

        # temp = y_old[i] + sigma_i * (Ai*x)
        temp = y_old + sigma * (Ablk[k % blk_r].dot(x))

        # update y
        y[mask] = y_new = proximal_y(mask, temp, sigma)

        # update dz
        dz = extra * Atblk[k % blk_r].dot(y_new - y_old)

        # update z z_bar
        z += dz
        z_bar = z + theta * dz

        if if_average:
            xx = (k / (k + 1)) * xx + (1 / (k + 1)) * x
        else:
            xx = x

        # store information
        primal_obj_val.append(primal_obj_func(xx))
        dual_obj_val.append(dual_obj_func(y))
        gap.append(primal_obj_val[-1] - dual_obj_val[-1])
        each_time.append(time.time() - start_time)
        total_time = total_time + each_time[-1]

        # print the information
        if verbose:
            if k % print_dist == 0:
                print(
                    '{:^14.4f}'.format(int(k/blk_r)), '|',
                    '{:^13.3e}'.format(primal_obj_val[-1]), '|',
                    '{:^13.3e}'.format(dual_obj_val[-1]), '|',
                    '{:^14.4e}'.format(gap[-1]), '|',
                    '{:^13.3f}'.format(each_time[-1]), '|',
                    '{:^13.3e}'.format(total_time), '|',
                )

    return dict(primal_opt=xx, dual_opt=y, primal_obj_val=primal_obj_val, dual_obj_val=dual_obj_val, gap=gap,
                each_time=each_time, total_time=total_time)


# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, abort, jsonify, request, redirect, url_for, g, \
    flash, current_app

from leancloud import Query

from ..utils.user import require_login, require_admin
from ..models import Account
from ..forms import SearchAccountForm, EditAccountForm
from ..utils.helpers import force_int

__author__ = 'Simi'
__all__ = ['bp']
bp = Blueprint('admin', __name__)

@bp.route('/')
@require_login
def index():
    return render_template('admin/index_type.html')

@bp.route('/user')
@require_login
@require_admin
def user():
    page = force_int(request.args.get('page', 1), 1)
    page_size = 10

    q = Query("_User")

    search_form = SearchAccountForm()

    keyword = None
    if request.method == 'GET':
        search_form.keyword.data = keyword = request.args.get('keyword', '')

    if search_form.validate_on_submit():
        keyword = search_form.keyword.data.strip()

    if keyword:
        if "@" in keyword:
            q = q.startswith("email", keyword)
        else:
            q = q.startswith("username", keyword)

    users = q.skip((page - 1) * page_size).limit(page_size).find()
    count = q.count()
    pages = count / page_size + 1

    return render_template('admin/user.html', users=users, form=search_form, count=count, pages=pages, page=page)

@bp.route('/user/edit/<string:id>', methods=['GET', 'POST'])
@require_login
@require_admin
def edit_user(id):
    user = Account.get(id)
    if not user:
        abort(404)
    form = EditAccountForm(obj=user)

    if form.validate_on_submit():
        user.set('state', form.state.data)
        user.set('roles', [form.role.data])
        user.save()
        flash('用户 %s 的信息已成功保存' % user.get('username'), 'success')
        return redirect(url_for('.user'))
    else:
        roles = user.get('roles')
        if roles:
            # 当前仅支持一个用户拥有一种角色
            form.role.data = roles[0]
        state = user.get('state')
        if state:
            form.state.data = state
    return render_template('admin/edit_user.html', form=form, user=user)


# This source code is inspired by Yuxin Wu's repo(tensorpack/expamples/dorefanet.py)
import tensorflow as tf

from tensorpack.utils.argtools import graph_memoized
#from tensorpack.callbacks.base import Callback

__all__ = ['ternarize']

def quantize_midtread(x, k):
    n = float(2 ** k - 1)

    @tf.custom_gradient
    def _quantize_midtread(x):
        return tf.round(x * n) / n, lambda dy: dy

    return _quantize_midtread(x)

def quantize_midrise(x, k):
    n = float(2 ** k - 0.5)

    @tf.custom_gradient
    def _quantize_midrise(x):
        return (tf.floor(x * n) + 0.5) / n, lambda dy: dy

    return _quantize_midrise(x)

def quantize_odd(x, s):
    n = float((s - 1) / 2)

    @tf.custom_gradient
    def _quantize_odd(x):
        return tf.round(x * n) / n, lambda dy: dy

    return _quantize_odd(x)

def quantize_even(x, s):
    n = float(s / 2 - 0.5)

    @tf.custom_gradient
    def _qunatize_even(x):
        return (tf.floor(x * n) + 0.5) / n, lambda dy: dy

    return _qunatize_even(x)

'''
class GlobalStep(Callback):
    def get_global_step(self):
        return self.trainer.global_step
'''

def quantize_weight(bitW, name, opts, quantizer_config):
    # 1. Linear Quantization
    if name == 'linear':
        # 1-Level Quantization
        if eval(opts['centralized']) == False or eval(opts['centralized']) == True:
            def qw(x):
                if bitW == 32:

                    if quantizer_config['mulR'] in ['2R', 'R']:
                        if eval(opts['fix_max']):
                            param_name = x.op.name.split('/W')[0] + '/maxW'
                            max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32), name=param_name)
                            tf.add_to_collection('maxs', max_x)
                        else:
                            param_name = x.op.name.split('/W')[0] + '/maxW'
                            max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)), name=param_name)
                            tf.add_to_collection('maxs', max_x)

                    return x

                if eval(opts['fix_max']):
                    #param_name = 'regularize_cost_internals/' + x.op.name.split('/W')[0] + '/maxW'
                    param_name = x.op.name.split('/W')[0] + '/maxW_stop_grad'
                    max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32))
                    max_x = tf.multiply(float(opts['max_scale']), max_x, name=param_name)
                    x = tf.clip_by_value(x, -max_x, max_x)
                else:
                    param_name = x.op.name.split('/W')[0] + '/maxW_stop_grad'
                    max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)), name=param_name)

                tf.add_to_collection('maxs', max_x)

                x = x / max_x

                if eval(opts['is_Lv']): # midtread
                    assert bitW != 1, '[ConfigError]Cannot quantize weight to 1-bit with midtread method'
                    if bitW == 3:
                        if eval(opts['fix_max']):
                            return ternarize_fixmax(x, max_x)
                        else:
                            return ternarize(x)
                    x = quantize_odd(x, bitW)
                else:  # midrise
                    x = quantize_midrise(x, bitW - 1)

                #w_s = tf.get_variable('scale_Ws', initializer=1.0, dtype=tf.float32)
                return tf.multiply(max_x, x)
            return qw

    # intervals quantization
    elif name == 'intQ':

        @tf.custom_gradient
        def qw(x):
            if bitW == 32:
                if quantizer_config['mulR'] in ['2R', 'R']:
                    if eval(opts['fix_max']):
                        param_name = x.op.name.split('/W')[0] + '/maxW'
                        max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32), name=param_name)
                        tf.add_to_collection('maxs', max_x)
                    else:
                        param_name = x.op.name.split('/W')[0] + '/maxW'
                        max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)), name=param_name)
                        tf.add_to_collection('maxs', max_x)

                return x

            if eval(opts['fix_max']):
                #param_name = 'regularize_cost_internals/' + x.op.name.split('/W')[0] + '/maxW'
                param_name = x.op.name.split('/W')[0] + '/maxW_stop_grad'
                max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32), name=param_name)
            else:
                param_name = x.op.name.split('/W')[0] + '/maxW_stop_grad'
                max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)), name=param_name)

            tf.add_to_collection('maxs', max_x)

            n = (bitW - 1) / 2

            x_abs = tf.abs(x)

            lower = max_x * 0.05
            upper = max_x * 0.95

            x_temp = tf.conf(x_abs < lower, tf.zeros_like(x_abs), tf.clip_by_value(x_abs, lower, upper*0.9999))
            x_temp = (n / 0.9 * max_x) * x_temp + (0.5 - (0.5 * n / 9))
            x_temp = tf.round(x_temp)

            x_temp = x_temp / n * upper

            x_temp = x_temp * tf.sign(x)

            return x_temp, lambda dy: dy
        return qw

    # 2. Centroid Quantization
    elif name == 'cent':

        if type(opts['threshold_bit']) == str:
            inBIT, exBIT = eval(opts['threshold_bit'])
        else:
            inBIT, exBIT = opts['threshold_bit']
        ratio = (1 / (1 + ((2 ** exBIT - 1) / (2 ** inBIT - 1))))

        def qw(x):
            if bitW == 32:
                return x

            if eval(opts['fix_max']):
                #param_name = 'regularize_cost_internals/' + x.op.name.split('/W')[0] + '/maxW'
                max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32))
                max_x *= float(opts['max_scale'])
                x = tf.clip_by_value(x, -max_x, max_x)
            else:
                max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)))

            thresh = ratio * max_x
            thresh2 = thresh * 0.999

            mask = tf.get_variable('maskW', shape=x.shape, initializer=tf.ones_initializer, dtype=tf.float32)

            x = tf.where(tf.equal(1.0, mask), tf.clip_by_value(x, -thresh2, thresh2), x)

            x = x / max_x

            if eval(opts['is_Lv']): # midtread
                assert bitW != 1, '[ConfigError]Cannot quantize weight to 1-bit with midtread method'
                x = quantize_odd(x, bitW)
            else:  # midrise
                x = quantize_midrise(x, bitW - 1)

            #w_s = tf.get_variable('scale_Ws', initializer=1.0, dtype=tf.float32)
            return tf.multiply(max_x, x)
        return qw

    # 3. Dynamic Network Surgery
    elif name == 'dns':

        if type(opts['threshold_bit']) == str:
            inBIT, exBIT = eval(opts['threshold_bit'])
        else:
            inBIT, exBIT = opts['threshold_bit']
        ratio = (1 / (1 + ((2 ** exBIT - 1) / (2 ** inBIT - 1))))

        def qw(x):
            if bitW == 32:
                return x

            if eval(opts['fix_max']):
                # param_name = 'regularize_cost_internals/' + x.op.name.split('/W')[0] + '/maxW'
                max_x = tf.stop_gradient(tf.get_variable('maxW', initializer=1.0, dtype=tf.float32))
                x = tf.clip_by_value(x, -max_x, max_x)
                max_x *= float(opts['max_scale'])
            else:
                max_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)))
            x = x / max_x

            thresh = ratio * max_x * 0.999

            if eval(opts['is_Lv']):  # midtread
                assert bitW != 1, '[ConfigError]Cannot quantize weight to 1-bit with midtread method'
                if bitW == 3:
                    return ternarize(x)

                mask = tf.get_variable('maskW', shape=x.shape, initializer=tf.ones_initializer, dtype=tf.float32)

                @tf.custom_gradient
                def clip_with_STE(x):
                    return tf.clip_by_value(x, -thresh, thresh), lambda dy: dy

                x = tf.where(tf.equal(0.0, mask), clip_with_STE(x), x)
                x = quantize_odd(x, bitW)
            else:  # midrise
                x = quantize_midrise(x, bitW - 1)

            #w_s = tf.get_variable('scale_Ws', initializer=1.0, dtype=tf.float32)
            return tf.multiply(max_x, x)

        return qw

def quantize_activation(bitA, name, q_config):
    if name == 'intQ':
        @tf.custom_gradient
        def qa(x):
            name = x.op.name
            ema_name = name + '_ema'

            c = tf.get_variable(ema_name, initializer=0.0, dtype=tf.float32)

            max_a = tf.max(x)

            temp_c = max_a

            new_c = tf.cond(tf.get_global_step() == 0, temp_c, c * 0.99 + temp_c * 0.01, name=ema_name + '_new')

            #op = tf.assign(c, new_c, use_locking=False).op

            tf.add_to_collection('new_cs', new_c)

            n = 2 ** bitA - 1

            lower = new_c * 0.05
            upper = new_c * 0.95

            x_temp = tf.conf(x < lower, tf.zeros_like(x), tf.clip_by_value(x, lower, upper*0.9999))
            x_temp = (n / 0.9 * new_c) * x_temp + (0.5 - (0.5 * n / 9))
            x_temp = tf.round(x_temp)

            x_temp = x_temp / n * upper

            return x_temp, lambda dy: dy

        return qa

    def qa(x):
        if bitA == 32:
            return x
        return quantize_midtread(x, bitA)
    return qa

def quantize_gradient(bitG):
    def qg(x):
        if bitG == 32:
            return x

        @tf.custom_gradient
        def _identity(input):
            def grad_fg(x):
                rank = x.get_shape().ndims
                assert rank is not None
                maxx = tf.reduce_max(tf.abs(x), list(range(1, rank)), keep_dims=True)
                x = x / maxx
                n = float(2**bitG - 1)
                x = x * 0.5 + 0.5 + tf.random_uniform(
                    tf.shape(x), minval=-0.5 / n, maxval=0.5 / n)
                x = tf.clip_by_value(x, 0.0, 1.0)
                x = quantize_midtread(x, bitG) - 0.5
                return x * maxx * 2
            return input, grad_fg
        return _identity(x)
    return qg

def ternarize(x, thresh=0.05):
    """
    Implemented Trained Ternary Quantization:
    https://arxiv.org/abs/1612.01064
    Code modified from the authors' at:
    https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
    """
    shape = x.get_shape()

    thre_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)) * thresh)

    w_p = tf.get_variable('Wp', initializer=1.0, dtype=tf.float32)
    w_n = tf.get_variable('Wn', initializer=1.0, dtype=tf.float32)

    tf.summary.scalar(w_p.op.name + '-summary', w_p)
    tf.summary.scalar(w_n.op.name + '-summary', w_n)

    mask = tf.ones(shape)
    mask_p = tf.where(x > thre_x, tf.ones(shape) * w_p, mask)
    mask_np = tf.where(x < -thre_x, tf.ones(shape) * w_n, mask_p)
    mask_z = tf.where((x < thre_x) & (x > - thre_x), tf.zeros(shape), mask)

    @tf.custom_gradient
    def _sign_mask(x):
        return tf.sign(x) * mask_z, lambda dy: dy

    w1 = _sign_mask(x)

    w2 = tf.multiply(w1, mask_np, name='QW')

    #w_loss = 0.5 * tf.reduce_sum(tf.square(w1))
    #tf.add_to_collection('regularization_losses', w_loss)

    tf.summary.histogram(w2.name, w2)
    return w2

def ternarize_fixmax(x, max_x):

    thresh = 0.05

    shape = x.get_shape()

    thre_x = max_x * thresh

    w_s = tf.get_variable('Ws', initializer=1.0, dtype=tf.float32)

    tf.summary.scalar(w_s.op.name + '-summary', w_s)

    mask = tf.ones(shape)
    mask_s = tf.where(tf.logical_or(x > thre_x, x < -thresh), tf.ones(shape) * w_s, mask)
    mask_z = tf.where((x < thre_x) & (x > - thre_x), tf.zeros(shape), mask)

    @tf.custom_gradient
    def _sign_mask(x):
        return tf.sign(x) * mask_z, lambda dy: dy

    w1 = _sign_mask(x)

    w2 = tf.multiply(w1, mask_s, name='QW')

    #w_loss = 0.5 * tf.reduce_sum(tf.square(w1))
    #tf.add_to_collection('regularization_losses', w_loss)

    tf.summary.histogram(w2.name, w2)
    return w2


from inventory_report.inventory.product import Product

def produto_mock():
    return {
      "id": 1,
      "nome_da_empresa": "Farinini",
      "nome_do_produto": "farinha",
      "data_de_fabricacao": "01-05-2021",
      "data_de_validade": "02-06-2023",
      "numero_de_serie": "AA22",
      "instrucoes_de_armazenamento": "ao abrigo de luz"
    }

def test_relatorio_produto():
    produto = produto_mock()

    cria_produto = Product(
        produto["id"],
        produto["nome_do_produto"],
        produto["nome_da_empresa"],
        produto["data_de_fabricacao"],
        produto["data_de_validade"],
        produto["numero_de_serie"],
        produto["instrucoes_de_armazenamento"]
    )

    resultado_esperado = ("O produto farinha fabricado em 01-05-2021 por" +
                          " Farinini com validade até 02-06-2023 precisa ser" +
                          " armazenado ao abrigo de luz.")

    assert cria_produto.__repr__() == resultado_esperado