<commit_before>#
#

# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""Module doing node maintenance for Ganeti watcher.

"""

import logging

from ganeti import constants
from ganeti import errors
from ganeti import hypervisor
from ganeti import netutils
from ganeti import ssconf
from ganeti import utils
from ganeti import confd
from ganeti.storage import drbd

import ganeti.confd.client # pylint: disable=W0611

class NodeMaintenance(object):
  """Talks to confd daemons and possible shutdown instances/drbd devices.

  """
  def __init__(self):
    self.store_cb = confd.client.StoreResultCallback()
    self.filter_cb = confd.client.ConfdFilterCallback(self.store_cb)
    self.confd_client = confd.client.GetConfdClient(self.filter_cb)

  @staticmethod
  def ShouldRun():
    """Checks whether node maintenance should run.

    """
    try:
      return ssconf.SimpleStore().GetMaintainNodeHealth()
    except errors.ConfigurationError, err:
      logging.error("Configuration error, not activating node maintenance: %s",
                    err)
      return False

  @staticmethod
  def GetRunningInstances():
    """Compute list of hypervisor/running instances.

    """
    hyp_list = ssconf.SimpleStore().GetHypervisorList()
    results = []
    for hv_name in hyp_list:
      try:
        hv = hypervisor.GetHypervisor(hv_name)
        ilist = hv.ListInstances()
        results.extend([(iname, hv_name) for iname in ilist])
      except: # pylint: disable=W0702
        logging.error("Error while listing instances for hypervisor %s",
                      hv_name, exc_info=True)
    return results

  @staticmethod
  def GetUsedDRBDs():
    """Get list of used DRBD minors.

    """
    return drbd.DRBD8.GetUsedDevs()

  @classmethod
  def DoMaintenance(cls, role):
    """Maintain the instance list.

    """
    if role == constants.CONFD_NODE_ROLE_OFFLINE:
      inst_running = cls.GetRunningInstances()
      cls.ShutdownInstances(inst_running)
      drbd_running = cls.GetUsedDRBDs()
      cls.ShutdownDRBD(drbd_running)
    else:
      logging.debug("Not doing anything for role %s", role)

  @staticmethod
  def ShutdownInstances(inst_running):
    """Shutdown running instances.

    """
    names_running = set([i[0] for i in inst_running])
    if names_running:
      logging.info("Following instances should not be running,"
                   " shutting them down: %s", utils.CommaJoin(names_running))
      # this dictionary will collapse duplicate instance names (only
      # xen pvm/vhm) into a single key, which is fine
      i2h = dict(inst_running)
      for name in names_running:
        hv_name = i2h[name]
        hv = hypervisor.GetHypervisor(hv_name)
        hv.StopInstance(None, force=True, name=name)

  @staticmethod
  def ShutdownDRBD(drbd_running):
    """Shutdown active DRBD devices.

    """
    if drbd_running:
      logging.info("Following DRBD minors should not be active,"
                   " shutting them down: %s", utils.CommaJoin(drbd_running))
      for minor in drbd_running:
        drbd.DRBD8.ShutdownAll(minor)

  def Exec(self):
    """Check node status versus cluster desired state.

    """
    if not constants.ENABLE_CONFD:
      logging.warning("Confd use not enabled, cannot do maintenance")
      return

    my_name = netutils.Hostname.GetSysName()
    req = \
      confd.client.ConfdClientRequest(type=constants.CONFD_REQ_NODE_ROLE_BYNAME,
                                      query=my_name)
    self.confd_client.SendRequest(req, async=False, coverage=-1)
    timed_out, _, _ = self.confd_client.WaitForReply(req.rsalt)
    if not timed_out:
      # should have a valid response
      status, result = self.store_cb.GetResponse(req.rsalt)
      assert status, "Missing result but received replies"
      if not self.filter_cb.consistent[req.rsalt]:
        logging.warning("Inconsistent replies, not doing anything")
        return
      self.DoMaintenance(result.server_reply.answer)
    else:
      logging.warning("Confd query timed out, cannot do maintenance actions")
<commit_msg>Watcher: Use hvparams when listing instances<commit_after>#
#

# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""Module doing node maintenance for Ganeti watcher.

"""

import logging

from ganeti import constants
from ganeti import errors
from ganeti import hypervisor
from ganeti import netutils
from ganeti import ssconf
from ganeti import utils
from ganeti import confd
from ganeti.storage import drbd

import ganeti.confd.client # pylint: disable=W0611

class NodeMaintenance(object):
  """Talks to confd daemons and possible shutdown instances/drbd devices.

  """
  def __init__(self):
    self.store_cb = confd.client.StoreResultCallback()
    self.filter_cb = confd.client.ConfdFilterCallback(self.store_cb)
    self.confd_client = confd.client.GetConfdClient(self.filter_cb)

  @staticmethod
  def ShouldRun():
    """Checks whether node maintenance should run.

    """
    try:
      return ssconf.SimpleStore().GetMaintainNodeHealth()
    except errors.ConfigurationError, err:
      logging.error("Configuration error, not activating node maintenance: %s",
                    err)
      return False

  @staticmethod
  def GetRunningInstances():
    """Compute list of hypervisor/running instances.

    """
    hyp_list = ssconf.SimpleStore().GetHypervisorList()
    hvparams = ssconf.SimpleStore().GetHvparams()
    results = []
    for hv_name in hyp_list:
      try:
        hv = hypervisor.GetHypervisor(hv_name)
        ilist = hv.ListInstances(hvparams=hvparams)
        results.extend([(iname, hv_name) for iname in ilist])
      except: # pylint: disable=W0702
        logging.error("Error while listing instances for hypervisor %s",
                      hv_name, exc_info=True)
    return results

  @staticmethod
  def GetUsedDRBDs():
    """Get list of used DRBD minors.

    """
    return drbd.DRBD8.GetUsedDevs()

  @classmethod
  def DoMaintenance(cls, role):
    """Maintain the instance list.

    """
    if role == constants.CONFD_NODE_ROLE_OFFLINE:
      inst_running = cls.GetRunningInstances()
      cls.ShutdownInstances(inst_running)
      drbd_running = cls.GetUsedDRBDs()
      cls.ShutdownDRBD(drbd_running)
    else:
      logging.debug("Not doing anything for role %s", role)

  @staticmethod
  def ShutdownInstances(inst_running):
    """Shutdown running instances.

    """
    names_running = set([i[0] for i in inst_running])
    if names_running:
      logging.info("Following instances should not be running,"
                   " shutting them down: %s", utils.CommaJoin(names_running))
      # this dictionary will collapse duplicate instance names (only
      # xen pvm/vhm) into a single key, which is fine
      i2h = dict(inst_running)
      for name in names_running:
        hv_name = i2h[name]
        hv = hypervisor.GetHypervisor(hv_name)
        hv.StopInstance(None, force=True, name=name)

  @staticmethod
  def ShutdownDRBD(drbd_running):
    """Shutdown active DRBD devices.

    """
    if drbd_running:
      logging.info("Following DRBD minors should not be active,"
                   " shutting them down: %s", utils.CommaJoin(drbd_running))
      for minor in drbd_running:
        drbd.DRBD8.ShutdownAll(minor)

  def Exec(self):
    """Check node status versus cluster desired state.

    """
    if not constants.ENABLE_CONFD:
      logging.warning("Confd use not enabled, cannot do maintenance")
      return

    my_name = netutils.Hostname.GetSysName()
    req = \
      confd.client.ConfdClientRequest(type=constants.CONFD_REQ_NODE_ROLE_BYNAME,
                                      query=my_name)
    self.confd_client.SendRequest(req, async=False, coverage=-1)
    timed_out, _, _ = self.confd_client.WaitForReply(req.rsalt)
    if not timed_out:
      # should have a valid response
      status, result = self.store_cb.GetResponse(req.rsalt)
      assert status, "Missing result but received replies"
      if not self.filter_cb.consistent[req.rsalt]:
        logging.warning("Inconsistent replies, not doing anything")
        return
      self.DoMaintenance(result.server_reply.answer)
    else:
      logging.warning("Confd query timed out, cannot do maintenance actions")
<|endoftext|>


<commit_before>import json
from datetime import datetime as date
from django.shortcuts import render
from django.http import HttpResponse
from .models import Class, Student, Event, Teacher, Department, Note, Subject, TaughtBy

period_time = {0: '9:00',
               1: '10:00',
               2: '11:00',
               3: '13:00',
               4: '14:00',
               5: '15:00'}

def index(request):
    # Return the page at core/index.html
    return render(request, "core/index.html", None)

def get_timetable_dummy(request, user_id):
    timetable = {
            'monday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'tuesday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'wednessday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'thursday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'friday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            }
    return HttpResponse(json.dumps(timetable), content_type="application/json")

def get_timetable(request, user_id):
    user = Student.objects.get(SID=user_id)
    timetable = user.current_class.get_tt()
    return HttpResponse(json.dumps(timetable), content_type="application/json")

def get_notes(request, user_id):
    user = Student.objects.get(SID=user_id)
    notes = Note.objects.filter(user=user)

    notes_list = []
    for note in notes:
        n = {}
        n['date'] = note.date
        n['subject'] = note.subject.subject_title
        n['note'] = note.data
        notes_list.append(n)

    return HttpResponse(json.dumps(notes_list))

def get_notes_dummy(request, user_id):
    notes_data = [
            {
                'date': '24-3-2014',
                'subject': 'Modern Control Systems',
                'note': '# Control Theory \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list'
                },
            {
                'date': '21-3-2014',
                'subject': 'Modern Control Systems',
                'note': '# Eeks \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list'
                },
            {
                'date': '22-3-2014',
                'subject': 'Digital Signal Processing',
                'note': '# Image support \n\n` it is very very important ` \n\n![image](https://img.buzzfeed.com/buzzfeed-static/static/2015-04/21/16/enhanced/webdr05/enhanced-31550-1429646952-7.jpg)'
                },
            {
                'date': '25-3-2014',
                'subject': 'Operating Systems',
                'note': '# Multilevel headings\n\n ## second level\n\n### third level\n\n#### forth level\n\n and more ...'
                },
            {
                'date': '26-3-2014',
                'subject': 'Compiler Construction',
                'note': '# Hyperlinks too \n\n[Google](http://google.com)'
                },
            {
                'date': '28-3-2014',
                'subject': 'Control Thory',
                'note': '# Full markdown support\n\n`even code snippet`\n\n```python\nprint "hai"```'
                },
            ]
    return_data = {}
    return_data['data'] = notes_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_sub_data_dummy(request, user_id):
    subject_data = {
            'MCS': {
                'subject': 'Modern Control Systems',
                'teacher':'Jisha Joseph',
                },
            'DSP': {
                'subject': 'Digital Signal Processing',
                'teacher':'Razia Rahim',
                },
            'OS': {
                'subject': 'Operating Systems',
                'teacher':'Damodaran V',
                },
            'CC': {
                'subject': 'Compiler Construction',
                'teacher':'Sheena Mathew',
                }
            }
    return HttpResponse(json.dumps(subject_data), content_type="application/json")

def get_sub_data(request, user_id):
    # day = (date.today().strftime("%A")).lower()
    day = 'monday'
    return_dict = {}
    if not (day == 'sunday' or day == 'saturday'):
        user = Student.objects.get(SID=user_id)
        daytable = user.current_class.get_tt()[day].split(',')

        query = TaughtBy.objects.filter(classes__class_name=user.current_class)
        ts_dict = {x.subject.subject_short_name: (x.teachers.teacher_name, x.subject.subject_title) for x in query}

        for sub_code in daytable:
            return_dict[sub_code] = {'teacher': ts_dict[sub_code][0],
                                     'subject': ts_dict[sub_code][1]}

    return HttpResponse(json.dumps(return_dict))

def get_events_dummy(request, user_id):
    upcoming_events = [
            {
                'name': 'Project interim submission',
                'due': '30-03-2017',
                'to': 'Damodaran V',
                'subject' : 'Mini Project',
                'description': 'Interim submission of mini project'
                },
            {
                'name': 'SP Lab Record submission',
                'due': '30-03-2017',
                'to': 'Deepa Paul',
                'subject' : 'SP-Laboratory',
                'description': 'Fair record submission of Systems Programming Laboratory'
                },
            ]
    return_data = {}
    return_data['data'] = upcoming_events
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_events(request, user_id):
    user = Student.objects.get(SID=user_id)
    elist = Event.objects.filter(assigned_to=user.current_class)
    # elist = set(list(Event.objects.filter(assigned_to__class_name=user.current_class)) + list(Event.objects.filter(user__SID=user_id)))
    print elist
    return_list = []
    for event in elist:
        d = {}
        d['name'] = event.title
        d['due'] = str(event.due_date)
        d['to'] = event.teacher.teacher_name
        d['subject'] = event.subject.subject_title
        d['description'] = event.description
        return_list.append(d)
    print return_list
    return HttpResponse(json.dumps(return_list))

def get_track_data(request):
    if request.method == "POST":
        data = json.loads(request.POST.get('data'))
        user_id = data['id']
        date = data['date']
        day = data['day']
    user = Student.objects.get(SID=user_id)
    day_tt = user.current_class.get_tt()[day].split(',')

    def get_notes_for_period(period):
        if Note.objects.filter(user=user, date=date, period=period).exists():
            return Note.objects.get(user=user, date=date, period=period)
        else:
            return None

    track_data = []
    for i in range(6):
        note = get_notes_for_period(i)
        p = {}

        p['period'] = i
        if note is not None:
            p['notes'] = note.data
            p['subject'] = note.subject.subject_short_name
        else:
            p['notes'] = ''
            p['subject'] = day_tt[i]

        p['time'] = period_time[i]
        track_data.append(p)

    return HttpResponse(json.dumps(track_data))

def set_track_data(request):
    if request.method == "POST":
            user_id = request.POST.get('id')
            date = request.POST.get('date')
            day = request.POST.get('day')
            track_data = request.POST.get('track_data')[1:][:-1]
            # a wild bodge appeared
            track_data = [e+'}' for e in track_data.split('},') if e]
            track_data[-1] = track_data[-1][:-1]
            track_data = [json.loads(e) for e in track_data]

    user = Student.objects.get(SID=user_id)
    day_tt = user.current_class.get_tt()[day].split(',')

    for entry in track_data:
        period = entry['period']
        subject = Subject.objects.get(subject_short_name=day_tt[period])
        note = Note.objects.filter(user=user, period=period, date=date)
        if note.exists():
            note.update(data=entry['notes'])
        else:
            new_note = Note(user=user, period=period, date=date, data=entry['notes'], subject=subject)
            new_note.save()
    return HttpResponse(json.dumps({ 'status': 'OK' }))

def get_track_data_dummy(request, user_id):
    track_data = [
            {
                'period': 0,
                'notes': '# Control Theory \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list',
                'attendece' : '',
                'time': '9:00'
                },
            {
                'period': 1,
                'notes': '',
                'attendece' : '',
                'time': '10:00'
                },
            {
                'period': 2,
                'notes': '',
                'attendece' : '',
                'time': '11:00'
                },
            {
                'period': 3,
                'notes': '',
                'attendece' : '',
                'time': '13:00'
                },
            {
                'period': 4,
                'notes': '',
                'attendece' : '',
                'time': '14:00'
                },
            {
                'period': 5,
                'notes': '',
                'attendece' : '',
                'time': '15:00'
                }
            ]

    return_data = {}
    return_data['data'] = track_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def create_new_user(request):
    if request.method == "POST":
        user_id = json.loads(request.POST.get('user_data'))['id']
        _class = request.POST.get('class')
        c = Class.objects.filter(class_name=_class)[0]
        #Initialize attendence
        attendence = {}
        subs = c.get_subs()
        for sub in subs:
            attendence[sub] = {'attended': 0, 'total': 0}
        attendence = json.dumps(attendence)

        user = Student(SID=user_id)
        user.current_class = c
        user.attendence = attendence
        user.save()
        return HttpResponse(json.dumps({'exists': True}))

def signin(request):
    if request.method == "POST":
        data = json.loads(request.POST.get('data'))
        sid = data['id']
        if Student.objects.filter(SID=sid).exists():
            return HttpResponse(json.dumps({'exists': True}))
        else:
            classes = [name.class_name for name in Class.objects.all()]
            data = json.dumps({'exists': False, 'options': classes})
            return HttpResponse(json.dumps(data), content_type="application/json")

def get_cal_data(request, user_id):
    user = Student.objects.get(SID=user_id)
    elist = Event.objects.filter(assigned_to=user.current_class)
    # elist = set(list(Event.objects.filter(assigned_to__class_name=user.current_class)) + list(Event.objects.filter(user__SID=user_id)))
    print elist
    return_list = []
    for event in elist:
        d = {}
        d['name'] = event.title
        d['due'] = str(event.due_date)
        d['to'] = event.teacher.teacher_name
        d['subject'] = event.subject.subject_title
        d['description'] = event.description
        return_list.append(d)
    print return_list
    return HttpResponse(json.dumps(return_list))

def get_cal_data_dummy(request, user_id):
    cal_events = [
            {
                'title': 'New Event',
                'start': '2017-05-01'
                },
            {
                'title': 'Some big event',
                'start': '2017-04-07',
                'end': '2017-04-10'
                },
            ]
    return_data = {}
    return_data['data'] = cal_events
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_attendence(request, user_id):
    user = Student.objects.get(SID=user_id)
    attendence_data = user.get_attendence_data()

    print attendence_data
    if len(attendence_data) is 0:
        # quick patch ( issue only if new user already created)
        daytable = user.current_class.get_tt()
        subs = {}
        for key in daytable:
            daysubs = daytable[key].split(',')
            for item in daysubs:
                # if item not in subs:  ( its a dict, lol )
                subs[item] = {'total':0, 'attended':0 }
        attendence_data = subs

    return_data = {}
    return_data['data'] = attendence_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def update_attendence(request):
    if request.method == "POST":
        data =  json.loads(request.POST.get('data'))
        user_id = data['id']
        attendence = json.dumps(data['attendance'])

        user = Student.objects.get(SID=user_id)
        user.attendence = attendence
        user.save()
    return_data = { 'status':'OK' }
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_subject_attendence_dummy(request, user_id):
    subject_attendence = [
            {
                'name': 'MCS',
                'attended': 15,
                'total': 22
                },
            {
                'name': 'DSP',
                'attended': 18,
                'total': 20
                },
            {
                'name': 'SIC',
                'attended': 15,
                'total': 27
                },
            {
                'name': 'OS',
                'attended': 5,
                'total': 20
                },
            {
                'name': 'CC',
                'attended': 15,
                'total': 15
                },
            {
                'name': 'PDG',
                'attended': 10,
                'total': 21
                },
            ]
    return_data = {}
    return_data['data'] = subject_attendence
    return HttpResponse(json.dumps(return_data), content_type="application/json")
<commit_msg>Exclude events before today<commit_after>import json
from datetime import datetime as date
from django.shortcuts import render
from django.http import HttpResponse
from .models import Class, Student, Event, Teacher, Department, Note, Subject, TaughtBy
from datetime import datetime

period_time = {0: '9:00',
               1: '10:00',
               2: '11:00',
               3: '13:00',
               4: '14:00',
               5: '15:00'}

def index(request):
    # Return the page at core/index.html
    return render(request, "core/index.html", None)

def get_timetable_dummy(request, user_id):
    timetable = {
            'monday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'tuesday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'wednessday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'thursday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            'friday': ['MCS', 'DSP', 'DSP', 'OS', 'OS', 'CC'],
            }
    return HttpResponse(json.dumps(timetable), content_type="application/json")

def get_timetable(request, user_id):
    user = Student.objects.get(SID=user_id)
    timetable = user.current_class.get_tt()
    return HttpResponse(json.dumps(timetable), content_type="application/json")

def get_notes(request, user_id):
    user = Student.objects.get(SID=user_id)
    notes = Note.objects.filter(user=user)

    notes_list = []
    for note in notes:
        n = {}
        n['date'] = note.date
        n['subject'] = note.subject.subject_title
        n['note'] = note.data
        notes_list.append(n)

    return HttpResponse(json.dumps(notes_list))

def get_notes_dummy(request, user_id):
    notes_data = [
            {
                'date': '24-3-2014',
                'subject': 'Modern Control Systems',
                'note': '# Control Theory \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list'
                },
            {
                'date': '21-3-2014',
                'subject': 'Modern Control Systems',
                'note': '# Eeks \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list'
                },
            {
                'date': '22-3-2014',
                'subject': 'Digital Signal Processing',
                'note': '# Image support \n\n` it is very very important ` \n\n![image](https://img.buzzfeed.com/buzzfeed-static/static/2015-04/21/16/enhanced/webdr05/enhanced-31550-1429646952-7.jpg)'
                },
            {
                'date': '25-3-2014',
                'subject': 'Operating Systems',
                'note': '# Multilevel headings\n\n ## second level\n\n### third level\n\n#### forth level\n\n and more ...'
                },
            {
                'date': '26-3-2014',
                'subject': 'Compiler Construction',
                'note': '# Hyperlinks too \n\n[Google](http://google.com)'
                },
            {
                'date': '28-3-2014',
                'subject': 'Control Thory',
                'note': '# Full markdown support\n\n`even code snippet`\n\n```python\nprint "hai"```'
                },
            ]
    return_data = {}
    return_data['data'] = notes_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_sub_data_dummy(request, user_id):
    subject_data = {
            'MCS': {
                'subject': 'Modern Control Systems',
                'teacher':'Jisha Joseph',
                },
            'DSP': {
                'subject': 'Digital Signal Processing',
                'teacher':'Razia Rahim',
                },
            'OS': {
                'subject': 'Operating Systems',
                'teacher':'Damodaran V',
                },
            'CC': {
                'subject': 'Compiler Construction',
                'teacher':'Sheena Mathew',
                }
            }
    return HttpResponse(json.dumps(subject_data), content_type="application/json")

def get_sub_data(request, user_id):
    # day = (date.today().strftime("%A")).lower()
    day = 'monday'
    return_dict = {}
    if not (day == 'sunday' or day == 'saturday'):
        user = Student.objects.get(SID=user_id)
        daytable = user.current_class.get_tt()[day].split(',')

        query = TaughtBy.objects.filter(classes__class_name=user.current_class)
        ts_dict = {x.subject.subject_short_name: (x.teachers.teacher_name, x.subject.subject_title) for x in query}

        for sub_code in daytable:
            return_dict[sub_code] = {'teacher': ts_dict[sub_code][0],
                                     'subject': ts_dict[sub_code][1]}

    return HttpResponse(json.dumps(return_dict))

def get_events_dummy(request, user_id):
    upcoming_events = [
            {
                'name': 'Project interim submission',
                'due': '30-03-2017',
                'to': 'Damodaran V',
                'subject' : 'Mini Project',
                'description': 'Interim submission of mini project'
                },
            {
                'name': 'SP Lab Record submission',
                'due': '30-03-2017',
                'to': 'Deepa Paul',
                'subject' : 'SP-Laboratory',
                'description': 'Fair record submission of Systems Programming Laboratory'
                },
            ]
    return_data = {}
    return_data['data'] = upcoming_events
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_events(request, user_id):
    user = Student.objects.get(SID=user_id)
    elist = Event.objects.filter(assigned_to=user.current_class, due_date__gte=datetime.now())
    # elist = set(list(Event.objects.filter(assigned_to__class_name=user.current_class)) + list(Event.objects.filter(user__SID=user_id)))
    print elist
    return_list = []
    for event in elist:
        d = {}
        d['name'] = event.title
        d['due'] = str(event.due_date)
        d['to'] = event.teacher.teacher_name
        d['subject'] = event.subject.subject_title
        d['description'] = event.description
        return_list.append(d)
    print return_list
    return HttpResponse(json.dumps(return_list))

def get_track_data(request):
    if request.method == "POST":
        data = json.loads(request.POST.get('data'))
        user_id = data['id']
        date = data['date']
        day = data['day']
    user = Student.objects.get(SID=user_id)
    day_tt = user.current_class.get_tt()[day].split(',')

    def get_notes_for_period(period):
        if Note.objects.filter(user=user, date=date, period=period).exists():
            return Note.objects.get(user=user, date=date, period=period)
        else:
            return None

    track_data = []
    for i in range(6):
        note = get_notes_for_period(i)
        p = {}

        p['period'] = i
        if note is not None:
            p['notes'] = note.data
            p['subject'] = note.subject.subject_short_name
        else:
            p['notes'] = ''
            p['subject'] = day_tt[i]

        p['time'] = period_time[i]
        track_data.append(p)

    return HttpResponse(json.dumps(track_data))

def set_track_data(request):
    if request.method == "POST":
            user_id = request.POST.get('id')
            date = request.POST.get('date')
            day = request.POST.get('day')
            track_data = request.POST.get('track_data')[1:][:-1]
            # a wild bodge appeared
            track_data = [e+'}' for e in track_data.split('},') if e]
            track_data[-1] = track_data[-1][:-1]
            track_data = [json.loads(e) for e in track_data]

    user = Student.objects.get(SID=user_id)
    day_tt = user.current_class.get_tt()[day].split(',')

    for entry in track_data:
        period = entry['period']
        subject = Subject.objects.get(subject_short_name=day_tt[period])
        note = Note.objects.filter(user=user, period=period, date=date)
        if note.exists():
            note.update(data=entry['notes'])
        else:
            new_note = Note(user=user, period=period, date=date, data=entry['notes'], subject=subject)
            new_note.save()
    return HttpResponse(json.dumps({ 'status': 'OK' }))

def get_track_data_dummy(request, user_id):
    track_data = [
            {
                'period': 0,
                'notes': '# Control Theory \n\n` it is something important ` \n\n> e=mc^2\n\n* it\n* even\n* support\n* bulleted list',
                'attendece' : '',
                'time': '9:00'
                },
            {
                'period': 1,
                'notes': '',
                'attendece' : '',
                'time': '10:00'
                },
            {
                'period': 2,
                'notes': '',
                'attendece' : '',
                'time': '11:00'
                },
            {
                'period': 3,
                'notes': '',
                'attendece' : '',
                'time': '13:00'
                },
            {
                'period': 4,
                'notes': '',
                'attendece' : '',
                'time': '14:00'
                },
            {
                'period': 5,
                'notes': '',
                'attendece' : '',
                'time': '15:00'
                }
            ]

    return_data = {}
    return_data['data'] = track_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def create_new_user(request):
    if request.method == "POST":
        user_id = json.loads(request.POST.get('user_data'))['id']
        _class = request.POST.get('class')
        c = Class.objects.filter(class_name=_class)[0]
        #Initialize attendence
        attendence = {}
        subs = c.get_subs()
        for sub in subs:
            attendence[sub] = {'attended': 0, 'total': 0}
        attendence = json.dumps(attendence)

        user = Student(SID=user_id)
        user.current_class = c
        user.attendence = attendence
        user.save()
        return HttpResponse(json.dumps({'exists': True}))

def signin(request):
    if request.method == "POST":
        data = json.loads(request.POST.get('data'))
        sid = data['id']
        if Student.objects.filter(SID=sid).exists():
            return HttpResponse(json.dumps({'exists': True}))
        else:
            classes = [name.class_name for name in Class.objects.all()]
            data = json.dumps({'exists': False, 'options': classes})
            return HttpResponse(json.dumps(data), content_type="application/json")

def get_cal_data(request, user_id):
    user = Student.objects.get(SID=user_id)
    elist = Event.objects.filter(assigned_to=user.current_class)
    # elist = set(list(Event.objects.filter(assigned_to__class_name=user.current_class)) + list(Event.objects.filter(user__SID=user_id)))
    print elist
    return_list = []
    for event in elist:
        d = {}
        d['name'] = event.title
        d['due'] = str(event.due_date)
        d['to'] = event.teacher.teacher_name
        d['subject'] = event.subject.subject_title
        d['description'] = event.description
        return_list.append(d)
    print return_list
    return HttpResponse(json.dumps(return_list))

def get_cal_data_dummy(request, user_id):
    cal_events = [
            {
                'title': 'New Event',
                'start': '2017-05-01'
                },
            {
                'title': 'Some big event',
                'start': '2017-04-07',
                'end': '2017-04-10'
                },
            ]
    return_data = {}
    return_data['data'] = cal_events
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_attendence(request, user_id):
    user = Student.objects.get(SID=user_id)
    attendence_data = user.get_attendence_data()

    print attendence_data
    if len(attendence_data) is 0:
        # quick patch ( issue only if new user already created)
        daytable = user.current_class.get_tt()
        subs = {}
        for key in daytable:
            daysubs = daytable[key].split(',')
            for item in daysubs:
                # if item not in subs:  ( its a dict, lol )
                subs[item] = {'total':0, 'attended':0 }
        attendence_data = subs

    return_data = {}
    return_data['data'] = attendence_data
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def update_attendence(request):
    if request.method == "POST":
        data =  json.loads(request.POST.get('data'))
        user_id = data['id']
        attendence = json.dumps(data['attendance'])

        user = Student.objects.get(SID=user_id)
        user.attendence = attendence
        user.save()
    return_data = { 'status':'OK' }
    return HttpResponse(json.dumps(return_data), content_type="application/json")

def get_subject_attendence_dummy(request, user_id):
    subject_attendence = [
            {
                'name': 'MCS',
                'attended': 15,
                'total': 22
                },
            {
                'name': 'DSP',
                'attended': 18,
                'total': 20
                },
            {
                'name': 'SIC',
                'attended': 15,
                'total': 27
                },
            {
                'name': 'OS',
                'attended': 5,
                'total': 20
                },
            {
                'name': 'CC',
                'attended': 15,
                'total': 15
                },
            {
                'name': 'PDG',
                'attended': 10,
                'total': 21
                },
            ]
    return_data = {}
    return_data['data'] = subject_attendence
    return HttpResponse(json.dumps(return_data), content_type="application/json")
<|endoftext|>


<commit_before># Copyright 2015 Carnegie Mellon University
#
# 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.

import cv2
import openface
import os

import numpy as np
np.set_printoptions(precision=2)
from numpy.linalg import norm

import scipy
import scipy.spatial

import time

import openface
import openface.helper
from openface.data import iterImgs
from openface.alignment import NaiveDlib  # Depends on dlib.

from subprocess import Popen, PIPE

import sys
fileDir = os.path.dirname(os.path.realpath(__file__))

modelDir = os.path.join(fileDir, 'models')
dlibModelDir = os.path.join(modelDir, 'dlib')
openfaceModelDir = os.path.join(modelDir, 'openface')

dlibFacePredictor = os.path.join(dlibModelDir,
                                 "shape_predictor_68_face_landmarks.dat")
networkModel = os.path.join(openfaceModelDir, 'nn4.v1.t7')
imgDim = 96

align = NaiveDlib(dlibFacePredictor)
net = openface.TorchWrap(networkModel, imgDim=imgDim)

def test_pipeline():
    imgPath = os.path.join('images', 'examples', 'lennon-1.jpg')
    bgrImg = cv2.imread(imgPath)
    if bgrImg is None:
        raise Exception("Unable to load image: {}".format(imgPath))
    rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)
    assert np.isclose(norm(rgbImg), 11.1355)

    bb = align.getLargestFaceBoundingBox(rgbImg)
    assert bb.left() == 341
    assert bb.right() == 1006
    assert bb.top() == 193
    assert bb.bottom() == 859

    alignedFace = align.alignImg("affine", imgDim, rgbImg, bb)
    assert np.isclose(norm(alignedFace), 8.30662)

    rep = net.forwardImage(alignedFace)
    assert np.isclose(scipy.spatial.distance.cosine(rep, np.ones(128)),
                      1.01860434258)

def test_compare_demo():
    cmd = ['python2', './demos/compare.py',
           'images/examples/lennon-1.jpg',
           'images/examples/lennon-2.jpg']
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    (out, err) = p.communicate()
    print(err)
    assert "0.298" in out

def test_classification_demo():
    cmd = ['python2', './demos/classifier.py',
           'infer',
           './models/openface/celeb-classifier.nn4.v1.pkl',
           'images/examples/carell.jpg']
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    (out, err) = p.communicate()
    print(err)
    assert "Predict SteveCarell with 0.96 confidence." in out
<commit_msg>tests: Use full paths.<commit_after># Copyright 2015 Carnegie Mellon University
#
# 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.

import cv2
import openface
import os

import numpy as np
np.set_printoptions(precision=2)
from numpy.linalg import norm

import scipy
import scipy.spatial

import time

import openface
import openface.helper
from openface.data import iterImgs
from openface.alignment import NaiveDlib  # Depends on dlib.

from subprocess import Popen, PIPE

import sys
fileDir = os.path.dirname(os.path.realpath(__file__))

modelDir = os.path.join(fileDir, 'models')
dlibModelDir = os.path.join(modelDir, 'dlib')
openfaceModelDir = os.path.join(modelDir, 'openface')

dlibFacePredictor = os.path.join(dlibModelDir,
                                 "shape_predictor_68_face_landmarks.dat")
networkModel = os.path.join(openfaceModelDir, 'nn4.v1.t7')
imgDim = 96

align = NaiveDlib(dlibFacePredictor)
net = openface.TorchWrap(networkModel, imgDim=imgDim)

def test_pipeline():
    imgPath = os.path.join(fileDir, 'images', 'examples', 'lennon-1.jpg')
    bgrImg = cv2.imread(imgPath)
    if bgrImg is None:
        raise Exception("Unable to load image: {}".format(imgPath))
    rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)
    assert np.isclose(norm(rgbImg), 11.1355)

    bb = align.getLargestFaceBoundingBox(rgbImg)
    assert bb.left() == 341
    assert bb.right() == 1006
    assert bb.top() == 193
    assert bb.bottom() == 859

    alignedFace = align.alignImg("affine", imgDim, rgbImg, bb)
    assert np.isclose(norm(alignedFace), 8.30662)

    rep = net.forwardImage(alignedFace)
    assert np.isclose(scipy.spatial.distance.cosine(rep, np.ones(128)),
                      1.01860434258)

def test_compare_demo():
    cmd = ['python2', os.path.join(fileDir, 'demos', 'compare.py'),
           os.path.join(fileDir, 'images', 'examples', 'lennon-1.jpg'),
           os.path.join(fileDir, 'images', 'examples', 'lennon-2.jpg')]
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    (out, err) = p.communicate()
    print(err)
    assert "0.298" in out

def test_classification_demo():
    cmd = ['python2', os.path.join(fileDir, 'demos', 'classifier.py'),
           'infer',
           os.path.join(fileDir, 'models', 'openface',
                        'celeb-classifier.nn4.v1.pkl'),
           os.path.join(fileDir, 'images', 'examples', 'carell.jpg')]
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    (out, err) = p.communicate()
    print(err)
    assert "Predict SteveCarell with 0.96 confidence." in out
<|endoftext|>


<commit_before>from twisted.words.protocols import irc
from txircd.modbase import Command
from txircd.utils import irc_lower, epoch

class ModeCommand(Command):
	def onUse(self, user, data):
		if "targetchan" in data:
			self.chanUse(user, data["targetchan"], data["modes"])
		elif "targetuser" in data:
			if user == data["targetuser"]:
				self.userUse(user, data["modes"])
			else:
				user.sendMessage(irc.ERR_USERSDONTMATCH, ":Can't operate on modes for other users")

	def chanUse(self, user, channel, modes):
		if not modes:
			user.sendMessage(irc.RPL_CHANNELMODEIS, channel.name, channel.modeString(user))
			user.sendMessage(irc.RPL_CREATIONTIME, channel.name, str(epoch(channel.created)))
			return
		modeDisplay = []
		for modedata in modes:
			modetype, adding, mode, param = modedata
			if not (modetype == 0 and param is None): # ignore these checks for listing list modes
				if not adding and mode not in channel.mode:
					continue # channel does not have mode set; cannot remove
				if adding:
					allowed, param = self.ircd.channel_modes[modetype][mode].checkSet(user, channel, param)
					if not allowed:
						continue
				else:
					allowed, param = self.ircd.channel_modes[modetype][mode].checkUnset(user, channel, param)
					if not allowed:
						continue
			modedata[3] = param # update the param in modedata so that the displayed mode change is shown correctly
			if modetype == -1:
				if param not in self.ircd.users:
					continue
				udata = self.ircd.users[param]
				if channel.name not in udata.channels:
					continue
				if adding:
					status = udata.channels[channel.name]["status"]
					statusList = list(status)
					for index, statusLevel in enumerate(status):
						if self.ircd.prefixes[statusLevel][1] < self.ircd.prefixes[mode][1]:
							statusList.insert(index, mode)
							break
					udata.channels[channel.name]["status"] = "".join(statusList)
					modeDisplay.append(modedata)
				else:
					if mode in udata.channels[channel.name]["status"]:
						udata.channels[channel.name]["status"].remove(mode)
						modeDisplay.append(modedata)
			elif modetype == 0:
				if not param:
					self.ircd.channel_modes[modetype][mode].showParam(user, channel)
				elif adding:
					if mode not in channel.mode:
						channel.mode[mode] = []
					if param not in channel.mode[mode]:
						channel.mode[mode].append(param)
						modeDisplay.append(modedata)
				else:
					if mode not in channel.mode:
						continue
					if param in channel.mode[mode]:
						channel.mode[mode].remove(param)
						modeDisplay.append(modedata)
						if not channel.mode[mode]:
							del channel.mode[mode]
			else:
				if adding:
					if mode in channel.mode and param == channel.mode[mode]:
						continue
					channel.mode[mode] = param
					modeDisplay.append(modedata)
				else:
					if mode not in channel.mode:
						continue
					if modetype == 1 and param != channel.mode[mode]:
						continue
					del channel.mode[mode]
					modeDisplay.append(modedata)
		if modeDisplay:
			adding = None
			modestring = [] # use an array of characters since we're repeatedly adding to this; join at the end
			params = []
			for mode in modeDisplay:
				if mode[1] and adding != "+":
					adding = "+"
					modestring.append("+")
				elif not mode[1] and adding != "-":
					adding = "-"
					modestring.append("-")
				modestring.append(mode[2])
				if mode[3]:
					params.append(mode[3])
			modeLine = "{} {}".format("".join(modestring), " ".join(params)) if params else "".join(modestring)
			for udata in channel.users:
				udata.sendMessage("MODE", modeLine, to=channel.name, prefix=user.prefix())

	def userUse(self, user, modes):
		if not modes:
			user.sendMessage(irc.RPL_UMODEIS, user.modeString(user))
			return
		modeDisplay = []
		for modedata in modes:
			modetype, adding, mode, param = modedata
			if not (modetype == 0 and param is None): # ignore these checks for listing list modes
				if not adding and mode not in user.mode:
					continue # Cannot unset mode that's not set
				if adding:
					allowed, param = self.ircd.user_modes[modetype][mode].checkSet(user, user, param)
					if not allowed:
						continue
				else:
					allowed, param = self.ircd.user_modes[modetype][mode].checkUnset(user, user, param)
					if not allowed:
						continue
			modedata[3] = param # update the param in modedata so that the displayed mode change is shown correctly
			if modetype == 0:
				if not param:
					self.ircd.user_modes[modetype][mode].showParam(user, user)
				elif adding:
					if mode not in user.mode:
						user.mode[mode] = []
					if param not in user.mode[mode]:
						user.mode[mode].append(param)
						modeDisplay.append(modedata)
				else:
					if mode not in user.mode:
						continue
					if param in user.mode[mode]:
						user.mode[mode].remove(param)
						modeDisplay.append(modedata)
						if not user.mode[mode]:
							del user.mode[mode]
			else:
				if adding:
					if mode in user.mode and param == user.mode[mode]:
						continue
					user.mode[mode] = param
					modeDisplay.append(modedata)
				else:
					if mode not in user.mode:
						continue
					if modetype == 1 and param != user.mode[mode]:
						continue
					del user.mode[mode]
					modeDisplay.append(modedata)
		if modeDisplay:
			adding = None
			modestring = [] # use an array of characters since we're repeatedly adding to this; join at the end
			params = []
			for mode in modeDisplay:
				if mode[1] and adding != "+":
					adding = "+"
					modestring.append("+")
				elif not mode[1] and adding != "-":
					adding = "-"
					modestring.append("-")
				modestring.append(mode[2])
				if mode[3]:
					params.append(mode[3])
			modeLine = "{} {}".format("".join(modestring), " ".join(params)) if params else "".join(modestring)
			user.sendMessage("MODE", modeLine, prefix=user.prefix())

	def processParams(self, user, params):
		if user.registered > 0:
			user.sendMessage(irc.ERR_NOTREGISTERED, "MODE", ":You have not registered")
			return {}
		if not params:
			user.sendMessage(irc.ERR_NEEDMOREPARAMS, "MODE", ":Not enough parameters")
			return {}
		if params[0] in self.ircd.users:
			modeChanges = []
			if len(params) > 1 and params[1]:
				adding = True
				current_param = 2
				for mode in params[1]:
					if mode == "+":
						adding = True
					elif mode == "-":
						adding = False
					else:
						if mode not in self.ircd.user_mode_type:
							user.sendMessage(irc.ERR_UMODEUNKNOWNFLAG, mode, ":is unknown mode char to me")
							continue
						mode_type = self.ircd.user_mode_type[mode]
						if mode_type == 1 or (adding and mode_type == 2) or (mode_type == 0 and len(params) > current_param):
							if len(params) <= current_param:
								continue # Mode must have param that wasn't provided
							modeChanges.append([mode_type, adding, mode, params[current_param]])
							current_param += 1
						else:
							modeChanges.append([mode_type, adding, mode, None])
			return {
				"user": user,
				"targetuser": self.ircd.users[params[0]],
				"modes": modeChanges
			}
		if params[0] in self.ircd.channels:
			cdata = self.ircd.channels[params[0]]
			modeChanges = []
			if len(params) > 1 and params[1]:
				if params[0] not in user.channels or not user.hasAccess(cdata.name, self.ircd.servconfig["channel_mode_level"]):
					user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, params[0], ":You must have channel operator access to set channel modes")
					return {}
				adding = True
				current_param = 2
				for mode in params[1]:
					if mode == "+":
						adding = True
					elif mode == "-":
						adding = False
					else:
						if mode not in self.ircd.channel_mode_type:
							user.sendMessage(irc.ERR_UNKNOWNMODE, mode, ":is unknown mode char to me")
							continue
						mode_type = self.ircd.channel_mode_type[mode]
						if mode_type == -1 or (mode_type == 0 and len(params) > current_param) or mode_type == 1 or (adding and mode_type == 2):
							if len(params) <= current_param:
								continue # Mode must have param that wasn't provided
							modeChanges.append([mode_type, adding, mode, params[current_param]])
							current_param += 1
						else:
							modeChanges.append([mode_type, adding, mode, None])
			return {
				"user": user,
				"targetchan": cdata,
				"modes": modeChanges
			}
		user.sendMessage(irc.ERR_NOSUCHNICK, params[0], ":No such nick/channel")
		return {}

class Spawner(object):
	def __init__(self, ircd):
		self.ircd = ircd

	def spawn(self):
		if "channel_mode_level" not in self.ircd.servconfig:
			self.ircd.servconfig["channel_mode_level"] = "o"
		return {
			"commands": {
				"MODE": ModeCommand()
			}
		}

	def cleanup(self):
		del self.ircd.commands["MODE"]<commit_msg>Allow non-chanops to list modes<commit_after>from twisted.words.protocols import irc
from txircd.modbase import Command
from txircd.utils import irc_lower, epoch

class ModeCommand(Command):
	def onUse(self, user, data):
		if "targetchan" in data:
			self.chanUse(user, data["targetchan"], data["modes"])
		elif "targetuser" in data:
			if user == data["targetuser"]:
				self.userUse(user, data["modes"])
			else:
				user.sendMessage(irc.ERR_USERSDONTMATCH, ":Can't operate on modes for other users")

	def chanUse(self, user, channel, modes):
		if not modes:
			user.sendMessage(irc.RPL_CHANNELMODEIS, channel.name, channel.modeString(user))
			user.sendMessage(irc.RPL_CREATIONTIME, channel.name, str(epoch(channel.created)))
			return
		modeDisplay = []
		for modedata in modes:
			modetype, adding, mode, param = modedata
			if not (modetype == 0 and param is None): # ignore these checks for listing list modes
				if not adding and mode not in channel.mode:
					continue # channel does not have mode set; cannot remove
				if adding:
					allowed, param = self.ircd.channel_modes[modetype][mode].checkSet(user, channel, param)
					if not allowed:
						continue
				else:
					allowed, param = self.ircd.channel_modes[modetype][mode].checkUnset(user, channel, param)
					if not allowed:
						continue
			modedata[3] = param # update the param in modedata so that the displayed mode change is shown correctly
			if modetype == -1:
				if param not in self.ircd.users:
					continue
				udata = self.ircd.users[param]
				if channel.name not in udata.channels:
					continue
				if adding:
					status = udata.channels[channel.name]["status"]
					statusList = list(status)
					for index, statusLevel in enumerate(status):
						if self.ircd.prefixes[statusLevel][1] < self.ircd.prefixes[mode][1]:
							statusList.insert(index, mode)
							break
					udata.channels[channel.name]["status"] = "".join(statusList)
					modeDisplay.append(modedata)
				else:
					if mode in udata.channels[channel.name]["status"]:
						udata.channels[channel.name]["status"].remove(mode)
						modeDisplay.append(modedata)
			elif modetype == 0:
				if not param:
					self.ircd.channel_modes[modetype][mode].showParam(user, channel)
				elif adding:
					if mode not in channel.mode:
						channel.mode[mode] = []
					if param not in channel.mode[mode]:
						channel.mode[mode].append(param)
						modeDisplay.append(modedata)
				else:
					if mode not in channel.mode:
						continue
					if param in channel.mode[mode]:
						channel.mode[mode].remove(param)
						modeDisplay.append(modedata)
						if not channel.mode[mode]:
							del channel.mode[mode]
			else:
				if adding:
					if mode in channel.mode and param == channel.mode[mode]:
						continue
					channel.mode[mode] = param
					modeDisplay.append(modedata)
				else:
					if mode not in channel.mode:
						continue
					if modetype == 1 and param != channel.mode[mode]:
						continue
					del channel.mode[mode]
					modeDisplay.append(modedata)
		if modeDisplay:
			adding = None
			modestring = [] # use an array of characters since we're repeatedly adding to this; join at the end
			params = []
			for mode in modeDisplay:
				if mode[1] and adding != "+":
					adding = "+"
					modestring.append("+")
				elif not mode[1] and adding != "-":
					adding = "-"
					modestring.append("-")
				modestring.append(mode[2])
				if mode[3]:
					params.append(mode[3])
			modeLine = "{} {}".format("".join(modestring), " ".join(params)) if params else "".join(modestring)
			for udata in channel.users:
				udata.sendMessage("MODE", modeLine, to=channel.name, prefix=user.prefix())

	def userUse(self, user, modes):
		if not modes:
			user.sendMessage(irc.RPL_UMODEIS, user.modeString(user))
			return
		modeDisplay = []
		for modedata in modes:
			modetype, adding, mode, param = modedata
			if not (modetype == 0 and param is None): # ignore these checks for listing list modes
				if not adding and mode not in user.mode:
					continue # Cannot unset mode that's not set
				if adding:
					allowed, param = self.ircd.user_modes[modetype][mode].checkSet(user, user, param)
					if not allowed:
						continue
				else:
					allowed, param = self.ircd.user_modes[modetype][mode].checkUnset(user, user, param)
					if not allowed:
						continue
			modedata[3] = param # update the param in modedata so that the displayed mode change is shown correctly
			if modetype == 0:
				if not param:
					self.ircd.user_modes[modetype][mode].showParam(user, user)
				elif adding:
					if mode not in user.mode:
						user.mode[mode] = []
					if param not in user.mode[mode]:
						user.mode[mode].append(param)
						modeDisplay.append(modedata)
				else:
					if mode not in user.mode:
						continue
					if param in user.mode[mode]:
						user.mode[mode].remove(param)
						modeDisplay.append(modedata)
						if not user.mode[mode]:
							del user.mode[mode]
			else:
				if adding:
					if mode in user.mode and param == user.mode[mode]:
						continue
					user.mode[mode] = param
					modeDisplay.append(modedata)
				else:
					if mode not in user.mode:
						continue
					if modetype == 1 and param != user.mode[mode]:
						continue
					del user.mode[mode]
					modeDisplay.append(modedata)
		if modeDisplay:
			adding = None
			modestring = [] # use an array of characters since we're repeatedly adding to this; join at the end
			params = []
			for mode in modeDisplay:
				if mode[1] and adding != "+":
					adding = "+"
					modestring.append("+")
				elif not mode[1] and adding != "-":
					adding = "-"
					modestring.append("-")
				modestring.append(mode[2])
				if mode[3]:
					params.append(mode[3])
			modeLine = "{} {}".format("".join(modestring), " ".join(params)) if params else "".join(modestring)
			user.sendMessage("MODE", modeLine, prefix=user.prefix())

	def processParams(self, user, params):
		if user.registered > 0:
			user.sendMessage(irc.ERR_NOTREGISTERED, "MODE", ":You have not registered")
			return {}
		if not params:
			user.sendMessage(irc.ERR_NEEDMOREPARAMS, "MODE", ":Not enough parameters")
			return {}
		if params[0] in self.ircd.users:
			modeChanges = []
			if len(params) > 1 and params[1]:
				adding = True
				current_param = 2
				for mode in params[1]:
					if mode == "+":
						adding = True
					elif mode == "-":
						adding = False
					else:
						if mode not in self.ircd.user_mode_type:
							user.sendMessage(irc.ERR_UMODEUNKNOWNFLAG, mode, ":is unknown mode char to me")
							continue
						mode_type = self.ircd.user_mode_type[mode]
						if mode_type == 1 or (adding and mode_type == 2) or (mode_type == 0 and len(params) > current_param):
							if len(params) <= current_param:
								continue # Mode must have param that wasn't provided
							modeChanges.append([mode_type, adding, mode, params[current_param]])
							current_param += 1
						else:
							modeChanges.append([mode_type, adding, mode, None])
			return {
				"user": user,
				"targetuser": self.ircd.users[params[0]],
				"modes": modeChanges
			}
		if params[0] in self.ircd.channels:
			cdata = self.ircd.channels[params[0]]
			modeChanges = []
			if len(params) > 1 and params[1]:
				if params[0] not in user.channels or not user.hasAccess(cdata.name, self.ircd.servconfig["channel_mode_level"]):
					if len(params) > 2:
						user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, params[0], ":You must have channel operator access to set channel modes")
						return {}
					for mode in params[1]:
						if mode == "+" or mode == "-":
							continue
						if self.ircd.channel_mode_type[mode] != 0:
							user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, params[0], ":You must have channel operator access to set channel modes")
							return {} # user is trying to change modes; abort
					# User isn't trying to change modes; go ahead and continue
				adding = True
				current_param = 2
				for mode in params[1]:
					if mode == "+":
						adding = True
					elif mode == "-":
						adding = False
					else:
						if mode not in self.ircd.channel_mode_type:
							user.sendMessage(irc.ERR_UNKNOWNMODE, mode, ":is unknown mode char to me")
							continue
						mode_type = self.ircd.channel_mode_type[mode]
						if mode_type == -1 or (mode_type == 0 and len(params) > current_param) or mode_type == 1 or (adding and mode_type == 2):
							if len(params) <= current_param:
								continue # Mode must have param that wasn't provided
							modeChanges.append([mode_type, adding, mode, params[current_param]])
							current_param += 1
						else:
							modeChanges.append([mode_type, adding, mode, None])
			return {
				"user": user,
				"targetchan": cdata,
				"modes": modeChanges
			}
		user.sendMessage(irc.ERR_NOSUCHNICK, params[0], ":No such nick/channel")
		return {}

class Spawner(object):
	def __init__(self, ircd):
		self.ircd = ircd

	def spawn(self):
		if "channel_mode_level" not in self.ircd.servconfig:
			self.ircd.servconfig["channel_mode_level"] = "o"
		return {
			"commands": {
				"MODE": ModeCommand()
			}
		}

	def cleanup(self):
		del self.ircd.commands["MODE"]<|endoftext|>


<commit_before>"""
Add columns arbitrarily to the Agronomic sheets
"""

import gdata.docs.client
import ConfigParser
import util

config = ConfigParser.ConfigParser()
config.read('mytokens.cfg')

# Get me a client, stat
spr_client = util.get_spreadsheet_client(config)
docs_client = util.get_docs_client(config)

query = gdata.docs.client.DocsQuery(show_collections='true', title='Agronomic Data')
feed = docs_client.GetAllResources(query=query)

newcols = [
           ['AGR35', '[35] Soybean grain biomass total carbon at R8', 'kg ha-1'],
           ['AGR36', '[36] Soybean grain biomass total nitrogen at R8', 'kg ha-1'],
           ['AGR37', '[37] Cover crop (rye) and weedy biomass in late fall', 'kg ha-1'],
           ['AGR38', '[38] Weedy biomass (only) in late fall', 'kg ha-1']
           ]

for entry in feed:
    spreadkey = entry.id.text.split("/")[-1][14:]
    feed2 = spr_client.GetWorksheets( spreadkey )
    for entry2 in feed2.entry:
        worksheet = entry2.id.text.split("/")[-1]
        print 'Processing %s WRK: %s Title: %s' % (entry.title.text,
                                                   worksheet, entry2.title.text),
        feed3 = spr_client.get_list_feed(spreadkey, worksheet)
        row = feed3.entry[0]
        data = row.to_dict()
        if data.get('agr6') is None and data.get('agr7') is None:
            print ' ... not found!'
            continue

        plusone = int(entry2.col_count.text) + 4
        entry2.col_count.text = str(plusone)
        spr_client.update(entry2)

        # Add a column?
        for i in range(len(newcols)):
            cell = spr_client.get_cell(spreadkey, worksheet,1, plusone-i)
            cell.cell.input_value = newcols[i][0]
            spr_client.update(cell)

            cell = spr_client.get_cell(spreadkey, worksheet,2, plusone-i)
            cell.cell.input_value = newcols[i][1]
            spr_client.update(cell)

            cell = spr_client.get_cell(spreadkey, worksheet,3, plusone-i)
            cell.cell.input_value = newcols[i][2]
            spr_client.update(cell)

        print ' ... updated'
        #sys.exit()

<commit_msg>add some cols to NAEW sheets<commit_after>"""
Add columns arbitrarily to the Agronomic sheets
"""

import gdata.docs.client
import ConfigParser
import util

config = ConfigParser.ConfigParser()
config.read('mytokens.cfg')

# Get me a client, stat
spr_client = util.get_spreadsheet_client(config)
docs_client = util.get_docs_client(config)

query = gdata.docs.client.DocsQuery(show_collections='true', title='NAEW Agronomic Data')
feed = docs_client.GetAllResources(query=query)

newcols = [
    ['AGR44', '[44] Red clover or mixed cover crop biomass in spring of spreadsheet year', 'kg ha-1'],
    ['AGR45', '[45] Red clover or mixed cover crop total nitrogen in spring of spreadsheet year', 'kg ha-1'],
    ['AGR46', '[46] Red clover or mixed cover crop total carbon in spring of spreadsheet year', 'kg ha-1'],
           ]

for entry in feed:
    spreadkey = entry.id.text.split("/")[-1][14:]
    feed2 = spr_client.GetWorksheets( spreadkey )
    for entry2 in feed2.entry:
        worksheet = entry2.id.text.split("/")[-1]
        print 'Processing %s WRK: %s Title: %s' % (entry.title.text,
                                                   worksheet, entry2.title.text),
        feed3 = spr_client.get_list_feed(spreadkey, worksheet)
        row = feed3.entry[0]
        data = row.to_dict()
        if data.get('agr41') is None and data.get('agr42') is None:
            print ' ... not found!'
            continue

        plusone = int(entry2.col_count.text) + 3
        entry2.col_count.text = str(plusone)
        spr_client.update(entry2)

        # Add a column?
        for i in range(len(newcols)):
            cell = spr_client.get_cell(spreadkey, worksheet,1, plusone-i)
            cell.cell.input_value = newcols[i][0]
            spr_client.update(cell)

            cell = spr_client.get_cell(spreadkey, worksheet,2, plusone-i)
            cell.cell.input_value = newcols[i][1]
            spr_client.update(cell)

            cell = spr_client.get_cell(spreadkey, worksheet,3, plusone-i)
            cell.cell.input_value = newcols[i][2]
            spr_client.update(cell)

        print ' ... updated'
        #sys.exit()

<|endoftext|>


<commit_before># Handle all HTTP / ESI API work:
# input validation, correctly navigating ESI endpoints, rate limiting, async retrieval

# import aiohttp

ESI_URL = 'https://esi.tech.ccp.is/latest/markets/'

URL_OPTS = {
    'orders': '{}/orders/',
    'history': '{}/history/',
    'citadels': 'structures/{}/'
}

def url_format(num_id, req_type):
    return ESI_URL + URL_OPTS[req_type].format(num_id)

# replace the functionality below to use aiohttp instead of requests-futures
'''
import logging
import sys

import concurrent.futures as cf
from requests_futures.sessions import FuturesSession

TEST_URL = 'https://crest-tq.eveonline.com/market/10000002/orders/all/?page='

logging.basicConfig(
    stream=sys.stderr, level=logging.INFO,
    format='%(relativeCreated)s %(message)s',
    )

session = FuturesSession(max_workers=10)
futures = []

data = []

logging.info('Sending requests to CREST API')
for n in range(1, 20):
    try_url = TEST_URL + str(n)
    future = session.get(try_url)
    futures.append(future)

logging.info('Requests sent; awaiting responses')

for future in cf.as_completed(futures, timeout=15):
    res = future.result()
    if 'items' in res.json() and len(res.json()['items']) > 0:
        logging.info('OK: [%s items] %s' % (len(res.json()['items']), res.url))
        data.append(res.json()['items'])
    elif 'items' in res.json() and len(res.json()['items']) == 0:
        logging.info('ERROR: [data is empty] %s' % res.url)
    else:
        logging.info('ERROR: [unknown exception]')

logging.info('Process complete')
'''<commit_msg>clean out io/http.py<commit_after># Handle all HTTP / ESI API work:
# input validation, correctly navigating ESI endpoints, rate limiting, async retrieval

# import aiohttp

ESI_URL = 'https://esi.tech.ccp.is/latest/markets/'

URL_OPTS = {
    'orders': '{}/orders/',
    'history': '{}/history/',
    'citadels': 'structures/{}/'
}

def url_define(num_id, req_type):
    return ESI_URL + URL_OPTS[req_type].format(num_id)<|endoftext|>


<commit_before># 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.

import functools

from babel.core import Locale
from pyramid import viewderivers
from pyramid.i18n import TranslationStringFactory, default_locale_negotiator
from pyramid.threadlocal import get_current_request

from warehouse.cache.http import add_vary

KNOWN_LOCALES = {
    identifier: Locale.parse(identifier, sep="_")
    for identifier in [
        "en",  # English
        "es",  # Spanish
        "fr",  # French
        "ja",  # Japanese
        "pt_BR",  # Brazilian Portugeuse
        "uk",  # Ukranian
        "el",  # Greek
        "de",  # German
        "zh_Hans",  # Simplified Chinese
        "ru",  # Russian
        "he",  # Hebrew
    ]
}

LOCALE_ATTR = "_LOCALE_"

_translation_factory = TranslationStringFactory("messages")

class LazyString:
    def __init__(self, fn, *args, **kwargs):
        self.fn = fn
        self.args = args
        self.mapping = kwargs.get("mapping", {})
        self.kwargs = kwargs

    def __json__(self, request):
        return str(self)

    def __mod__(self, new_mapping):
        mapping = self.mapping.copy()
        mapping.update(new_mapping)
        return LazyString(self.fn, *self.args, mapping=new_mapping, **self.kwargs)

    def __str__(self):
        return self.fn(*self.args, **self.kwargs)

def _locale(request):
    """
    Gets a babel.core:Locale() object for this request.
    """
    return KNOWN_LOCALES.get(request.locale_name, KNOWN_LOCALES["en"])

def _negotiate_locale(request):
    locale_name = getattr(request, LOCALE_ATTR, None)
    if locale_name is not None:
        return locale_name

    locale_name = request.params.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    locale_name = request.cookies.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    if not request.accept_language:
        return default_locale_negotiator(request)

    return request.accept_language.best_match(
        tuple(KNOWN_LOCALES.keys()), default_match=default_locale_negotiator(request)
    )

def _localize(request, message, **kwargs):
    """
    To be used on the request directly, e.g. `request._(message)`
    """
    return request.localizer.translate(_translation_factory(message, **kwargs))

def localize(message, **kwargs):
    """
    To be used when we don't have the request context, e.g.
    `from warehouse.i18n import localize as _`
    """

    def _lazy_localize(message, **kwargs):
        request = get_current_request()
        return _localize(request, message, **kwargs)

    return LazyString(_lazy_localize, message, **kwargs)

class InvalidLocalizer:
    def _fail(self):
        raise RuntimeError("Cannot use localizer without has_translations=True")

    @property
    def locale_name(self):
        self._fail()

    def pluralize(self, *args, **kwargs):
        self._fail()

    def translate(self, *args, **kwargs):
        self._fail()

def translated_view(view, info):
    if info.options.get("has_translations"):
        # If this page can be translated, then we'll add a Vary: PyPI-Locale
        #   Vary header.
        # Note: This will give weird results if hitting PyPI directly instead of through
        #       the Fastly VCL which sets PyPI-Locale.
        return add_vary("PyPI-Locale")(view)
    elif info.exception_only:
        return view
    else:
        # If we're not using translations on this view, then we'll wrap the view
        # with a wrapper that just ensures that the localizer cannot be used.
        @functools.wraps(view)
        def wrapped(context, request):
            # This whole method is a little bit of an odd duck, we want to make
            # sure that we don't actually *access* request.localizer, because
            # doing so triggers the machinery to create a new localizer. So
            # instead we will dig into the request object __dict__ to
            # effectively do the same thing, just without triggering an access
            # on request.localizer.

            # Save the original session so that we can restore it once the
            # inner views have been called.
            nothing = object()
            original_localizer = request.__dict__.get("localizer", nothing)

            # This particular view hasn't been set to allow access to the
            # translations, so we'll just assign an InvalidLocalizer to
            # request.localizer
            request.__dict__["localizer"] = InvalidLocalizer()

            try:
                # Invoke the real view
                return view(context, request)
            finally:
                # Restore the original session so that things like
                # pyramid_debugtoolbar can access it.
                if original_localizer is nothing:
                    del request.__dict__["localizer"]
                else:
                    request.__dict__["localizer"] = original_localizer

        return wrapped

translated_view.options = {"has_translations"}

def includeme(config):
    # Add the request attributes
    config.add_request_method(_locale, name="locale", reify=True)
    config.add_request_method(_localize, name="_")

    # Register our translation directory.
    config.add_translation_dirs("warehouse:locale/")

    config.set_locale_negotiator(_negotiate_locale)

    # Register our i18n/l10n filters for Jinja2
    filters = config.get_settings().setdefault("jinja2.filters", {})
    filters.setdefault("format_date", "warehouse.i18n.filters:format_date")
    filters.setdefault("format_datetime", "warehouse.i18n.filters:format_datetime")
    filters.setdefault(
        "format_rfc822_datetime", "warehouse.i18n.filters:format_rfc822_datetime"
    )
    filters.setdefault("format_number", "warehouse.i18n.filters:format_number")

    jglobals = config.get_settings().setdefault("jinja2.globals", {})
    jglobals.setdefault("KNOWN_LOCALES", "warehouse.i18n:KNOWN_LOCALES")

    config.add_view_deriver(
        translated_view, over="rendered_view", under=viewderivers.INGRESS
    )
<commit_msg>Add eo locale to KNOWN_LOCALES mapping (#9245)<commit_after># 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.

import functools

from babel.core import Locale
from pyramid import viewderivers
from pyramid.i18n import TranslationStringFactory, default_locale_negotiator
from pyramid.threadlocal import get_current_request

from warehouse.cache.http import add_vary

KNOWN_LOCALES = {
    identifier: Locale.parse(identifier, sep="_")
    for identifier in [
        "en",  # English
        "es",  # Spanish
        "fr",  # French
        "ja",  # Japanese
        "pt_BR",  # Brazilian Portugeuse
        "uk",  # Ukranian
        "el",  # Greek
        "de",  # German
        "zh_Hans",  # Simplified Chinese
        "ru",  # Russian
        "he",  # Hebrew
        "eo",  # Esperanto
    ]
}

LOCALE_ATTR = "_LOCALE_"

_translation_factory = TranslationStringFactory("messages")

class LazyString:
    def __init__(self, fn, *args, **kwargs):
        self.fn = fn
        self.args = args
        self.mapping = kwargs.get("mapping", {})
        self.kwargs = kwargs

    def __json__(self, request):
        return str(self)

    def __mod__(self, new_mapping):
        mapping = self.mapping.copy()
        mapping.update(new_mapping)
        return LazyString(self.fn, *self.args, mapping=new_mapping, **self.kwargs)

    def __str__(self):
        return self.fn(*self.args, **self.kwargs)

def _locale(request):
    """
    Gets a babel.core:Locale() object for this request.
    """
    return KNOWN_LOCALES.get(request.locale_name, KNOWN_LOCALES["en"])

def _negotiate_locale(request):
    locale_name = getattr(request, LOCALE_ATTR, None)
    if locale_name is not None:
        return locale_name

    locale_name = request.params.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    locale_name = request.cookies.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    if not request.accept_language:
        return default_locale_negotiator(request)

    return request.accept_language.best_match(
        tuple(KNOWN_LOCALES.keys()), default_match=default_locale_negotiator(request)
    )

def _localize(request, message, **kwargs):
    """
    To be used on the request directly, e.g. `request._(message)`
    """
    return request.localizer.translate(_translation_factory(message, **kwargs))

def localize(message, **kwargs):
    """
    To be used when we don't have the request context, e.g.
    `from warehouse.i18n import localize as _`
    """

    def _lazy_localize(message, **kwargs):
        request = get_current_request()
        return _localize(request, message, **kwargs)

    return LazyString(_lazy_localize, message, **kwargs)

class InvalidLocalizer:
    def _fail(self):
        raise RuntimeError("Cannot use localizer without has_translations=True")

    @property
    def locale_name(self):
        self._fail()

    def pluralize(self, *args, **kwargs):
        self._fail()

    def translate(self, *args, **kwargs):
        self._fail()

def translated_view(view, info):
    if info.options.get("has_translations"):
        # If this page can be translated, then we'll add a Vary: PyPI-Locale
        #   Vary header.
        # Note: This will give weird results if hitting PyPI directly instead of through
        #       the Fastly VCL which sets PyPI-Locale.
        return add_vary("PyPI-Locale")(view)
    elif info.exception_only:
        return view
    else:
        # If we're not using translations on this view, then we'll wrap the view
        # with a wrapper that just ensures that the localizer cannot be used.
        @functools.wraps(view)
        def wrapped(context, request):
            # This whole method is a little bit of an odd duck, we want to make
            # sure that we don't actually *access* request.localizer, because
            # doing so triggers the machinery to create a new localizer. So
            # instead we will dig into the request object __dict__ to
            # effectively do the same thing, just without triggering an access
            # on request.localizer.

            # Save the original session so that we can restore it once the
            # inner views have been called.
            nothing = object()
            original_localizer = request.__dict__.get("localizer", nothing)

            # This particular view hasn't been set to allow access to the
            # translations, so we'll just assign an InvalidLocalizer to
            # request.localizer
            request.__dict__["localizer"] = InvalidLocalizer()

            try:
                # Invoke the real view
                return view(context, request)
            finally:
                # Restore the original session so that things like
                # pyramid_debugtoolbar can access it.
                if original_localizer is nothing:
                    del request.__dict__["localizer"]
                else:
                    request.__dict__["localizer"] = original_localizer

        return wrapped

translated_view.options = {"has_translations"}

def includeme(config):
    # Add the request attributes
    config.add_request_method(_locale, name="locale", reify=True)
    config.add_request_method(_localize, name="_")

    # Register our translation directory.
    config.add_translation_dirs("warehouse:locale/")

    config.set_locale_negotiator(_negotiate_locale)

    # Register our i18n/l10n filters for Jinja2
    filters = config.get_settings().setdefault("jinja2.filters", {})
    filters.setdefault("format_date", "warehouse.i18n.filters:format_date")
    filters.setdefault("format_datetime", "warehouse.i18n.filters:format_datetime")
    filters.setdefault(
        "format_rfc822_datetime", "warehouse.i18n.filters:format_rfc822_datetime"
    )
    filters.setdefault("format_number", "warehouse.i18n.filters:format_number")

    jglobals = config.get_settings().setdefault("jinja2.globals", {})
    jglobals.setdefault("KNOWN_LOCALES", "warehouse.i18n:KNOWN_LOCALES")

    config.add_view_deriver(
        translated_view, over="rendered_view", under=viewderivers.INGRESS
    )
<|endoftext|>


<commit_before>from sqlalchemy import *
from sqlalchemy.test import *
from sqlalchemy.pool import QueuePool

class QueuePoolTest(TestBase, AssertsExecutionResults):
    class Connection(object):
        def rollback(self):
            pass

        def close(self):
            pass

    def setup(self):
        global pool
        pool = QueuePool(creator=self.Connection,
                         pool_size=3, max_overflow=-1,
                         use_threadlocal=True)

    @profiling.function_call_count(64, {'2.4': 42, '2.7':59,
                                            '2.7+cextension':59,
                                            '3.0':65, '3.1':65})
    def test_first_connect(self):
        conn = pool.connect()

    def test_second_connect(self):
        conn = pool.connect()
        conn.close()

        @profiling.function_call_count(32, {'2.4': 21, '2.7':29,
                                            '2.7+cextension':29})
        def go():
            conn2 = pool.connect()
            return conn2
        c2 = go()

    def test_second_samethread_connect(self):
        conn = pool.connect()

        @profiling.function_call_count(5, {'2.4': 3, '3.0':6, '3.1':6})
        def go():
            return pool.connect()
        c2 = go()

<commit_msg>up the variance on these as the call counts are very low and things wiggle around even between 2.6.4/2.6.5<commit_after>from sqlalchemy import *
from sqlalchemy.test import *
from sqlalchemy.pool import QueuePool

class QueuePoolTest(TestBase, AssertsExecutionResults):
    class Connection(object):
        def rollback(self):
            pass

        def close(self):
            pass

    def setup(self):
        global pool
        pool = QueuePool(creator=self.Connection,
                         pool_size=3, max_overflow=-1,
                         use_threadlocal=True)

    @profiling.function_call_count(64, {'2.4': 42, '2.7':59,
                                            '2.7+cextension':59,
                                            '3.0':65, '3.1':65},
                                            variance=.10)
    def test_first_connect(self):
        conn = pool.connect()

    def test_second_connect(self):
        conn = pool.connect()
        conn.close()

        @profiling.function_call_count(32, {'2.4': 21, '2.7':29,
                                            '2.7+cextension':29},
                                            variance=.10)
        def go():
            conn2 = pool.connect()
            return conn2
        c2 = go()

    def test_second_samethread_connect(self):
        conn = pool.connect()

        @profiling.function_call_count(5, {'2.4': 3, '3.0':6, '3.1':6})
        def go():
            return pool.connect()
        c2 = go()

<|endoftext|>


<commit_before>import SokoMap

class HashTable:
    def __init__(self):
        self.table = []

    def checkAdd(self, sokomap):
        keyList = []
        keyList.extend(sokomap.getBlocks())
        keyList.extend(sokomap.getPlayer())
        key = str(keyList)
        if key in self.table:
            return True
        else:
            self.table.append(key)
            return False

<commit_msg>Convert HashTable to use a dict.<commit_after>import SokoMap

class HashTable:
    def __init__(self):
        self.table = {}

    def checkAdd(self, sokomap):
        keyList = []
        keyList.extend(sokomap.getBlocks())
        keyList.extend(sokomap.getPlayer())
        key = str(keyList)
        if key in self.table:
            return True
        else:
            self.table[key] = True
            return False

<|endoftext|>


<commit_before><commit_msg>Path: Add basic support for arc and circular edges<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python2.5
#
# Copyright 2011 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.

"""Module for the org applications.
"""

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

from django import forms as django_forms
from django.utils.translation import ugettext

from soc.views import forms
from soc.views import survey
from soc.views.helper import lists

from soc.logic import cleaning
from soc.models.org_app_record import OrgAppRecord
from soc.models.org_app_survey import OrgAppSurvey
from soc.views.readonly_template import SurveyRecordReadOnlyTemplate

from soc.views.base import SiteRequestHandler

class OrgAppEditForm(forms.SurveyEditForm):
  """Form to create/edit organization application survey.
  """

  class Meta:
    model = OrgAppSurvey
    css_prefix = 'org-app-edit'
    exclude = ['scope', 'author', 'program', 'created_by', 'modified_by']

class OrgAppTakeForm(forms.SurveyTakeForm):
  """Form for would-be organization admins to apply for the program.
  """

  backup_admin_id = django_forms.CharField(
      label=ugettext('Backup Admin'), required=True,
      help_text=ugettext('The Link ID of the user who will serve as the '
                         'backup admin for this organization.'))

  def __init__(self, survey, bound_class_field, *args, **kwargs):
    super(OrgAppTakeForm, self).__init__(survey, bound_class_field, *args,
                                         **kwargs)
    if self.instance:
      self.fields['backup_admin_id'].initial = \
          self.instance.backup_admin.link_id

    # not marked required by data model for backwards compatibility
    self.fields['org_id'].required = True

  class Meta:
    model = OrgAppRecord
    css_prefix = 'org-app-record'
    exclude = ['main_admin', 'backup_admin', 'status', 'user', 'survey',
               'created', 'modified']

  def clean_org_id(self):
    org_id = cleaning.clean_link_id('org_id')(self)

    if not org_id:
      # manual required check, see Issue 1291
      raise django_forms.ValidationError('This field is required.')

    q = OrgAppRecord.all()
    q.filter('survey', self.survey)
    q.filter('org_id', org_id)

    org_app = q.get()

    if org_app:
      # If we are creating a new org app it is a duplicate, if we are editing
      # an org app we must check if the one we found has a different key.
      if (not self.instance) or (org_app.key() != self.instance.key()):
        raise django_forms.ValidationError('This ID has already been taken.')

    return org_id

  def clean_backup_admin_id(self):
    backup_admin = cleaning.clean_existing_user('backup_admin_id')(self)

    if not self.instance:
      cleaning.clean_users_not_same('backup_admin_id')(self)
    elif self.instance.main_admin.key() == backup_admin.key():
      raise django_forms.ValidationError(
          'You cannot enter the person who created the application here.')

    self.cleaned_data['backup_admin'] = backup_admin
    return backup_admin

  def clean(self):
    cleaned_data = self.cleaned_data

    # pop our custom id field if exists
    if 'backup_admin_id' in cleaned_data:
      cleaned_data.pop('backup_admin_id')

    return cleaned_data

class OrgAppRecordsList(SiteRequestHandler):
  """View for listing all records of a Organization Applications.
  """

  def checkAccess(self):
    """Defines access checks for this list, all hosts should be able to see it.
    """
    self.check.isHost()
    self.mutator.orgAppFromKwargs()

  def context(self):
    """Returns the context of the page to render.
    """
    record_list = self._createOrgAppsList()

    page_name = ugettext('Records - %s' % (self.data.org_app.title))
    context = {
        'page_name': page_name,
        'record_list': record_list,
        }
    return context

  def jsonContext(self):
    """Handler for JSON requests.
    """
    idx = lists.getListIndex(self.request)
    if idx == 0:
      record_list = self._createOrgAppsList()
      return record_list.listContentResponse(
          self.request, prefetch=['org', 'project']).content()
    else:
      super(OrgAppRecordsList, self).jsonContext()

  def _createOrgAppsList(self):
    """Creates a SurveyRecordList for the requested survey.
    """
    record_list = survey.SurveyRecordList(
        self.data, self.data.org_app, OrgAppRecord, idx=0)

    return record_list

  def templatePath(self):
    return 'v2/modules/gsoc/student_eval/record_list.html'

class OrgAppReadOnlyTemplate(SurveyRecordReadOnlyTemplate):
  """Template to construct readonly organization application record.
  """

  class Meta:
    model = OrgAppRecord
    css_prefix = 'org-app-show'
    fields = ['org_id', 'name', 'description', 'home_page', 'license',
              'agreed_to_admin_agreement']
    survey_name = 'Organization Application'
<commit_msg>Added myself org app authors for future reference.<commit_after>#!/usr/bin/env python2.5
#
# Copyright 2011 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.

"""Module for the org applications.
"""

__authors__ = [
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from django import forms as django_forms
from django.utils.translation import ugettext

from soc.views import forms
from soc.views import survey
from soc.views.helper import lists

from soc.logic import cleaning
from soc.models.org_app_record import OrgAppRecord
from soc.models.org_app_survey import OrgAppSurvey
from soc.views.readonly_template import SurveyRecordReadOnlyTemplate

from soc.views.base import SiteRequestHandler

class OrgAppEditForm(forms.SurveyEditForm):
  """Form to create/edit organization application survey.
  """

  class Meta:
    model = OrgAppSurvey
    css_prefix = 'org-app-edit'
    exclude = ['scope', 'author', 'program', 'created_by', 'modified_by']

class OrgAppTakeForm(forms.SurveyTakeForm):
  """Form for would-be organization admins to apply for the program.
  """

  backup_admin_id = django_forms.CharField(
      label=ugettext('Backup Admin'), required=True,
      help_text=ugettext('The Link ID of the user who will serve as the '
                         'backup admin for this organization.'))

  def __init__(self, survey, bound_class_field, *args, **kwargs):
    super(OrgAppTakeForm, self).__init__(survey, bound_class_field, *args,
                                         **kwargs)
    if self.instance:
      self.fields['backup_admin_id'].initial = \
          self.instance.backup_admin.link_id

    # not marked required by data model for backwards compatibility
    self.fields['org_id'].required = True

  class Meta:
    model = OrgAppRecord
    css_prefix = 'org-app-record'
    exclude = ['main_admin', 'backup_admin', 'status', 'user', 'survey',
               'created', 'modified']

  def clean_org_id(self):
    org_id = cleaning.clean_link_id('org_id')(self)

    if not org_id:
      # manual required check, see Issue 1291
      raise django_forms.ValidationError('This field is required.')

    q = OrgAppRecord.all()
    q.filter('survey', self.survey)
    q.filter('org_id', org_id)

    org_app = q.get()

    if org_app:
      # If we are creating a new org app it is a duplicate, if we are editing
      # an org app we must check if the one we found has a different key.
      if (not self.instance) or (org_app.key() != self.instance.key()):
        raise django_forms.ValidationError('This ID has already been taken.')

    return org_id

  def clean_backup_admin_id(self):
    backup_admin = cleaning.clean_existing_user('backup_admin_id')(self)

    if not self.instance:
      cleaning.clean_users_not_same('backup_admin_id')(self)
    elif self.instance.main_admin.key() == backup_admin.key():
      raise django_forms.ValidationError(
          'You cannot enter the person who created the application here.')

    self.cleaned_data['backup_admin'] = backup_admin
    return backup_admin

  def clean(self):
    cleaned_data = self.cleaned_data

    # pop our custom id field if exists
    if 'backup_admin_id' in cleaned_data:
      cleaned_data.pop('backup_admin_id')

    return cleaned_data

class OrgAppRecordsList(SiteRequestHandler):
  """View for listing all records of a Organization Applications.
  """

  def checkAccess(self):
    """Defines access checks for this list, all hosts should be able to see it.
    """
    self.check.isHost()
    self.mutator.orgAppFromKwargs()

  def context(self):
    """Returns the context of the page to render.
    """
    record_list = self._createOrgAppsList()

    page_name = ugettext('Records - %s' % (self.data.org_app.title))
    context = {
        'page_name': page_name,
        'record_list': record_list,
        }
    return context

  def jsonContext(self):
    """Handler for JSON requests.
    """
    idx = lists.getListIndex(self.request)
    if idx == 0:
      record_list = self._createOrgAppsList()
      return record_list.listContentResponse(
          self.request, prefetch=['org', 'project']).content()
    else:
      super(OrgAppRecordsList, self).jsonContext()

  def _createOrgAppsList(self):
    """Creates a SurveyRecordList for the requested survey.
    """
    record_list = survey.SurveyRecordList(
        self.data, self.data.org_app, OrgAppRecord, idx=0)

    return record_list

  def templatePath(self):
    return 'v2/modules/gsoc/student_eval/record_list.html'

class OrgAppReadOnlyTemplate(SurveyRecordReadOnlyTemplate):
  """Template to construct readonly organization application record.
  """

  class Meta:
    model = OrgAppRecord
    css_prefix = 'org-app-show'
    fields = ['org_id', 'name', 'description', 'home_page', 'license',
              'agreed_to_admin_agreement']
    survey_name = 'Organization Application'
<|endoftext|>


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

print "Coco1"
print 45
print 46
print 47
print 48
print 40
print 40
print 42<commit_msg>Ajout ligne 10<commit_after>#!/usr/bin/env python

print "Coco"
print 45
print 46
print 47
print 48
print 40
print 40
print 42<|endoftext|>