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

"""Appengine Tasks related to GHOP Task handling.
"""

__authors__ = [
    '"Madhusudan.C.S" <madhusudancs@gmail.com>'
  ]

import logging

from google.appengine.api.labs import taskqueue
from google.appengine.ext import db

from django import http
from django.utils.translation import ugettext

from soc.logic import system
from soc.tasks.helper import error_handler
from soc.views.helper import redirects

from soc.modules.ghop.logic.models import task as ghop_task_logic

DEF_TASK_UPDATE_SUBJECT_FMT = ugettext('[GHOP Task Update] %(title)s')

def getDjangoURLPatterns():
  """Returns the URL patterns for the tasks in this module.
  """

  patterns = [
      (r'^tasks/ghop/task/update$',
       'soc.modules.ghop.tasks.task_update.updateGHOPTask'),
      (r'^tasks/ghop/task/mail/create$',
       'soc.modules.ghop.tasks.task_update.createNotificationMail'),
      (r'^tasks/ghop/task/update/student_status$',
       'soc.modules.ghop.tasks.task_update.updateTasksPostStudentSignUp')]

  return patterns

def spawnUpdateTask(entity):
  """Spawns a task to update the state of the task.
  """

  update_params = {
      'ghop_task_key': entity.key().name(),
      }
  update_url = '/tasks/ghop/task/update'

  new_task = taskqueue.Task(eta=entity.deadline,
                            params=update_params,
                            url=update_url)
  new_task.add('ghop-update')

def updateGHOPTask(request, *args, **kwargs):
  """Method executed by Task Queue API to update a GHOP Task to
  relevant state.

  Expects the ghop_task_key entry to be present in the POST dict.

  Args:
    request: the standard Django HTTP request object
  """

  post_dict = request.POST

  key_name = post_dict.get('ghop_task_key')

  if not key_name:
    # invalid task data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid updateGHOPTask data: %s' % post_dict)

  entity = ghop_task_logic.logic.getFromKeyNameOr404(key_name)

  entity, comment_entity, ws_entity = ghop_task_logic.logic.updateTaskStatus(
      entity)

  if entity:
    # TODO(madhusudan): does this really mean an unsuccessful update?
    # return OK
    return http.HttpResponse()

def spawnCreateNotificationMail(entity):
  """Spawns a task to send mail to the user who has subscribed to the specific
  task.

  Args:
    entity: The Comment entity for which mails must be sent
  """

  task_params = {
      'comment_key': entity.key().id_or_name(),
      'task_key': entity.parent_key().id_or_name(),
      }
  task_url = '/tasks/ghop/task/mail/create'

  new_task = taskqueue.Task(params=task_params, url=task_url)
  new_task.add('mail')

def createNotificationMail(request, *args, **kwargs):
  """Appengine task that sends mail to the subscribed users.

  Expects the following to be present in the POST dict:
    comment_key: Specifies the comment id for which to send the notifications
    task_key: Specifies the task key name for which the comment belongs to

  Args:
    request: Django Request object
  """

  from soc.modules.ghop.logic.helper import notifications as ghop_notifications

  from soc.modules.ghop.logic.models import comment as ghop_comment_logic
  from soc.modules.ghop.logic.models import task_subscription as \
      ghop_task_subscription_logic

  # set default batch size
  batch_size = 10

  post_dict = request.POST

  comment_key = post_dict.get('comment_key')
  task_key = post_dict.get('task_key')

  if not (comment_key and task_key):
    # invalid task data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid createNotificationMail data: %s' % post_dict)

  comment_key = long(comment_key)

  # get the task entity under which the specified comment was made
  task_entity = ghop_task_logic.logic.getFromKeyName(task_key)

  # get the comment for the given id
  comment_entity = ghop_comment_logic.logic.getFromID(
      comment_key, task_entity)

  if not comment_entity:
    # invalid comment specified, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid comment specified: %s/%s' % (comment_key, task_key))

  # check and retrieve the subscriber_start_key that has been done last
  if 'subscriber_start_index' in post_dict:
    subscriber_start_index = post_dict['subscriber_start_index']
  else:
    subscriber_start_index = 0

  # get all subscribers to GHOP task
  fields = {
      'task': task_entity,
      }

  ts_entity = ghop_task_subscription_logic.logic.getForFields(
      fields, unique=True)

  subscribers = db.get(ts_entity.subscribers[
      subscriber_start_index:subscriber_start_index+batch_size])

  task_url = "http://%(host)s%(task)s" % {
                 'host': system.getHostname(),
                 'task': redirects.getPublicRedirect(
                     task_entity, {'url_name': 'ghop/task'}),
                 }

  # create the data for the mail to be sent
  message_properties = {
      'task_url': task_url,
      'redirect_url': "%(task_url)s#c%(cid)d" % {
          'task_url': task_url,
          'cid': comment_entity.key().id_or_name()
          },
      'comment_entity': comment_entity,
      'task_entity': task_entity,
  }

  subject = DEF_TASK_UPDATE_SUBJECT_FMT % {
      'title': task_entity.title,
      }

  for subscriber in subscribers:
    ghop_notifications.sendTaskUpdate(entity, subject, message_properties)

  if len(subscribers) == batch_size:
    # spawn task for sending out notifications to next set of subscribers
    next_start = subscriber_start_index + batch_size

    task_params = {
        'comment_key': comment_key,
        'task_key': task_key,
        'subscriber_start_index': next_start
        }
    task_url = '/tasks/ghop/task/mail/create'

    new_task = taskqueue.Task(params=task_params, url=task_url)
    new_task.add('mail')

  # return OK
  return http.HttpResponse()

def updateTasksPostStudentSignUp(request, *args, **kwargs):
  """Appengine task that updates the GHOP Tasks after the student signs up.

  Expects the following to be present in the POST dict:
    student_key: Specifies the student key name who registered

  Args:
    request: Django Request object
  """
  from soc.modules.ghop.logic.models import student as ghop_student_logic

  post_dict = request.POST

  student_key = post_dict.get('student_key')

  if not student_key:
    # invalid student data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid Student data: %s' % post_dict)

  student_entity = ghop_student_logic.logic.getFromKeyNameOr404(student_key)

  # retrieve all tasks currently assigned to the user
  task_fields = {
      'user': student_entity.user,
      }
  task_entities = ghop_task_logic.logic.getForFields(task_fields)

  # TODO(madhusudan) move this to the Task Logic
  # Make sure the tasks store references to the student as well as
  # closing all tasks that are AwaitingRegistration.
  for task_entity in task_entities:
    task_entity.student = student_entity
    if task_entity.status == 'AwaitingRegistration':
      task_entities.remove(task_entity)

      properties = {'status': 'Closed'}
      changes = [ugettext('User-MelangeAutomatic'),
                 ugettext('Action-Student registered'),
                 ugettext('Status-%s' % (properties['status']))]

      comment_properties = {
          'parent': task_entity,
          'scope_path': task_entity.key().name(),
          'created_by': None,
          'changes': changes,
          'content': ugettext(
              '(The Melange Automated System has detected that the student '
              'has signed up for the program and hence has closed this task.'),
          }

      ghop_task_logic.logic.updateEntityPropertiesWithCWS(
          task_entity, properties, comment_properties)

  db.put(task_entities)

  # return OK
  return http.HttpResponse()
<commit_msg>Removed obsolete value to unpack in the updateGHOPTask Task.<commit_after>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Appengine Tasks related to GHOP Task handling.
"""

__authors__ = [
    '"Madhusudan.C.S" <madhusudancs@gmail.com>'
  ]

import logging

from google.appengine.api.labs import taskqueue
from google.appengine.ext import db

from django import http
from django.utils.translation import ugettext

from soc.logic import system
from soc.tasks.helper import error_handler
from soc.views.helper import redirects

from soc.modules.ghop.logic.models import task as ghop_task_logic

DEF_TASK_UPDATE_SUBJECT_FMT = ugettext('[GHOP Task Update] %(title)s')

def getDjangoURLPatterns():
  """Returns the URL patterns for the tasks in this module.
  """

  patterns = [
      (r'^tasks/ghop/task/update$',
       'soc.modules.ghop.tasks.task_update.updateGHOPTask'),
      (r'^tasks/ghop/task/mail/create$',
       'soc.modules.ghop.tasks.task_update.createNotificationMail'),
      (r'^tasks/ghop/task/update/student_status$',
       'soc.modules.ghop.tasks.task_update.updateTasksPostStudentSignUp')]

  return patterns

def spawnUpdateTask(entity):
  """Spawns a task to update the state of the task.
  """

  update_params = {
      'ghop_task_key': entity.key().name(),
      }
  update_url = '/tasks/ghop/task/update'

  new_task = taskqueue.Task(eta=entity.deadline,
                            params=update_params,
                            url=update_url)
  new_task.add('ghop-update')

def updateGHOPTask(request, *args, **kwargs):
  """Method executed by Task Queue API to update a GHOP Task to
  relevant state.

  Expects the ghop_task_key entry to be present in the POST dict.

  Args:
    request: the standard Django HTTP request object
  """

  post_dict = request.POST

  key_name = post_dict.get('ghop_task_key')

  if not key_name:
    # invalid task data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid updateGHOPTask data: %s' % post_dict)

  entity = ghop_task_logic.logic.getFromKeyNameOr404(key_name)

  entity, comment_entity = ghop_task_logic.logic.updateTaskStatus(entity)

  if entity:
    # TODO(madhusudan): does this really mean an unsuccessful update?
    # return OK
    return http.HttpResponse()

def spawnCreateNotificationMail(entity):
  """Spawns a task to send mail to the user who has subscribed to the specific
  task.

  Args:
    entity: The Comment entity for which mails must be sent
  """

  task_params = {
      'comment_key': entity.key().id_or_name(),
      'task_key': entity.parent_key().id_or_name(),
      }
  task_url = '/tasks/ghop/task/mail/create'

  new_task = taskqueue.Task(params=task_params, url=task_url)
  new_task.add('mail')

def createNotificationMail(request, *args, **kwargs):
  """Appengine task that sends mail to the subscribed users.

  Expects the following to be present in the POST dict:
    comment_key: Specifies the comment id for which to send the notifications
    task_key: Specifies the task key name for which the comment belongs to

  Args:
    request: Django Request object
  """

  from soc.modules.ghop.logic.helper import notifications as ghop_notifications

  from soc.modules.ghop.logic.models import comment as ghop_comment_logic
  from soc.modules.ghop.logic.models import task_subscription as \
      ghop_task_subscription_logic

  # set default batch size
  batch_size = 10

  post_dict = request.POST

  comment_key = post_dict.get('comment_key')
  task_key = post_dict.get('task_key')

  if not (comment_key and task_key):
    # invalid task data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid createNotificationMail data: %s' % post_dict)

  comment_key = long(comment_key)

  # get the task entity under which the specified comment was made
  task_entity = ghop_task_logic.logic.getFromKeyName(task_key)

  # get the comment for the given id
  comment_entity = ghop_comment_logic.logic.getFromID(
      comment_key, task_entity)

  if not comment_entity:
    # invalid comment specified, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid comment specified: %s/%s' % (comment_key, task_key))

  # check and retrieve the subscriber_start_key that has been done last
  if 'subscriber_start_index' in post_dict:
    subscriber_start_index = post_dict['subscriber_start_index']
  else:
    subscriber_start_index = 0

  # get all subscribers to GHOP task
  fields = {
      'task': task_entity,
      }

  ts_entity = ghop_task_subscription_logic.logic.getForFields(
      fields, unique=True)

  subscribers = db.get(ts_entity.subscribers[
      subscriber_start_index:subscriber_start_index+batch_size])

  task_url = "http://%(host)s%(task)s" % {
                 'host': system.getHostname(),
                 'task': redirects.getPublicRedirect(
                     task_entity, {'url_name': 'ghop/task'}),
                 }

  # create the data for the mail to be sent
  message_properties = {
      'task_url': task_url,
      'redirect_url': "%(task_url)s#c%(cid)d" % {
          'task_url': task_url,
          'cid': comment_entity.key().id_or_name()
          },
      'comment_entity': comment_entity,
      'task_entity': task_entity,
  }

  subject = DEF_TASK_UPDATE_SUBJECT_FMT % {
      'title': task_entity.title,
      }

  for subscriber in subscribers:
    ghop_notifications.sendTaskUpdate(entity, subject, message_properties)

  if len(subscribers) == batch_size:
    # spawn task for sending out notifications to next set of subscribers
    next_start = subscriber_start_index + batch_size

    task_params = {
        'comment_key': comment_key,
        'task_key': task_key,
        'subscriber_start_index': next_start
        }
    task_url = '/tasks/ghop/task/mail/create'

    new_task = taskqueue.Task(params=task_params, url=task_url)
    new_task.add('mail')

  # return OK
  return http.HttpResponse()

def updateTasksPostStudentSignUp(request, *args, **kwargs):
  """Appengine task that updates the GHOP Tasks after the student signs up.

  Expects the following to be present in the POST dict:
    student_key: Specifies the student key name who registered

  Args:
    request: Django Request object
  """
  from soc.modules.ghop.logic.models import student as ghop_student_logic

  post_dict = request.POST

  student_key = post_dict.get('student_key')

  if not student_key:
    # invalid student data, log and return OK
    return error_handler.logErrorAndReturnOK(
        'Invalid Student data: %s' % post_dict)

  student_entity = ghop_student_logic.logic.getFromKeyNameOr404(student_key)

  # retrieve all tasks currently assigned to the user
  task_fields = {
      'user': student_entity.user,
      }
  task_entities = ghop_task_logic.logic.getForFields(task_fields)

  # TODO(madhusudan) move this to the Task Logic
  # Make sure the tasks store references to the student as well as
  # closing all tasks that are AwaitingRegistration.
  for task_entity in task_entities:
    task_entity.student = student_entity
    if task_entity.status == 'AwaitingRegistration':
      task_entities.remove(task_entity)

      properties = {'status': 'Closed'}
      changes = [ugettext('User-MelangeAutomatic'),
                 ugettext('Action-Student registered'),
                 ugettext('Status-%s' % (properties['status']))]

      comment_properties = {
          'parent': task_entity,
          'scope_path': task_entity.key().name(),
          'created_by': None,
          'changes': changes,
          'content': ugettext(
              '(The Melange Automated System has detected that the student '
              'has signed up for the program and hence has closed this task.'),
          }

      ghop_task_logic.logic.updateEntityPropertiesWithCWS(
          task_entity, properties, comment_properties)

  db.put(task_entities)

  # return OK
  return http.HttpResponse()
<|endoftext|>


<commit_before># this file provides generic api's for validation of various user inputs
import re
#domain '-' allowed but not double or more continuosly, '.' also allowed , both
# (-, .) not in the begining or end
domain_re = "^[0-9a-zA-Z]+((-[0-9a-zA-Z]+)*(\.[0-9a-zA-Z]+)*)*(\.[0-9a-zA-Z]+)+$"
domain_regex = None

MAX_EPOCH_TIME = 32535215999 # epoch time for 12/31/3000
MAX_DOMAIN_LEN = 512

def validateDomain(domain, field_name = None):
    global domain_regex
    global domain_re

    retval = True
    msg = ""

    if field_name is None or len(field_name) == 0:
        field_name = "hostname"

    if domain is None or len(domain) == 0:
        return True, str(field_name) + " is empty"

    if domain_regex is None:
        domain_regex = re.compile(domain_re)

    if domain_regex.match(domain) is None:
        retval = False
        msg = msg + str(field_name) + ": " + str(domain) + " is not valid !!. "
    if len(domain) > MAX_DOMAIN_LEN:
        retval = False
        msg = msg + str(field_name) + ": " + str(domain) + " length exceeds limit of " + str(MAX_DOMAIN_LEN) + ". "
    return retval, msg

def validateScale(scale = 2):
  if scale < 0 or scale > 4:
    return False, "Invalid value supplied for scale"
  return True, ""

def validateTime(time_val):
  if time_val < 0 or time_val > MAX_EPOCH_TIME:
    return False, "Invalid value supplied for time"
  return True, ""

def validateInput(hostname = "", scale = 2, time_from = 0, time_to = 0):

  msg = ""
  retval = True
  tmp_val, tmp_msg = validateDomain(hostname)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateScale(scale)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateTime(time_from)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateTime(time_to)
  if tmp_val is False or time_to < time_from:
    retval = False
    msg = msg + tmp_msg

  if time_from > time_to:
    retval = False
    msg = msg + "\ntime_from cannot be greater than time_to \n"

  return retval, msg

<commit_msg>fix scale<commit_after># this file provides generic api's for validation of various user inputs
import re
#domain '-' allowed but not double or more continuosly, '.' also allowed , both
# (-, .) not in the begining or end
domain_re = "^[0-9a-zA-Z]+((-[0-9a-zA-Z]+)*(\.[0-9a-zA-Z]+)*)*(\.[0-9a-zA-Z]+)+$"
domain_regex = None

MAX_EPOCH_TIME = 32535215999 # epoch time for 12/31/3000
MAX_DOMAIN_LEN = 512

def validateDomain(domain, field_name = None):
    global domain_regex
    global domain_re

    retval = True
    msg = ""

    if field_name is None or len(field_name) == 0:
        field_name = "hostname"

    if domain is None or len(domain) == 0:
        return True, str(field_name) + " is empty"

    if domain_regex is None:
        domain_regex = re.compile(domain_re)

    if domain_regex.match(domain) is None:
        retval = False
        msg = msg + str(field_name) + ": " + str(domain) + " is not valid !!. "
    if len(domain) > MAX_DOMAIN_LEN:
        retval = False
        msg = msg + str(field_name) + ": " + str(domain) + " length exceeds limit of " + str(MAX_DOMAIN_LEN) + ". "
    return retval, msg

def validateScale(scale = 2):
  if scale < 0 or scale > 6:
    return False, "Invalid value supplied for scale"
  return True, ""

def validateTime(time_val):
  if time_val < 0 or time_val > MAX_EPOCH_TIME:
    return False, "Invalid value supplied for time"
  return True, ""

def validateInput(hostname = "", scale = 2, time_from = 0, time_to = 0):

  msg = ""
  retval = True
  tmp_val, tmp_msg = validateDomain(hostname)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateScale(scale)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateTime(time_from)
  if tmp_val is False:
    retval = False
    msg = msg + tmp_msg

  tmp_val, tmp_msg = validateTime(time_to)
  if tmp_val is False or time_to < time_from:
    retval = False
    msg = msg + tmp_msg

  if time_from > time_to:
    retval = False
    msg = msg + "\ntime_from cannot be greater than time_to \n"

  return retval, msg

<|endoftext|>


<commit_before>from PyQt5.QtWidgets import (
    QDialog, QLabel, QDialogButtonBox, QVBoxLayout, QLineEdit)

import grpc
import queue
import time
import threading
from thegame.gui import GuiClient
from thegame import thegame_pb2, thegame_pb2_grpc

class SpectatorClient(GuiClient):

    def _action(self, **kwds):
        if self.options.smooth:
            self.frames.put(kwds)
        else:
            super()._action(**kwds)

    def _consumer(self):
        fps = 40

        qsize0 = self.frames.qsize()
        while True:
            kwds = self.frames.get()
            super()._action(**kwds)
            time.sleep(1 / fps)
            qsize1 = self.frames.qsize()
            fps *= 0.999 + (qsize1 - qsize0 + 1) * 0.001
            print('est. fps:', fps, 'stored:', qsize1)
            qsize0 = qsize1

    def init(self):
        self.to_level_up = []

    @staticmethod
    def get_token():
        dialog = QDialog()
        layout = QVBoxLayout()
        layout.addWidget(QLabel('Enter server token:'))
        line = QLineEdit()
        layout.addWidget(line)
        box = QDialogButtonBox()
        button = box.addButton('OK', QDialogButtonBox.AcceptRole)
        button.clicked.connect(dialog.accept)
        layout.addWidget(box)
        dialog.setLayout(layout)
        dialog.exec()
        return line.text()

    @classmethod
    def _configure_parser(cls, parser):
        super()._configure_parser(parser)
        parser.add_argument('token')
        parser.add_argument('--smooth', action='store_true')

    def run(self):
        remote = self.options.remote
        token = self.options.token

        if self.options.smooth:
            self.frames = queue.Queue()
            self.play_thread = threading.Thread(target=self._consumer, daemon=True)
            self.play_thread.start()

        channel = grpc.insecure_channel(remote)
        stub = thegame_pb2_grpc.TheGameStub(channel)
        for response in stub.View(thegame_pb2.ViewRequest(token=token)):
            self._game_state = response
            self._response_to_controls(response)

if __name__ == '__main__':
    SpectatorClient.main()
<commit_msg>make spectator token a flag<commit_after>from PyQt5.QtWidgets import (
    QDialog, QLabel, QDialogButtonBox, QVBoxLayout, QLineEdit)

import grpc
import queue
import time
import threading
from thegame.gui import GuiClient
from thegame import thegame_pb2, thegame_pb2_grpc

class SpectatorClient(GuiClient):

    def _action(self, **kwds):
        if self.options.smooth:
            self.frames.put(kwds)
        else:
            super()._action(**kwds)

    def _consumer(self):
        fps = 40

        qsize0 = self.frames.qsize()
        while True:
            kwds = self.frames.get()
            super()._action(**kwds)
            time.sleep(1 / fps)
            qsize1 = self.frames.qsize()
            fps *= 0.999 + (qsize1 - qsize0 + 1) * 0.001
            print('est. fps:', fps, 'stored:', qsize1)
            qsize0 = qsize1

    def init(self):
        self.to_level_up = []

    @staticmethod
    def get_token():
        dialog = QDialog()
        layout = QVBoxLayout()
        layout.addWidget(QLabel('Enter server token:'))
        line = QLineEdit()
        layout.addWidget(line)
        box = QDialogButtonBox()
        button = box.addButton('OK', QDialogButtonBox.AcceptRole)
        button.clicked.connect(dialog.accept)
        layout.addWidget(box)
        dialog.setLayout(layout)
        dialog.exec()
        return line.text()

    @classmethod
    def _configure_parser(cls, parser):
        super()._configure_parser(parser)
        parser.add_argument('--token', default='')
        parser.add_argument('--smooth', action='store_true')

    def run(self):
        remote = self.options.remote
        token = self.options.token

        if self.options.smooth:
            self.frames = queue.Queue()
            self.play_thread = threading.Thread(target=self._consumer, daemon=True)
            self.play_thread.start()

        channel = grpc.insecure_channel(remote)
        stub = thegame_pb2_grpc.TheGameStub(channel)
        for response in stub.View(thegame_pb2.ViewRequest(token=token)):
            self._game_state = response
            self._response_to_controls(response)

if __name__ == '__main__':
    SpectatorClient.main()
<|endoftext|>


<commit_before>"""
.. _statsrefmanual:

==========================================
Statistical functions (:mod:`scipy.stats`)
==========================================

.. currentmodule:: scipy.stats

This module contains a large number of probability distributions as
well as a growing library of statistical functions.

Each univariate distribution is an instance of a subclass of `rv_continuous`
(`rv_discrete` for discrete distributions):

.. autosummary::
   :toctree: generated/

   rv_continuous
   rv_discrete
   rv_histogram

Continuous distributions
========================

.. autosummary::
   :toctree: generated/

   alpha             -- Alpha
   anglit            -- Anglit
   arcsine           -- Arcsine
   argus             -- Argus
   beta              -- Beta
   betaprime         -- Beta Prime
   bradford          -- Bradford
   burr              -- Burr (Type III)
   burr12            -- Burr (Type XII)
   cauchy            -- Cauchy
   chi               -- Chi
   chi2              -- Chi-squared
   cosine            -- Cosine
   crystalball       -- Crystalball
   dgamma            -- Double Gamma
   dweibull          -- Double Weibull
   erlang            -- Erlang
   expon             -- Exponential
   exponnorm         -- Exponentially Modified Normal
   exponweib         -- Exponentiated Weibull
   exponpow          -- Exponential Power
   f                 -- F (Snecdor F)
   fatiguelife       -- Fatigue Life (Birnbaum-Saunders)
   fisk              -- Fisk
   foldcauchy        -- Folded Cauchy
   foldnorm          -- Folded Normal
   genlogistic       -- Generalized Logistic
   gennorm           -- Generalized normal
   genpareto         -- Generalized Pareto
   genexpon          -- Generalized Exponential
   genextreme        -- Generalized Extreme Value
   gausshyper        -- Gauss Hypergeometric
   gamma             -- Gamma
   gengamma          -- Generalized gamma
   genhalflogistic   -- Generalized Half Logistic
   geninvgauss       -- Generalized Inverse Gaussian
   gilbrat           -- Gilbrat
   gompertz          -- Gompertz (Truncated Gumbel)
   gumbel_r          -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I
   gumbel_l          -- Left Sided Gumbel, etc.
   halfcauchy        -- Half Cauchy
   halflogistic      -- Half Logistic
   halfnorm          -- Half Normal
   halfgennorm       -- Generalized Half Normal
   hypsecant         -- Hyperbolic Secant
   invgamma          -- Inverse Gamma
   invgauss          -- Inverse Gaussian
   invweibull        -- Inverse Weibull
   johnsonsb         -- Johnson SB
   johnsonsu         -- Johnson SU
   kappa4            -- Kappa 4 parameter
   kappa3            -- Kappa 3 parameter
   ksone             -- Distribution of Kolmogorov-Smirnov one-sided test statistic
   kstwo             -- Distribution of Kolmogorov-Smirnov two-sided test statistic
   kstwobign         -- Limiting Distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
   laplace           -- Laplace
   laplace_asymmetric    -- Asymmetric Laplace
   levy              -- Levy
   levy_l
   levy_stable
   logistic          -- Logistic
   loggamma          -- Log-Gamma
   loglaplace        -- Log-Laplace (Log Double Exponential)
   lognorm           -- Log-Normal
   loguniform        -- Log-Uniform
   lomax             -- Lomax (Pareto of the second kind)
   maxwell           -- Maxwell
   mielke            -- Mielke's Beta-Kappa
   moyal             -- Moyal
   nakagami          -- Nakagami
   ncx2              -- Non-central chi-squared
   ncf               -- Non-central F
   nct               -- Non-central Student's T
   norm              -- Normal (Gaussian)
   norminvgauss      -- Normal Inverse Gaussian
   pareto            -- Pareto
   pearson3          -- Pearson type III
   powerlaw          -- Power-function
   powerlognorm      -- Power log normal
   powernorm         -- Power normal
   rdist             -- R-distribution
   rayleigh          -- Rayleigh
   rice              -- Rice
   recipinvgauss     -- Reciprocal Inverse Gaussian
   semicircular      -- Semicircular
   skewnorm          -- Skew normal
   t                 -- Student's T
   trapezoid         -- Trapezoidal
   triang            -- Triangular
   truncexpon        -- Truncated Exponential
   truncnorm         -- Truncated Normal
   tukeylambda       -- Tukey-Lambda
   uniform           -- Uniform
   vonmises          -- Von-Mises (Circular)
   vonmises_line     -- Von-Mises (Line)
   wald              -- Wald
   weibull_min       -- Minimum Weibull (see Frechet)
   weibull_max       -- Maximum Weibull (see Frechet)
   wrapcauchy        -- Wrapped Cauchy

Multivariate distributions
==========================

.. autosummary::
   :toctree: generated/

   multivariate_normal    -- Multivariate normal distribution
   matrix_normal          -- Matrix normal distribution
   dirichlet              -- Dirichlet
   wishart                -- Wishart
   invwishart             -- Inverse Wishart
   multinomial            -- Multinomial distribution
   special_ortho_group    -- SO(N) group
   ortho_group            -- O(N) group
   unitary_group          -- U(N) group
   random_correlation     -- random correlation matrices
   multivariate_t         -- Multivariate t-distribution
   multivariate_hypergeom -- Multivariate hypergeometric distribution

Discrete distributions
======================

.. autosummary::
   :toctree: generated/

   bernoulli         -- Bernoulli
   betabinom         -- Beta-Binomial
   binom             -- Binomial
   boltzmann         -- Boltzmann (Truncated Discrete Exponential)
   dlaplace          -- Discrete Laplacian
   geom              -- Geometric
   hypergeom         -- Hypergeometric
   logser            -- Logarithmic (Log-Series, Series)
   nbinom            -- Negative Binomial
   nhypergeom        -- Negative Hypergeometric
   planck            -- Planck (Discrete Exponential)
   poisson           -- Poisson
   randint           -- Discrete Uniform
   skellam           -- Skellam
   zipf              -- Zipf
   yulesimon         -- Yule-Simon

An overview of statistical functions is given below.
Several of these functions have a similar version in
`scipy.stats.mstats` which work for masked arrays.

Summary statistics
==================

.. autosummary::
   :toctree: generated/

   describe          -- Descriptive statistics
   gmean             -- Geometric mean
   hmean             -- Harmonic mean
   kurtosis          -- Fisher or Pearson kurtosis
   mode              -- Modal value
   moment            -- Central moment
   skew              -- Skewness
   kstat             --
   kstatvar          --
   tmean             -- Truncated arithmetic mean
   tvar              -- Truncated variance
   tmin              --
   tmax              --
   tstd              --
   tsem              --
   variation         -- Coefficient of variation
   find_repeats
   trim_mean
   gstd              -- Geometric Standard Deviation
   iqr
   sem
   bayes_mvs
   mvsdist
   entropy
   median_absolute_deviation
   median_abs_deviation

Frequency statistics
====================

.. autosummary::
   :toctree: generated/

   cumfreq
   itemfreq
   percentileofscore
   scoreatpercentile
   relfreq

.. autosummary::
   :toctree: generated/

   binned_statistic     -- Compute a binned statistic for a set of data.
   binned_statistic_2d  -- Compute a 2-D binned statistic for a set of data.
   binned_statistic_dd  -- Compute a d-D binned statistic for a set of data.

Correlation functions
=====================

.. autosummary::
   :toctree: generated/

   f_oneway
   pearsonr
   spearmanr
   pointbiserialr
   kendalltau
   weightedtau
   linregress
   siegelslopes
   theilslopes
   multiscale_graphcorr

Statistical tests
=================

.. autosummary::
   :toctree: generated/

   ttest_1samp
   ttest_ind
   ttest_ind_from_stats
   ttest_rel
   chisquare
   cramervonmises
   power_divergence
   kstest
   ks_1samp
   ks_2samp
   epps_singleton_2samp
   mannwhitneyu
   tiecorrect
   rankdata
   ranksums
   wilcoxon
   kruskal
   friedmanchisquare
   brunnermunzel
   combine_pvalues
   jarque_bera

.. autosummary::
   :toctree: generated/

   ansari
   bartlett
   levene
   shapiro
   anderson
   anderson_ksamp
   binom_test
   fligner
   median_test
   mood
   skewtest
   kurtosistest
   normaltest

Transformations
===============

.. autosummary::
   :toctree: generated/

   boxcox
   boxcox_normmax
   boxcox_llf
   yeojohnson
   yeojohnson_normmax
   yeojohnson_llf
   obrientransform
   sigmaclip
   trimboth
   trim1
   zmap
   zscore

Statistical distances
=====================

.. autosummary::
   :toctree: generated/

   wasserstein_distance
   energy_distance

Random variate generation
=========================

.. autosummary::
   :toctree: generated/

   rvs_ratio_uniforms

Circular statistical functions
==============================

.. autosummary::
   :toctree: generated/

   circmean
   circvar
   circstd

Contingency table functions
===========================

.. autosummary::
   :toctree: generated/

   chi2_contingency
   contingency.crosstab
   contingency.expected_freq
   contingency.margins
   fisher_exact

Plot-tests
==========

.. autosummary::
   :toctree: generated/

   ppcc_max
   ppcc_plot
   probplot
   boxcox_normplot
   yeojohnson_normplot

Masked statistics functions
===========================

.. toctree::

   stats.mstats

Univariate and multivariate kernel density estimation
=====================================================

.. autosummary::
   :toctree: generated/

   gaussian_kde

Quasi-Monte Carlo
=================

.. autosummary::
   :toctree: generated/

   qmc.QMCEngine
   qmc.Sobol
   qmc.Halton
   qmc.OrthogonalLatinHypercube
   qmc.LatinHypercube
   qmc.OptimalDesign
   qmc.NormalQMC
   qmc.MultivariateNormalQMC
   qmc.discrepancy
   qmc.scale
   qmc.multinomial_qmc

Warnings used in :mod:`scipy.stats`
===================================

.. autosummary::
   :toctree: generated/

   F_onewayConstantInputWarning
   F_onewayBadInputSizesWarning
   PearsonRConstantInputWarning
   PearsonRNearConstantInputWarning
   SpearmanRConstantInputWarning

For many more stat related functions install the software R and the
interface package rpy.

"""
from .stats import *
from .distributions import *
from .morestats import *
from ._binned_statistic import *
from .kde import gaussian_kde
from . import mstats
from .contingency import chi2_contingency
from ._multivariate import *

__all__ = [s for s in dir() if not s.startswith("_")]  # Remove dunders.

from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
<commit_msg>DOC: move QMC toctree<commit_after>"""
.. _statsrefmanual:

==========================================
Statistical functions (:mod:`scipy.stats`)
==========================================

.. currentmodule:: scipy.stats

This module contains a large number of probability distributions as
well as a growing library of statistical functions.

Each univariate distribution is an instance of a subclass of `rv_continuous`
(`rv_discrete` for discrete distributions):

.. autosummary::
   :toctree: generated/

   rv_continuous
   rv_discrete
   rv_histogram

Continuous distributions
========================

.. autosummary::
   :toctree: generated/

   alpha             -- Alpha
   anglit            -- Anglit
   arcsine           -- Arcsine
   argus             -- Argus
   beta              -- Beta
   betaprime         -- Beta Prime
   bradford          -- Bradford
   burr              -- Burr (Type III)
   burr12            -- Burr (Type XII)
   cauchy            -- Cauchy
   chi               -- Chi
   chi2              -- Chi-squared
   cosine            -- Cosine
   crystalball       -- Crystalball
   dgamma            -- Double Gamma
   dweibull          -- Double Weibull
   erlang            -- Erlang
   expon             -- Exponential
   exponnorm         -- Exponentially Modified Normal
   exponweib         -- Exponentiated Weibull
   exponpow          -- Exponential Power
   f                 -- F (Snecdor F)
   fatiguelife       -- Fatigue Life (Birnbaum-Saunders)
   fisk              -- Fisk
   foldcauchy        -- Folded Cauchy
   foldnorm          -- Folded Normal
   genlogistic       -- Generalized Logistic
   gennorm           -- Generalized normal
   genpareto         -- Generalized Pareto
   genexpon          -- Generalized Exponential
   genextreme        -- Generalized Extreme Value
   gausshyper        -- Gauss Hypergeometric
   gamma             -- Gamma
   gengamma          -- Generalized gamma
   genhalflogistic   -- Generalized Half Logistic
   geninvgauss       -- Generalized Inverse Gaussian
   gilbrat           -- Gilbrat
   gompertz          -- Gompertz (Truncated Gumbel)
   gumbel_r          -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I
   gumbel_l          -- Left Sided Gumbel, etc.
   halfcauchy        -- Half Cauchy
   halflogistic      -- Half Logistic
   halfnorm          -- Half Normal
   halfgennorm       -- Generalized Half Normal
   hypsecant         -- Hyperbolic Secant
   invgamma          -- Inverse Gamma
   invgauss          -- Inverse Gaussian
   invweibull        -- Inverse Weibull
   johnsonsb         -- Johnson SB
   johnsonsu         -- Johnson SU
   kappa4            -- Kappa 4 parameter
   kappa3            -- Kappa 3 parameter
   ksone             -- Distribution of Kolmogorov-Smirnov one-sided test statistic
   kstwo             -- Distribution of Kolmogorov-Smirnov two-sided test statistic
   kstwobign         -- Limiting Distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
   laplace           -- Laplace
   laplace_asymmetric    -- Asymmetric Laplace
   levy              -- Levy
   levy_l
   levy_stable
   logistic          -- Logistic
   loggamma          -- Log-Gamma
   loglaplace        -- Log-Laplace (Log Double Exponential)
   lognorm           -- Log-Normal
   loguniform        -- Log-Uniform
   lomax             -- Lomax (Pareto of the second kind)
   maxwell           -- Maxwell
   mielke            -- Mielke's Beta-Kappa
   moyal             -- Moyal
   nakagami          -- Nakagami
   ncx2              -- Non-central chi-squared
   ncf               -- Non-central F
   nct               -- Non-central Student's T
   norm              -- Normal (Gaussian)
   norminvgauss      -- Normal Inverse Gaussian
   pareto            -- Pareto
   pearson3          -- Pearson type III
   powerlaw          -- Power-function
   powerlognorm      -- Power log normal
   powernorm         -- Power normal
   rdist             -- R-distribution
   rayleigh          -- Rayleigh
   rice              -- Rice
   recipinvgauss     -- Reciprocal Inverse Gaussian
   semicircular      -- Semicircular
   skewnorm          -- Skew normal
   t                 -- Student's T
   trapezoid         -- Trapezoidal
   triang            -- Triangular
   truncexpon        -- Truncated Exponential
   truncnorm         -- Truncated Normal
   tukeylambda       -- Tukey-Lambda
   uniform           -- Uniform
   vonmises          -- Von-Mises (Circular)
   vonmises_line     -- Von-Mises (Line)
   wald              -- Wald
   weibull_min       -- Minimum Weibull (see Frechet)
   weibull_max       -- Maximum Weibull (see Frechet)
   wrapcauchy        -- Wrapped Cauchy

Multivariate distributions
==========================

.. autosummary::
   :toctree: generated/

   multivariate_normal    -- Multivariate normal distribution
   matrix_normal          -- Matrix normal distribution
   dirichlet              -- Dirichlet
   wishart                -- Wishart
   invwishart             -- Inverse Wishart
   multinomial            -- Multinomial distribution
   special_ortho_group    -- SO(N) group
   ortho_group            -- O(N) group
   unitary_group          -- U(N) group
   random_correlation     -- random correlation matrices
   multivariate_t         -- Multivariate t-distribution
   multivariate_hypergeom -- Multivariate hypergeometric distribution

Discrete distributions
======================

.. autosummary::
   :toctree: generated/

   bernoulli         -- Bernoulli
   betabinom         -- Beta-Binomial
   binom             -- Binomial
   boltzmann         -- Boltzmann (Truncated Discrete Exponential)
   dlaplace          -- Discrete Laplacian
   geom              -- Geometric
   hypergeom         -- Hypergeometric
   logser            -- Logarithmic (Log-Series, Series)
   nbinom            -- Negative Binomial
   nhypergeom        -- Negative Hypergeometric
   planck            -- Planck (Discrete Exponential)
   poisson           -- Poisson
   randint           -- Discrete Uniform
   skellam           -- Skellam
   zipf              -- Zipf
   yulesimon         -- Yule-Simon

An overview of statistical functions is given below.
Several of these functions have a similar version in
`scipy.stats.mstats` which work for masked arrays.

Summary statistics
==================

.. autosummary::
   :toctree: generated/

   describe          -- Descriptive statistics
   gmean             -- Geometric mean
   hmean             -- Harmonic mean
   kurtosis          -- Fisher or Pearson kurtosis
   mode              -- Modal value
   moment            -- Central moment
   skew              -- Skewness
   kstat             --
   kstatvar          --
   tmean             -- Truncated arithmetic mean
   tvar              -- Truncated variance
   tmin              --
   tmax              --
   tstd              --
   tsem              --
   variation         -- Coefficient of variation
   find_repeats
   trim_mean
   gstd              -- Geometric Standard Deviation
   iqr
   sem
   bayes_mvs
   mvsdist
   entropy
   median_absolute_deviation
   median_abs_deviation

Frequency statistics
====================

.. autosummary::
   :toctree: generated/

   cumfreq
   itemfreq
   percentileofscore
   scoreatpercentile
   relfreq

.. autosummary::
   :toctree: generated/

   binned_statistic     -- Compute a binned statistic for a set of data.
   binned_statistic_2d  -- Compute a 2-D binned statistic for a set of data.
   binned_statistic_dd  -- Compute a d-D binned statistic for a set of data.

Correlation functions
=====================

.. autosummary::
   :toctree: generated/

   f_oneway
   pearsonr
   spearmanr
   pointbiserialr
   kendalltau
   weightedtau
   linregress
   siegelslopes
   theilslopes
   multiscale_graphcorr

Statistical tests
=================

.. autosummary::
   :toctree: generated/

   ttest_1samp
   ttest_ind
   ttest_ind_from_stats
   ttest_rel
   chisquare
   cramervonmises
   power_divergence
   kstest
   ks_1samp
   ks_2samp
   epps_singleton_2samp
   mannwhitneyu
   tiecorrect
   rankdata
   ranksums
   wilcoxon
   kruskal
   friedmanchisquare
   brunnermunzel
   combine_pvalues
   jarque_bera

.. autosummary::
   :toctree: generated/

   ansari
   bartlett
   levene
   shapiro
   anderson
   anderson_ksamp
   binom_test
   fligner
   median_test
   mood
   skewtest
   kurtosistest
   normaltest

Transformations
===============

.. autosummary::
   :toctree: generated/

   boxcox
   boxcox_normmax
   boxcox_llf
   yeojohnson
   yeojohnson_normmax
   yeojohnson_llf
   obrientransform
   sigmaclip
   trimboth
   trim1
   zmap
   zscore

Statistical distances
=====================

.. autosummary::
   :toctree: generated/

   wasserstein_distance
   energy_distance

Random variate generation
=========================

.. autosummary::
   :toctree: generated/

   rvs_ratio_uniforms

Circular statistical functions
==============================

.. autosummary::
   :toctree: generated/

   circmean
   circvar
   circstd

Contingency table functions
===========================

.. autosummary::
   :toctree: generated/

   chi2_contingency
   contingency.crosstab
   contingency.expected_freq
   contingency.margins
   fisher_exact

Plot-tests
==========

.. autosummary::
   :toctree: generated/

   ppcc_max
   ppcc_plot
   probplot
   boxcox_normplot
   yeojohnson_normplot

Masked statistics functions
===========================

.. toctree::

   stats.mstats

Univariate and multivariate kernel density estimation
=====================================================

.. autosummary::
   :toctree: generated/

   gaussian_kde

Quasi-Monte Carlo
=================

.. autosummary::
   :toctree: generated/

   qmc

Warnings used in :mod:`scipy.stats`
===================================

.. autosummary::
   :toctree: generated/

   F_onewayConstantInputWarning
   F_onewayBadInputSizesWarning
   PearsonRConstantInputWarning
   PearsonRNearConstantInputWarning
   SpearmanRConstantInputWarning

For many more stat related functions install the software R and the
interface package rpy.

"""
from .stats import *
from .distributions import *
from .morestats import *
from ._binned_statistic import *
from .kde import gaussian_kde
from . import mstats
from .contingency import chi2_contingency
from ._multivariate import *

__all__ = [s for s in dir() if not s.startswith("_")]  # Remove dunders.

from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
<|endoftext|>


<commit_before>__author__ = 'Xsank'
import thread
from multiprocessing.pool import ThreadPool
from threading import Condition

from event import Event
from listener import Listener
from util import Singleton
from exception import EventTypeError
from exception import ListenerTypeError
from exception import UnregisterError
from exception import ProcessException

def check_type(valid_type,exception):
    def decorator(func):
        def _decorator(obj,_type):
            if isinstance(_type,valid_type):
                func(obj,_type)
            else:
                raise exception
        return _decorator
    return decorator

class EventBus(object):
    __metaclass__=Singleton

    def __init__(self,pool_size=4):
        super(EventBus,self).__init__()
        self.pool=ThreadPool(pool_size)
        self.async_events=list()
        self.event_handlers=dict()
        self.con=Condition()
        self.init()

    def init(self):
        thread.start_new_thread(self.loop,())

    @check_type(Listener,ListenerTypeError)
    def register(self,listener):
        self.event_handlers.update(listener.event_handlers)

    @check_type(Listener,ListenerTypeError)
    def unregister(self,listener):
        try:
            for event in listener.event_handlers:
                del self.event_handlers[event]
        except Exception:
            raise UnregisterError

    def process(self,event):
        handlers=self.event_handlers[event.id()]
        if not handlers:
            raise ProcessException

        for handler in handlers:
            handler(event)

    @check_type(Event,EventTypeError)
    def post(self,event):
        self.process(event)

    @check_type(Event,EventTypeError)
    def async_post(self,event):
        self.con.acquire()
        self.async_events.append(event)
        self.con.notifyAll()
        self.con.release()

    def loop(self):
        while True:
            self.con.acquire()
            while not self.async_events:
                self.con.wait()
            self.pool.map(self.process,self.async_events)
            self.async_events=list()
            self.con.release()

    def destroy(self):
        self.event_handlers.clear()
        self.pool.close()<commit_msg>add event and listener type check decorator<commit_after>__author__ = 'Xsank'
import thread
from multiprocessing.pool import ThreadPool
from threading import Condition

from event import Event
from listener import Listener
from util import Singleton
from exception import EventTypeError
from exception import ListenerTypeError
from exception import UnregisterError
from exception import ProcessException

def check_type(valid_type,exception):
    def decorator(func):
        def _decorator(obj,_type):
            if isinstance(_type,valid_type):
                func(obj,_type)
            else:
                raise exception
        return _decorator
    return decorator

check_event=check_type(Event,EventTypeError)
check_listener=check_type(Listener,ListenerTypeError)

class EventBus(object):
    __metaclass__=Singleton

    def __init__(self,pool_size=4):
        super(EventBus,self).__init__()
        self.pool=ThreadPool(pool_size)
        self.async_events=list()
        self.event_handlers=dict()
        self.con=Condition()
        self.init()

    def init(self):
        thread.start_new_thread(self.loop,())

    @check_listener
    def register(self,listener):
        self.event_handlers.update(listener.event_handlers)

    @check_listener
    def unregister(self,listener):
        try:
            for event in listener.event_handlers:
                del self.event_handlers[event]
        except Exception:
            raise UnregisterError

    def process(self,event):
        handlers=self.event_handlers[event.id()]
        if not handlers:
            raise ProcessException

        for handler in handlers:
            handler(event)

    @check_event
    def post(self,event):
        self.process(event)

    @check_event
    def async_post(self,event):
        self.con.acquire()
        self.async_events.append(event)
        self.con.notifyAll()
        self.con.release()

    def loop(self):
        while True:
            self.con.acquire()
            while not self.async_events:
                self.con.wait()
            self.pool.map(self.process,self.async_events)
            self.async_events=list()
            self.con.release()

    def destroy(self):
        self.event_handlers.clear()
        self.pool.close()<|endoftext|>


<commit_before>#!/usr/bin/env python
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/lbpcascades/lbpcascade_frontalface.xml')
def draw(coor,img) :
    for (x,y,w,h) in coor:
        #mg = crypto(img,y,w)
        cv2.rectangle(img,(x,y),(x+w,y+h),(100,10,100),2)
        roi_color = img[y:y+h, x:x+w]

def main() :
    while(True):
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 3)
        print(faces)
        draw(faces,frame)
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

if __name__=='__main__' :
    main()
<commit_msg>Delete simple.py<commit_after><|endoftext|>


<commit_before>"""
A consent module for the satosa proxy
"""
import hashlib
import json
from jwkest.jws import JWS
import requests
from requests.exceptions import ConnectionError
from base64 import urlsafe_b64encode
from satosa.internal_data import InternalResponse, AuthenticationInformation, UserIdHashType
from satosa.response import Redirect
from satosa.state import state_to_cookie, cookie_to_state
from jwkest.jwk import rsa_load
from jwkest.jwk import RSAKey

__author__ = 'mathiashedstrom'

class ConsentModule(object):
    """
    Module for handling consent. Uses an external consent service
    """

    STATE_KEY = "CONSENT"

    def __init__(self, config, callback_func):
        self.callback_func = callback_func
        self.enabled = "CONSENT" in config and ("enable" not in config.CONSENT or config.CONSENT["enable"])
        if self.enabled:
            self.proxy_base = config.BASE
            self.state_enc_key = config.CONSENT["state_enc_key"]
            self.consent_uri = config.CONSENT["service.rest_uri"]
            self.consent_redirect_url = config.CONSENT["service.consent_redirect"]
            self.endpoint = config.CONSENT["endpoint"]
            self.verify_ssl = config.CONSENT["verify_ssl"]

            _bkey = rsa_load(config.CONSENT["sign_key"])
            self.sign_key = RSAKey().load_key(_bkey)
            self.sign_key.use = "sig"

    def save_state(self, internal_request, state):
        """
        Save stuff needed by the consent module when getting an internal response

        :type internal_request: satosa.internal_data.InternalRequest
        :type state: satosa.state.State
        :rtype: None

        :param internal_request: The current request
        :param state: the current state
        :return: None
        """
        if self.enabled:
            state.add(ConsentModule.STATE_KEY, {"fr": internal_request._attribute_filter,
                                                "reqor": internal_request.requestor})

    def _handle_consent_response(self, context):
        """
        Endpoint for handling consent service response
        :type context: satosa.context.Context
        :rtype context: Any

        :param context: response context
        :return: response
        """
        # Handle answer from consent service
        # load state
        # TODO What if no cookie?
        state = cookie_to_state(context.cookie, "consent_state", self.state_enc_key)

        consent_state = state.get(ConsentModule.STATE_KEY)
        saved_resp = consent_state["internal_resp"]

        # rebuild internal_response from state
        auth_info = AuthenticationInformation(saved_resp["auth_info"]["auth_class_ref"],
                                              saved_resp["auth_info"]["timestamp"],
                                              saved_resp["auth_info"]["issuer"])
        internal_response = InternalResponse(getattr(UserIdHashType, saved_resp["hash_type"]),
                                             auth_info=auth_info)
        internal_response._attributes = saved_resp["attr"]
        internal_response.user_id = saved_resp["usr_id"]

        requestor = consent_state["reqor"]

        hash_id = self._get_consent_id(requestor, internal_response.user_id, list(internal_response._attributes.keys()))

        try:
            consent_given = self._verify_consent(hash_id)
        except ConnectionError as error:
            # TODO LOG
            # Send an internal_response without any attributes
            consent_given = False

        if not consent_given:
            # If consent was not given, then don't send any attributes
            internal_response._attributes = {}

        return self.callback_func(context, internal_response, state)

    def manage_consent(self, context, internal_response, state):
        """
        Manage consent and attribute filtering

        :type context: satosa.context.Context
        :type internal_response: satosa.internal_data.InternalResponse
        :type state: satosa.state.State
        :rtype: Any

        :param context: response context
        :param internal_response: the response
        :param state: the current state
        :return: response
        """

        if not self.enabled:
            return self.callback_func(context, internal_response, state)

        consent_state = state.get(ConsentModule.STATE_KEY)
        filter = consent_state["fr"]
        requestor = consent_state["reqor"]

        # filter attributes
        filtered_data = {}
        for attr in filter:
            if attr in internal_response._attributes:
                data = internal_response._attributes[attr]
                if not isinstance(data, list):
                    data = [data]
                filtered_data[attr] = data
        # Update intenal response
        internal_response._attributes = filtered_data

        id_hash = self._get_consent_id(requestor, internal_response.user_id, list(filtered_data.keys()))

        try:
            # Check if consent is already given
            if self._verify_consent(id_hash):
                return self.callback_func(context, internal_response, state)
        except ConnectionError as error:
            # TODO LOG
            # Send an internal_response without any attributes
            internal_response._attributes = {}
            return self.callback_func(context, internal_response, state)

        consent_state["internal_resp"] = self._internal_resp_to_dict(internal_response)
        state.add(ConsentModule.STATE_KEY, consent_state)

        # Save state in cookie
        state_cookie = state_to_cookie(state, "consent_state", "/consent/%s" % self.endpoint, self.state_enc_key)

        consent_args = {"attr": filtered_data,
                        "id": id_hash,
                        "redirect_endpoint": "%s/consent/%s" % (self.proxy_base, self.endpoint)}
        consent_args_jws = self._to_jws(consent_args)

        try:
            ticket = self._consent_registration(consent_args_jws)
        except (ConnectionError, AssertionError) as error:
            # TODO LOG
            # Send an internal_response without any attributes
            internal_response._attributes = {}
            return self.callback_func(context, internal_response, state)

        consent_redirect = "%s?ticket=%s" % (self.consent_redirect_url, ticket)
        return Redirect(consent_redirect, state_cookie)

    def _get_consent_id(self, requestor, user_id, filtered_attr):
        """
        Get a hashed id based on requestor, user id and filtered attributes

        :type requestor: str
        :type user_id: str
        :type filtered_attr: list[str]

        :param requestor: The calling requestor
        :param user_id: The authorized user id
        :param filtered_attr: a list containing all attributes to be sent
        :return: an id
        """
        filtered_attr.sort()
        id_string = "%s%s%s" % (requestor, user_id, json.dumps(filtered_attr))
        return urlsafe_b64encode(hashlib.sha224(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8")

    def _consent_registration(self, jws):
        """
        Register a request at the consent service

        :type jws: str
        :type state: satosa.state.State
        :rtype: str

        :param jws: A jws containing id, redirect_endpoint and attr
        :param state: The current state
        :return: Ticket received from the consent service
        """
        try:
            request = "{}/creq/{}".format(self.consent_uri, jws)
            res = requests.get(request, verify=self.verify_ssl)
        except ConnectionError as con_exc:
            raise ConnectionError("Could not connect to consent service: {}".format(str(con_exc)))

        assert res.status_code == 200, "Consent service: {}".format(res.status_code)

        ticket = res.text
        return ticket

    def _verify_consent(self, id):
        """
        Connects to the consent service using the REST api and checks if the user has given consent

        :type id: str
        :type state: satosa.state.State
        :rtype: bool

        :param id: An id associated to the authenticated user, the calling requestor and attributes to be sent.
        :param state: The current state
        :return: True if given consent, else False
        """
        try:
            request = "{}/verify/{}".format(self.consent_uri, id)
            res = requests.get(request, verify=self.verify_ssl)
        except ConnectionError as con_exc:
            raise ConnectionError("Could not connect to consent service: {}".format(str(con_exc)))

        return res.status_code == 200

    def _internal_resp_to_dict(self, internal_response):
        """
        Converts an InternalResponse object to a dict

        :type internal_response: satosa.internal_data.InternalResponse

        :param internal_response: The incoming response
        :return: A dict representation of internal_response
        """
        # TODO move to InternalResponse?
        auth_info = internal_response.auth_info
        response_state = {"usr_id": internal_response.user_id,
                          "attr": internal_response._attributes,
                          "hash_type": internal_response.user_id_hash_type.name,
                          "auth_info": {"issuer": auth_info.issuer,
                                        "timestamp": auth_info.timestamp,
                                        "auth_class_ref": auth_info.auth_class_ref, }}
        return response_state

    def _to_jws(self, data):
        """
        Converts data to a jws

        :type data: Any
        :rtype: str

        :param data: Data to be converted to jws
        :return: a jws
        """
        algorithm = "RS256"
        _jws = JWS(json.dumps(data), alg=algorithm)
        return _jws.sign_compact([self.sign_key])

    def register_endpoints(self):
        """
        Register consent module endpoints

        :rtype: list[(srt, (satosa.context.Context) -> Any)]

        :return: A list of endpoints bound to a function
        """
        return [("^consent/%s?(.*)$" % self.endpoint, self._handle_consent_response)]
<commit_msg>REmoved the filter, since it do not work with oidc.<commit_after>"""
A consent module for the satosa proxy
"""
import hashlib
import json
from jwkest.jws import JWS
import requests
from requests.exceptions import ConnectionError
from base64 import urlsafe_b64encode
from satosa.internal_data import InternalResponse, AuthenticationInformation, UserIdHashType
from satosa.response import Redirect
from satosa.state import state_to_cookie, cookie_to_state
from jwkest.jwk import rsa_load
from jwkest.jwk import RSAKey

__author__ = 'mathiashedstrom'

class ConsentModule(object):
    """
    Module for handling consent. Uses an external consent service
    """

    STATE_KEY = "CONSENT"

    def __init__(self, config, callback_func):
        self.callback_func = callback_func
        self.enabled = "CONSENT" in config and ("enable" not in config.CONSENT or config.CONSENT["enable"])
        if self.enabled:
            self.proxy_base = config.BASE
            self.state_enc_key = config.CONSENT["state_enc_key"]
            self.consent_uri = config.CONSENT["service.rest_uri"]
            self.consent_redirect_url = config.CONSENT["service.consent_redirect"]
            self.endpoint = config.CONSENT["endpoint"]
            self.verify_ssl = config.CONSENT["verify_ssl"]

            _bkey = rsa_load(config.CONSENT["sign_key"])
            self.sign_key = RSAKey().load_key(_bkey)
            self.sign_key.use = "sig"

    def save_state(self, internal_request, state):
        """
        Save stuff needed by the consent module when getting an internal response

        :type internal_request: satosa.internal_data.InternalRequest
        :type state: satosa.state.State
        :rtype: None

        :param internal_request: The current request
        :param state: the current state
        :return: None
        """
        if self.enabled:
            state.add(ConsentModule.STATE_KEY, {"fr": internal_request._attribute_filter,
                                                "reqor": internal_request.requestor})

    def _handle_consent_response(self, context):
        """
        Endpoint for handling consent service response
        :type context: satosa.context.Context
        :rtype context: Any

        :param context: response context
        :return: response
        """
        # Handle answer from consent service
        # load state
        # TODO What if no cookie?
        state = cookie_to_state(context.cookie, "consent_state", self.state_enc_key)

        consent_state = state.get(ConsentModule.STATE_KEY)
        saved_resp = consent_state["internal_resp"]

        # rebuild internal_response from state
        auth_info = AuthenticationInformation(saved_resp["auth_info"]["auth_class_ref"],
                                              saved_resp["auth_info"]["timestamp"],
                                              saved_resp["auth_info"]["issuer"])
        internal_response = InternalResponse(getattr(UserIdHashType, saved_resp["hash_type"]),
                                             auth_info=auth_info)
        internal_response._attributes = saved_resp["attr"]
        internal_response.user_id = saved_resp["usr_id"]

        requestor = consent_state["reqor"]

        hash_id = self._get_consent_id(requestor, internal_response.user_id, list(internal_response._attributes.keys()))

        try:
            consent_given = self._verify_consent(hash_id)
        except ConnectionError as error:
            # TODO LOG
            # Send an internal_response without any attributes
            consent_given = False

        if not consent_given:
            # If consent was not given, then don't send any attributes
            internal_response._attributes = {}

        return self.callback_func(context, internal_response, state)

    def manage_consent(self, context, internal_response, state):
        """
        Manage consent and attribute filtering

        :type context: satosa.context.Context
        :type internal_response: satosa.internal_data.InternalResponse
        :type state: satosa.state.State
        :rtype: Any

        :param context: response context
        :param internal_response: the response
        :param state: the current state
        :return: response
        """

        if not self.enabled:
            return self.callback_func(context, internal_response, state)

        consent_state = state.get(ConsentModule.STATE_KEY)
        filter = consent_state["fr"]
        requestor = consent_state["reqor"]

        ##filter attributes
        #filtered_data = {}
        #for attr in filter:
        #    if attr in internal_response._attributes:
        #        data = internal_response._attributes[attr]
        #        if not isinstance(data, list):
        #            data = [data]
        #        filtered_data[attr] = data
        ##Update intenal response
        #internal_response._attributes = filtered_data
        filtered_data = internal_response._attributes

        id_hash = self._get_consent_id(requestor, internal_response.user_id, list(filtered_data.keys()))

        try:
            # Check if consent is already given
            if self._verify_consent(id_hash):
                return self.callback_func(context, internal_response, state)
        except ConnectionError as error:
            # TODO LOG
            # Send an internal_response without any attributes
            internal_response._attributes = {}
            return self.callback_func(context, internal_response, state)

        consent_state["internal_resp"] = self._internal_resp_to_dict(internal_response)
        state.add(ConsentModule.STATE_KEY, consent_state)

        # Save state in cookie
        state_cookie = state_to_cookie(state, "consent_state", "/consent/%s" % self.endpoint, self.state_enc_key)

        consent_args = {"attr": filtered_data,
                        "id": id_hash,
                        "redirect_endpoint": "%s/consent/%s" % (self.proxy_base, self.endpoint)}
        consent_args_jws = self._to_jws(consent_args)

        try:
            ticket = self._consent_registration(consent_args_jws)
        except (ConnectionError, AssertionError) as error:
            # TODO LOG
            # Send an internal_response without any attributes
            internal_response._attributes = {}
            return self.callback_func(context, internal_response, state)

        consent_redirect = "%s?ticket=%s" % (self.consent_redirect_url, ticket)
        return Redirect(consent_redirect, state_cookie)

    def _get_consent_id(self, requestor, user_id, filtered_attr):
        """
        Get a hashed id based on requestor, user id and filtered attributes

        :type requestor: str
        :type user_id: str
        :type filtered_attr: list[str]

        :param requestor: The calling requestor
        :param user_id: The authorized user id
        :param filtered_attr: a list containing all attributes to be sent
        :return: an id
        """
        filtered_attr.sort()
        id_string = "%s%s%s" % (requestor, user_id, json.dumps(filtered_attr))
        return urlsafe_b64encode(hashlib.sha224(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8")

    def _consent_registration(self, jws):
        """
        Register a request at the consent service

        :type jws: str
        :type state: satosa.state.State
        :rtype: str

        :param jws: A jws containing id, redirect_endpoint and attr
        :param state: The current state
        :return: Ticket received from the consent service
        """
        try:
            request = "{}/creq/{}".format(self.consent_uri, jws)
            res = requests.get(request, verify=self.verify_ssl)
        except ConnectionError as con_exc:
            raise ConnectionError("Could not connect to consent service: {}".format(str(con_exc)))

        assert res.status_code == 200, "Consent service: {}".format(res.status_code)

        ticket = res.text
        return ticket

    def _verify_consent(self, id):
        """
        Connects to the consent service using the REST api and checks if the user has given consent

        :type id: str
        :type state: satosa.state.State
        :rtype: bool

        :param id: An id associated to the authenticated user, the calling requestor and attributes to be sent.
        :param state: The current state
        :return: True if given consent, else False
        """
        try:
            request = "{}/verify/{}".format(self.consent_uri, id)
            res = requests.get(request, verify=self.verify_ssl)
        except ConnectionError as con_exc:
            raise ConnectionError("Could not connect to consent service: {}".format(str(con_exc)))

        return res.status_code == 200

    def _internal_resp_to_dict(self, internal_response):
        """
        Converts an InternalResponse object to a dict

        :type internal_response: satosa.internal_data.InternalResponse

        :param internal_response: The incoming response
        :return: A dict representation of internal_response
        """
        # TODO move to InternalResponse?
        auth_info = internal_response.auth_info
        response_state = {"usr_id": internal_response.user_id,
                          "attr": internal_response._attributes,
                          "hash_type": internal_response.user_id_hash_type.name,
                          "auth_info": {"issuer": auth_info.issuer,
                                        "timestamp": auth_info.timestamp,
                                        "auth_class_ref": auth_info.auth_class_ref, }}
        return response_state

    def _to_jws(self, data):
        """
        Converts data to a jws

        :type data: Any
        :rtype: str

        :param data: Data to be converted to jws
        :return: a jws
        """
        algorithm = "RS256"
        _jws = JWS(json.dumps(data), alg=algorithm)
        return _jws.sign_compact([self.sign_key])

    def register_endpoints(self):
        """
        Register consent module endpoints

        :rtype: list[(srt, (satosa.context.Context) -> Any)]

        :return: A list of endpoints bound to a function
        """
        return [("^consent/%s?(.*)$" % self.endpoint, self._handle_consent_response)]
<|endoftext|>


<commit_before>from django.contrib import messages
from django.views.generic.edit import FormView
from django_twilio.decorators import twilio_view
from twilio import twiml

from apostello.forms import SendAdhocRecipientsForm, SendRecipientGroupForm
from apostello.mixins import ProfilePermsMixin
from apostello.models import RecipientGroup
from apostello.reply import InboundSms
from site_config.models import SiteConfiguration

class SendView(ProfilePermsMixin, FormView):
    """Display send SMS form."""
    required_perms = []
    success_url = '/'

    def get_form(self, **kwargs):
        """Add user to form so we can check cost limits."""
        form = super(SendView, self).get_form(**kwargs)
        prepopulated_recipient = self.request.GET.get('recipient', None)
        if prepopulated_recipient is not None:
            form.initial['recipients'] = [prepopulated_recipient]
        form.user = self.request.user
        return form

    def get_context_data(self, **kwargs):
        """Inject not approved message into context."""
        context = super(SendView, self).get_context_data(**kwargs)
        context['js_path'] = self.template_name.replace('.html', '')
        return context

class SendAdhoc(SendView):
    """Display form for sending messages to individuals or ad-hoc groups."""
    form_class = SendAdhocRecipientsForm
    template_name = 'apostello/send_adhoc.html'
    success_url = '/send/adhoc/'

    def form_valid(self, form):
        """Send message and notify the user on valid form submission."""
        for recipient in form.cleaned_data['recipients']:
            # send and save message
            recipient.send_message(
                content=form.cleaned_data['content'],
                eta=form.cleaned_data['scheduled_time'],
                sent_by=str(self.request.user)
            )

        if form.cleaned_data['scheduled_time'] is None:
            messages.info(
                self.request, "Sending \"{0}\"...\n"
                "Please check the logs for verification...".format(
                    form.cleaned_data['content']
                )
            )
        else:
            messages.info(
                self.request, "'{0}' has been successfully queued.".format(
                    form.cleaned_data['content']
                )
            )

        return super(SendAdhoc, self).form_valid(form)

class SendGroup(SendView):
    """Display form for sending messages to a group."""
    form_class = SendRecipientGroupForm
    template_name = 'apostello/send_group.html'
    success_url = '/send/group/'

    def get_context_data(self, **kwargs):
        """Add the per group costs to context."""
        context = super(SendGroup, self).get_context_data(**kwargs)
        context['group_nums'] = [
            (x.id, x.recipient_set.all().count())
            for x in RecipientGroup.objects.all()
        ]
        return context

    def form_valid(self, form):
        """Send message and notify the user on valid form submission."""
        form.cleaned_data['recipient_group'].send_message(
            content=form.cleaned_data['content'],
            eta=form.cleaned_data['scheduled_time'],
            sent_by=str(self.request.user)
        )
        if form.cleaned_data['scheduled_time'] is None:
            messages.info(
                self.request, "Sending '{0}' to '{1}'...\n"
                "Please check the logs for verification...".format(
                    form.cleaned_data['content'],
                    form.cleaned_data['recipient_group']
                )
            )
        else:
            messages.info(
                self.request, "'{0}' has been successfully queued.".format(
                    form.cleaned_data['content']
                )
            )
        return super(SendGroup, self).form_valid(form)

@twilio_view
def sms(request):
    """
    Handle all incoming messages from Twilio.

    This is the start of the message processing pipeline.
    """
    r = twiml.Response()
    msg = InboundSms(request.POST)
    msg.start_bg_tasks()

    config = SiteConfiguration.get_solo()
    if not config.disable_all_replies:
        r.message(msg.reply)

    return r
<commit_msg>accept multiple recipients in url params<commit_after>from django.contrib import messages
from django.views.generic.edit import FormView
from django_twilio.decorators import twilio_view
from twilio import twiml

from apostello.forms import SendAdhocRecipientsForm, SendRecipientGroupForm
from apostello.mixins import ProfilePermsMixin
from apostello.models import RecipientGroup
from apostello.reply import InboundSms
from site_config.models import SiteConfiguration

class SendView(ProfilePermsMixin, FormView):
    """Display send SMS form."""
    required_perms = []
    success_url = '/'

    def get_form(self, **kwargs):
        """Add user to form so we can check cost limits."""
        form = super(SendView, self).get_form(**kwargs)
        prepopulated_recipients = self.request.GET.getlist('recipient')
        if prepopulated_recipients:
            form.initial['recipients'] = prepopulated_recipients
        form.user = self.request.user
        return form

    def get_context_data(self, **kwargs):
        """Inject not approved message into context."""
        context = super(SendView, self).get_context_data(**kwargs)
        context['js_path'] = self.template_name.replace('.html', '')
        return context

class SendAdhoc(SendView):
    """Display form for sending messages to individuals or ad-hoc groups."""
    form_class = SendAdhocRecipientsForm
    template_name = 'apostello/send_adhoc.html'
    success_url = '/send/adhoc/'

    def form_valid(self, form):
        """Send message and notify the user on valid form submission."""
        for recipient in form.cleaned_data['recipients']:
            # send and save message
            recipient.send_message(
                content=form.cleaned_data['content'],
                eta=form.cleaned_data['scheduled_time'],
                sent_by=str(self.request.user)
            )

        if form.cleaned_data['scheduled_time'] is None:
            messages.info(
                self.request, "Sending \"{0}\"...\n"
                "Please check the logs for verification...".format(
                    form.cleaned_data['content']
                )
            )
        else:
            messages.info(
                self.request, "'{0}' has been successfully queued.".format(
                    form.cleaned_data['content']
                )
            )

        return super(SendAdhoc, self).form_valid(form)

class SendGroup(SendView):
    """Display form for sending messages to a group."""
    form_class = SendRecipientGroupForm
    template_name = 'apostello/send_group.html'
    success_url = '/send/group/'

    def get_context_data(self, **kwargs):
        """Add the per group costs to context."""
        context = super(SendGroup, self).get_context_data(**kwargs)
        context['group_nums'] = [
            (x.id, x.recipient_set.all().count())
            for x in RecipientGroup.objects.all()
        ]
        return context

    def form_valid(self, form):
        """Send message and notify the user on valid form submission."""
        form.cleaned_data['recipient_group'].send_message(
            content=form.cleaned_data['content'],
            eta=form.cleaned_data['scheduled_time'],
            sent_by=str(self.request.user)
        )
        if form.cleaned_data['scheduled_time'] is None:
            messages.info(
                self.request, "Sending '{0}' to '{1}'...\n"
                "Please check the logs for verification...".format(
                    form.cleaned_data['content'],
                    form.cleaned_data['recipient_group']
                )
            )
        else:
            messages.info(
                self.request, "'{0}' has been successfully queued.".format(
                    form.cleaned_data['content']
                )
            )
        return super(SendGroup, self).form_valid(form)

@twilio_view
def sms(request):
    """
    Handle all incoming messages from Twilio.

    This is the start of the message processing pipeline.
    """
    r = twiml.Response()
    msg = InboundSms(request.POST)
    msg.start_bg_tasks()

    config = SiteConfiguration.get_solo()
    if not config.disable_all_replies:
        r.message(msg.reply)

    return r
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Plot the softmax function.

import matplotlib.pyplot as pl
import numpy as np

def softmax(a, t):
  e = np.exp((1.0 * np.array(a)) / t)
  return e / np.sum(e)

T = [100, 5, 1]
a = [3, 0, 1];
ind = [1, 2, 3]

for i in range(len(T)):
  pl.bar(ind, softmax(a, T[i]))
  pl.ylim(0, 1)
  pl.title('T = %d' % T[i])
  pl.savefig('softmax_temp%d.png' % T[i])
  pl.show()
<commit_msg>fix script<commit_after>#!/usr/bin/env python

# Plot the softmax function.

import matplotlib.pyplot as plt
import numpy as np
import os
from scipy.misc import logsumexp

def softmax(a):
  e = np.exp((1.0 * np.array(a)))
  return e / np.sum(e)

T = [100, 2, 1]
a = np.array([3, 0, 1]);
ind = [1, 2, 3]

plt.figure(figsize=(12,4))
for i in range(len(T)):
    plt.subplot(1,3,i+1)
    plt.bar(ind, softmax(a / T[i]))
    plt.title('T = %d' % T[i])
    plt.ylim(0, 1)
    ax = plt.gca()
    ax.set_xticklabels([])

plt.show()
fname = 'softmax_temp.pdf'
print(fname)
plt.savefig(os.path.join('../figures', fname))

#for i in range(len(T)):
#    plt.bar(ind, softmax(a / T[i]))
#    plt.ylim(0, 1)
#    plt.title('T = %d' % T[i])
#    plt.show()
#    #plt.savefig('softmax_temp%d.png' % T[i])
#    fname = 'softmax_temp%d.pdf' % T[i]
#    print(fname)
#    plt.savefig(os.path.join('../figures', fname))

<|endoftext|>


<commit_before>from django.conf import settings
from django.core.mail import send_mail
from django.template import Context, Template
from django.template.loader import render_to_string

from .models import MailTemplate

def render_mail(template, context):
    """ helper to load subject and content from template """
    subject = render_to_string('zipfelchappe/emails/%s_subject.txt' % template,
        context).strip()
    message = render_to_string('zipfelchappe/emails/%s_message.txt' % template,
        context)

    return subject, message

def send_pledge_completed_message(pledge, mail_template=None):
    """ Send message after backer successfully pledged to a project """

    # Try to get template from project if not explictly passed
    if mail_template is None:
        try:
            mail_template = MailTemplate.objects.get(
                project=pledge.project,
                action=MailTemplate.ACTION_THANKYOU
            ).translated
        except MailTemplate.DoesNotExist:
            pass

    if mail_template is not None:
        context = Context({'pledge': pledge})
        subject = Template(mail_template.subject).render(context)
        message = Template(mail_template.template).render(context)
    else:
        subject, message = render_mail('pledge_completed', {'pledge': pledge})

    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
        [pledge.backer.email], fail_silently=False)
<commit_msg>fail silently on pledge completed mail errors<commit_after>from django.conf import settings
from django.core.mail import send_mail
from django.template import Context, Template
from django.template.loader import render_to_string

from .models import MailTemplate

def render_mail(template, context):
    """ helper to load subject and content from template """
    subject = render_to_string('zipfelchappe/emails/%s_subject.txt' % template,
        context).strip()
    message = render_to_string('zipfelchappe/emails/%s_message.txt' % template,
        context)

    return subject, message

def send_pledge_completed_message(pledge, mail_template=None):
    """ Send message after backer successfully pledged to a project """

    # Try to get template from project if not explictly passed
    if mail_template is None:
        try:
            mail_template = MailTemplate.objects.get(
                project=pledge.project,
                action=MailTemplate.ACTION_THANKYOU
            ).translated
        except MailTemplate.DoesNotExist:
            pass

    if mail_template is not None:
        context = Context({'pledge': pledge})
        subject = Template(mail_template.subject).render(context)
        message = Template(mail_template.template).render(context)
    else:
        subject, message = render_mail('pledge_completed', {'pledge': pledge})

    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
        [pledge.backer.email], fail_silently=True)
<|endoftext|>