<commit_before># Copyright 2008 Google Inc.
#
# 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.

"""Django template library for Rietveld."""

import cgi
import logging

from google.appengine.api import memcache
from google.appengine.api import users

import django.template
import django.utils.safestring
from django.core.urlresolvers import reverse

import models

register = django.template.Library()

@register.filter
def show_user(email, arg=None, autoescape=None, memcache_results=None):
  """Render a link to the user's dashboard, with text being the nickname."""
  if isinstance(email, users.User):
    email = email.email()
  if not arg:
    user = users.get_current_user()
    if user is not None and email == user.email():
      return 'me'

  if memcache_results is not None:
    ret = memcache_results.get(email)
  else:
    ret = memcache.get('show_user:' + email)

  if ret is None:
    logging.debug('memcache miss for %r', email)
    account = models.Account.get_account_for_email(email)
    if account is not None and account.user_has_selected_nickname:
      ret = ('%s' %
             (reverse('codereview.views.show_user', args=[account.nickname]),
              cgi.escape(account.nickname)))
    else:
      # No account.  Let's not create a hyperlink.
      nick = email
      if '@' in nick:
        nick = nick.split('@', 1)[0]
      ret = cgi.escape(nick)

    memcache.add('show_user:%s' % email, ret, 300)

    # populate the dict with the results, so same user in the list later
    # will have a memcache "hit" on "read".
    if memcache_results is not None:
      memcache_results[email] = ret

  return django.utils.safestring.mark_safe(ret)

@register.filter
def show_users(email_list, arg=None):
  """Render list of links to each user's dashboard."""
  if not email_list:
    # Don't wast time calling memcache with an empty list.
    return ''
  memcache_results = memcache.get_multi(email_list, key_prefix='show_user:')
  return django.utils.safestring.mark_safe(', '.join(
      show_user(email, arg, memcache_results=memcache_results)
      for email in email_list))

class UrlAppendViewSettingsNode(django.template.Node):
  """Django template tag that appends context and column_width parameter.

  This tag should be used after any URL that requires view settings.

  Example:

  The tag tries to get the current column width and context from the
  template context and if they're present it returns '?param1&param2'
  otherwise it returns an empty string.
  """

  def __init__(self):
    """Constructor."""
    self.view_context = django.template.Variable('context')
    self.view_colwidth = django.template.Variable('column_width')

  def render(self, context):
    """Returns a HTML fragment."""
    url_params = []

    current_context = -1
    try:
      current_context = self.view_context.resolve(context)
    except django.template.VariableDoesNotExist:
      pass
    if current_context is None:
      url_params.append('context=')
    elif isinstance(current_context, int) and current_context > 0:
      url_params.append('context=%d' % current_context)

    current_colwidth = None
    try:
      current_colwidth = self.view_colwidth.resolve(context)
    except django.template.VariableDoesNotExist:
      pass
    if current_colwidth is not None:
      url_params.append('column_width=%d' % current_colwidth)

    if url_params:
      return '?%s' % '&'.join(url_params)
    return ''

@register.tag
def urlappend_view_settings(parser, token):
  """The actual template tag."""
  return UrlAppendViewSettingsNode()

def get_nickname(email, never_me=False, request=None):
  """Return a nickname for an email address.

  If 'never_me' is True, 'me' is not returned if 'email' belongs to the
  current logged in user. If 'request' is a HttpRequest, it is used to
  cache the nickname returned by models.Account.get_nickname_for_email().
  """
  if isinstance(email, users.User):
    email = email.email()
  if not never_me:
    if request is not None:
      user = request.user
    else:
      user = users.get_current_user()
    if user is not None and email == user.email():
      return 'me'

  if request is None:
    logging.warn("request not found in template context.")
    return models.Account.get_nickname_for_email(email)
  else:
    if getattr(request, '_nicknames', None) is None:
      request._nicknames = {}
    if email in request._nicknames:
      return request._nicknames[email]
    result = models.Account.get_nickname_for_email(email)
    request._nicknames[email] = result
  return result

class NicknameNode(django.template.Node):
  """Renders a nickname for a given email address.

  The return value is cached if a HttpRequest is available in a
  'request' template variable.

  The template tag accepts one or two arguments. The first argument is
  the template variable for the email address. If the optional second
  argument evaluates to True, 'me' as nickname is never rendered.

  Example usage:
    {% cached_nickname msg.sender %}
    {% cached_nickname msg.sender True %}
  """

  def __init__(self, email_address, never_me=''):
    """Constructor.

    'email_address' is the name of the template variable that holds an
    email address. If 'never_me' evaluates to True, 'me' won't be returned.
    """
    self.email_address = django.template.Variable(email_address)
    self.never_me = bool(never_me.strip())
    self.is_multi = False

  def render(self, context):
    try:
      email = self.email_address.resolve(context)
    except django.template.VariableDoesNotExist:
      return ''
    request = context.get('request')
    if self.is_multi:
      return ', '.join(get_nickname(e, self.never_me, request) for e in email)
    return get_nickname(email, self.never_me, request)

@register.tag
def nickname(parser, token):
  """Almost the same as nickname filter but the result is cached."""
  try:
    tag_name, email_address, never_me = token.split_contents()
  except ValueError:
    try:
      tag_name, email_address = token.split_contents()
      never_me = ''
    except ValueError:
      raise django.template.TemplateSyntaxError(
        "%r requires exactly one or two arguments" % token.contents.split()[0])
  return NicknameNode(email_address, never_me)

@register.tag
def nicknames(parser, token):
  """Wrapper for nickname tag with is_multi flag enabled."""
  node = nickname(parser, token)
  node.is_multi = True
  return node
<commit_msg>Remove warning message from library.get_nickname().<commit_after># Copyright 2008 Google Inc.
#
# 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.

"""Django template library for Rietveld."""

import cgi
import logging

from google.appengine.api import memcache
from google.appengine.api import users

import django.template
import django.utils.safestring
from django.core.urlresolvers import reverse

import models

register = django.template.Library()

@register.filter
def show_user(email, arg=None, autoescape=None, memcache_results=None):
  """Render a link to the user's dashboard, with text being the nickname."""
  if isinstance(email, users.User):
    email = email.email()
  if not arg:
    user = users.get_current_user()
    if user is not None and email == user.email():
      return 'me'

  if memcache_results is not None:
    ret = memcache_results.get(email)
  else:
    ret = memcache.get('show_user:' + email)

  if ret is None:
    logging.debug('memcache miss for %r', email)
    account = models.Account.get_account_for_email(email)
    if account is not None and account.user_has_selected_nickname:
      ret = ('%s' %
             (reverse('codereview.views.show_user', args=[account.nickname]),
              cgi.escape(account.nickname)))
    else:
      # No account.  Let's not create a hyperlink.
      nick = email
      if '@' in nick:
        nick = nick.split('@', 1)[0]
      ret = cgi.escape(nick)

    memcache.add('show_user:%s' % email, ret, 300)

    # populate the dict with the results, so same user in the list later
    # will have a memcache "hit" on "read".
    if memcache_results is not None:
      memcache_results[email] = ret

  return django.utils.safestring.mark_safe(ret)

@register.filter
def show_users(email_list, arg=None):
  """Render list of links to each user's dashboard."""
  if not email_list:
    # Don't wast time calling memcache with an empty list.
    return ''
  memcache_results = memcache.get_multi(email_list, key_prefix='show_user:')
  return django.utils.safestring.mark_safe(', '.join(
      show_user(email, arg, memcache_results=memcache_results)
      for email in email_list))

class UrlAppendViewSettingsNode(django.template.Node):
  """Django template tag that appends context and column_width parameter.

  This tag should be used after any URL that requires view settings.

  Example:

  The tag tries to get the current column width and context from the
  template context and if they're present it returns '?param1&param2'
  otherwise it returns an empty string.
  """

  def __init__(self):
    """Constructor."""
    self.view_context = django.template.Variable('context')
    self.view_colwidth = django.template.Variable('column_width')

  def render(self, context):
    """Returns a HTML fragment."""
    url_params = []

    current_context = -1
    try:
      current_context = self.view_context.resolve(context)
    except django.template.VariableDoesNotExist:
      pass
    if current_context is None:
      url_params.append('context=')
    elif isinstance(current_context, int) and current_context > 0:
      url_params.append('context=%d' % current_context)

    current_colwidth = None
    try:
      current_colwidth = self.view_colwidth.resolve(context)
    except django.template.VariableDoesNotExist:
      pass
    if current_colwidth is not None:
      url_params.append('column_width=%d' % current_colwidth)

    if url_params:
      return '?%s' % '&'.join(url_params)
    return ''

@register.tag
def urlappend_view_settings(parser, token):
  """The actual template tag."""
  return UrlAppendViewSettingsNode()

def get_nickname(email, never_me=False, request=None):
  """Return a nickname for an email address.

  If 'never_me' is True, 'me' is not returned if 'email' belongs to the
  current logged in user. If 'request' is a HttpRequest, it is used to
  cache the nickname returned by models.Account.get_nickname_for_email().
  """
  if isinstance(email, users.User):
    email = email.email()
  if not never_me:
    if request is not None:
      user = request.user
    else:
      user = users.get_current_user()
    if user is not None and email == user.email():
      return 'me'

  if request is None:
    return models.Account.get_nickname_for_email(email)
  else:
    if getattr(request, '_nicknames', None) is None:
      request._nicknames = {}
    if email in request._nicknames:
      return request._nicknames[email]
    result = models.Account.get_nickname_for_email(email)
    request._nicknames[email] = result
  return result

class NicknameNode(django.template.Node):
  """Renders a nickname for a given email address.

  The return value is cached if a HttpRequest is available in a
  'request' template variable.

  The template tag accepts one or two arguments. The first argument is
  the template variable for the email address. If the optional second
  argument evaluates to True, 'me' as nickname is never rendered.

  Example usage:
    {% cached_nickname msg.sender %}
    {% cached_nickname msg.sender True %}
  """

  def __init__(self, email_address, never_me=''):
    """Constructor.

    'email_address' is the name of the template variable that holds an
    email address. If 'never_me' evaluates to True, 'me' won't be returned.
    """
    self.email_address = django.template.Variable(email_address)
    self.never_me = bool(never_me.strip())
    self.is_multi = False

  def render(self, context):
    try:
      email = self.email_address.resolve(context)
    except django.template.VariableDoesNotExist:
      return ''
    request = context.get('request')
    if self.is_multi:
      return ', '.join(get_nickname(e, self.never_me, request) for e in email)
    return get_nickname(email, self.never_me, request)

@register.tag
def nickname(parser, token):
  """Almost the same as nickname filter but the result is cached."""
  try:
    tag_name, email_address, never_me = token.split_contents()
  except ValueError:
    try:
      tag_name, email_address = token.split_contents()
      never_me = ''
    except ValueError:
      raise django.template.TemplateSyntaxError(
        "%r requires exactly one or two arguments" % token.contents.split()[0])
  return NicknameNode(email_address, never_me)

@register.tag
def nicknames(parser, token):
  """Wrapper for nickname tag with is_multi flag enabled."""
  node = nickname(parser, token)
  node.is_multi = True
  return node
<|endoftext|>


<commit_before>"""
Django settings for cognitive atlas project.

Generated by 'django-admin startproject' using Django 1.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import sys
import os
from os.path import join, abspath, dirname

from py2neo import Graph
from py2neo.neo4j import authenticate

# PATH vars
here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here(".")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)

sys.path.insert(0, root('apps'))

#graph = Graph("http://graphdb:7474/db/data/")

# Just for local development - will read this from secrets
authenticate("localhost:7474", "neo4j", "noodles")
graph = Graph()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cognitive.apps.main',
    'cognitive.apps.atlas',
    'cognitive.apps.users',
]

THIRD_PARTY_APPS = [
    'rest_framework'
]

INSTALLED_APPS += THIRD_PARTY_APPS

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'cognitive.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.core.context_processors.i18n',
                'django.core.context_processors.media',
                'django.core.context_processors.static',
                'django.core.context_processors.tz',
                'django.core.context_processors.request',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.static',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'cognitive.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'cognitive.db'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

MEDIA_ROOT = '/var/www/assets'
MEDIA_URL = '/assets/'
STATIC_ROOT = '/var/www/static'
STATIC_URL = '/static/'

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

CRISPY_TEMPLATE_PACK = 'bootstrap3'

CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            }
}

# Bogus secret key.
try:
    from .secrets import *
except ImportError:
    from .bogus_secrets import *

# Local settings
try:
    from .local_settings import *
except ImportError:
    pass
<commit_msg>removed graph db settings from base setting file, moved to local settings in earlier commit<commit_after>"""
Django settings for cognitive atlas project.

Generated by 'django-admin startproject' using Django 1.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import sys
import os
from os.path import join, abspath, dirname

from py2neo import Graph
from py2neo.neo4j import authenticate

# PATH vars
here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here(".")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)

sys.path.insert(0, root('apps'))

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cognitive.apps.main',
    'cognitive.apps.atlas',
    'cognitive.apps.users',
]

THIRD_PARTY_APPS = [
    'rest_framework'
]

INSTALLED_APPS += THIRD_PARTY_APPS

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'cognitive.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.core.context_processors.i18n',
                'django.core.context_processors.media',
                'django.core.context_processors.static',
                'django.core.context_processors.tz',
                'django.core.context_processors.request',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.static',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'cognitive.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'cognitive.db'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

MEDIA_ROOT = '/var/www/assets'
MEDIA_URL = '/assets/'
STATIC_ROOT = '/var/www/static'
STATIC_URL = '/static/'

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

CRISPY_TEMPLATE_PACK = 'bootstrap3'

CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            }
}

# Bogus secret key.
try:
    from .secrets import *
except ImportError:
    from .bogus_secrets import *

# Local settings
try:
    from .local_settings import *
except ImportError:
    pass
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Andy Sayler
# Summer 2014
# Univerity of Colorado

import urllib

import moodle.ws

import config

EXTRA_REPORTER_SCHEMA = ['asn_id']
_MAX_COMMENT_LEN = 2000

class RepModMoodleError(Exception):
    """Base class for RepMod Moodle Exceptions"""

    def __init__(self, *args, **kwargs):
        super(RepModMoodleError, self).__init__(*args, **kwargs)

class Reporter(object):

    def __init__(self, rpt):

        # Check Input
        if rpt['mod'] != 'moodle':
            raise RepModMoodleError("Repmod requires report with repmod 'moodle'")

        # Call Parent
        super(Reporter, self).__init__()

        # Save vars
        self.asn_id = rpt['asn_id']

        # Setup Vars
        self.host = config.REPMOD_MOODLE_HOST

        # Setup WS
        self.ws = moodle.ws.WS(self.host)
        self.ws.authenticate(config.REPMOD_MOODLE_USERNAME,
                             config.REPMOD_MOODLE_PASSWORD,
                             config.REPMOD_MOODLE_SERVICE)

    def file_report(self, user, grade, comment):

        if user['auth'] != 'moodle':
            raise RepModMoodleError("Repmod requires users with authmod 'moodle'")

        # Clean Comment
        comment = comment.encode('ascii', 'replace')
        comment = comment[(len(comment)/4):(len(comment)/2)]

        warning = "\nWARNING: Output Truncated"
        max_len = (_MAX_COMMENT_LEN - len(warning))
        if len(comment) > max_len:
            comment = comment[:max_len]
            comment += warning

        asn_id = self.asn_id
        usr_id = user['moodle_id']
        self.ws.mod_assign_save_grade(asn_id, usr_id, grade, comment=comment)
<commit_msg>Bisection Search - 3/8th<commit_after># -*- coding: utf-8 -*-

# Andy Sayler
# Summer 2014
# Univerity of Colorado

import urllib

import moodle.ws

import config

EXTRA_REPORTER_SCHEMA = ['asn_id']
_MAX_COMMENT_LEN = 2000

class RepModMoodleError(Exception):
    """Base class for RepMod Moodle Exceptions"""

    def __init__(self, *args, **kwargs):
        super(RepModMoodleError, self).__init__(*args, **kwargs)

class Reporter(object):

    def __init__(self, rpt):

        # Check Input
        if rpt['mod'] != 'moodle':
            raise RepModMoodleError("Repmod requires report with repmod 'moodle'")

        # Call Parent
        super(Reporter, self).__init__()

        # Save vars
        self.asn_id = rpt['asn_id']

        # Setup Vars
        self.host = config.REPMOD_MOODLE_HOST

        # Setup WS
        self.ws = moodle.ws.WS(self.host)
        self.ws.authenticate(config.REPMOD_MOODLE_USERNAME,
                             config.REPMOD_MOODLE_PASSWORD,
                             config.REPMOD_MOODLE_SERVICE)

    def file_report(self, user, grade, comment):

        if user['auth'] != 'moodle':
            raise RepModMoodleError("Repmod requires users with authmod 'moodle'")

        # Clean Comment
        comment = comment.encode('ascii', 'replace')
        start = len(comment)/4
        end = start + len(comment)/8
        comment = comment[start:end]

        warning = "\nWARNING: Output Truncated"
        max_len = (_MAX_COMMENT_LEN - len(warning))
        if len(comment) > max_len:
            comment = comment[:max_len]
            comment += warning

        asn_id = self.asn_id
        usr_id = user['moodle_id']
        self.ws.mod_assign_save_grade(asn_id, usr_id, grade, comment=comment)
<|endoftext|>


<commit_before>import platform
import sys

__version_info__ = (0, 6, 7)
__version__ = '.'.join(map(str, __version_info__))

SERVER_ID = ','.join([platform.system(),
                      platform.release(),
                      'UPnP/1.0,Coherence UPnP framework',
                      __version__])

try:
    from twisted import version as twisted_version
    from twisted.web import version as twisted_web_version
    from twisted.python.versions import Version
except ImportError, exc:
    # log error to stderr, might be useful for debugging purpose
    sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
                     "Please install them.\n")
    raise

try:
    if twisted_version < Version("twisted", 2, 5, 0):
        raise ImportError("Twisted >= 2.5 is required. Please install it.")

except ImportError, exc:
    # log error to stderr, might be useful for debugging purpose
    for arg in exc.args:
        sys.stderr.write("%s\n" % arg)
    raise
<commit_msg>Switch to PEP 440 compliant version string and bump to 0.6.7.dev0.<commit_after>import platform
import sys

__version__ = "0.6.7.dev0"

SERVER_ID = ','.join([platform.system(),
                      platform.release(),
                      'UPnP/1.0,Coherence UPnP framework',
                      __version__])

try:
    from twisted import version as twisted_version
    from twisted.web import version as twisted_web_version
    from twisted.python.versions import Version
except ImportError, exc:
    # log error to stderr, might be useful for debugging purpose
    sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
                     "Please install them.\n")
    raise

try:
    if twisted_version < Version("twisted", 2, 5, 0):
        raise ImportError("Twisted >= 2.5 is required. Please install it.")

except ImportError, exc:
    # log error to stderr, might be useful for debugging purpose
    for arg in exc.args:
        sys.stderr.write("%s\n" % arg)
    raise
<|endoftext|>


<commit_before>import datetime

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import signals

from comics.core.models import Comic

class Set(models.Model):
    name = models.SlugField(max_length=100, unique=True,
        help_text='The set identifier')
    add_new_comics = models.BooleanField(default=False,
        help_text='Automatically add new comics to the set')
    hide_empty_comics = models.BooleanField(default=False,
        help_text='Hide comics without matching releases from view')
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField()
    last_loaded = models.DateTimeField()
    comics = models.ManyToManyField(Comic)

    class Meta:
        db_table = 'comics_set'
        ordering = ['name']

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('namedset-latest', kwargs={'namedset': self.name})

    def get_feed_url(self):
        return reverse('namedset-feed', kwargs={'namedset': self.name})

    def get_slug(self):
        return self.name
    def set_slug(self, slug):
        self.name = slug
    slug = property(get_slug, set_slug)

    def set_loaded(self):
        self.last_loaded = datetime.datetime.now()
        self.save()

class UserSet(models.Model):
    user = models.ForeignKey(User)
    add_new_comics = models.BooleanField(default=False,
        help_text='Automatically add new comics to the set')
    hide_empty_comics = models.BooleanField(default=False,
        help_text='Hide comics without matching releases from view')
    last_modified = models.DateTimeField()
    last_loaded = models.DateTimeField()
    comics = models.ManyToManyField(Comic)

    class Meta:
        db_table = 'comics_userset'

    def __unicode__(self):
        return u'Comic set for %s' % self.user

    def set_loaded(self):
        self.last_loaded = datetime.datetime.now()
        self.save()

def create_user_set_for_new_users_callback(sender, **kwargs):
    if sender == User and kwargs['created']:
        user_set = UserSet(user=kwargs['instance'])
        user_set.save()

signals.post_save.connect(create_user_set_for_new_users_callback, sender=User)

def add_new_comic_to_user_sets_callback(sender, **kwargs):
    if sender == Comic and kwargs['created']:
        # Add new comic to all sets with add_new_comics=True
        for user_set in UserSet.objects.filter(add_new_comics=True):
            user_set.comics.add(kwargs['instance'])
        # Update number_of_sets on the new comic
        kwargs['instance'].number_of_sets = UserSet.objects.filter(
            add_new_comics=True).count()
        kwargs['instance'].save()

signals.post_save.connect(add_new_comic_to_user_sets_callback, sender=Comic)
<commit_msg>Remove post_save hook on User creation which breaks superuser creation. The new middleware will create the user set when needed<commit_after>import datetime

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import signals

from comics.core.models import Comic

class Set(models.Model):
    name = models.SlugField(max_length=100, unique=True,
        help_text='The set identifier')
    add_new_comics = models.BooleanField(default=False,
        help_text='Automatically add new comics to the set')
    hide_empty_comics = models.BooleanField(default=False,
        help_text='Hide comics without matching releases from view')
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField()
    last_loaded = models.DateTimeField()
    comics = models.ManyToManyField(Comic)

    class Meta:
        db_table = 'comics_set'
        ordering = ['name']

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('namedset-latest', kwargs={'namedset': self.name})

    def get_feed_url(self):
        return reverse('namedset-feed', kwargs={'namedset': self.name})

    def get_slug(self):
        return self.name
    def set_slug(self, slug):
        self.name = slug
    slug = property(get_slug, set_slug)

    def set_loaded(self):
        self.last_loaded = datetime.datetime.now()
        self.save()

class UserSet(models.Model):
    user = models.ForeignKey(User)
    add_new_comics = models.BooleanField(default=False,
        help_text='Automatically add new comics to the set')
    hide_empty_comics = models.BooleanField(default=False,
        help_text='Hide comics without matching releases from view')
    last_modified = models.DateTimeField()
    last_loaded = models.DateTimeField()
    comics = models.ManyToManyField(Comic)

    class Meta:
        db_table = 'comics_userset'

    def __unicode__(self):
        return u'Comic set for %s' % self.user

    def set_loaded(self):
        self.last_loaded = datetime.datetime.now()
        self.save()

def add_new_comic_to_user_sets_callback(sender, **kwargs):
    if sender == Comic and kwargs['created']:
        # Add new comic to all sets with add_new_comics=True
        for user_set in UserSet.objects.filter(add_new_comics=True):
            user_set.comics.add(kwargs['instance'])
        # Update number_of_sets on the new comic
        kwargs['instance'].number_of_sets = UserSet.objects.filter(
            add_new_comics=True).count()
        kwargs['instance'].save()

signals.post_save.connect(add_new_comic_to_user_sets_callback, sender=Comic)
<|endoftext|>


<commit_before># created 1999/03/13, Greg Ward

__revision__ = "$Id$"

import sys, string
from distutils.core import Command
from distutils.util import copy_tree

class install_py (Command):

    description = "install pure Python modules"

    user_options = [
        ('install-dir=', 'd', "directory to install to"),
        ('build-dir=','b', "build directory (where to install from)"),
        ('compile', 'c', "compile .py to .pyc"),
        ('optimize', 'o', "compile .py to .pyo (optimized)"),
        ]

    def initialize_options (self):
        # let the 'install' command dictate our installation directory
        self.install_dir = None
        self.build_dir = None
        self.compile = 1
        self.optimize = 1

    def finalize_options (self):

        # Get all the information we need to install pure Python modules
        # from the umbrella 'install' command -- build (source) directory,
        # install (target) directory, and whether to compile .py files.
        self.set_undefined_options ('install',
                                    ('build_lib', 'build_dir'),
                                    ('install_lib', 'install_dir'),
                                    ('compile_py', 'compile'),
                                    ('optimize_py', 'optimize'))

    def run (self):

        # Make sure we have "built" all pure Python modules first
        self.run_peer ('build_py')

        # Install everything: simply dump the entire contents of the build
        # directory to the installation directory (that's the beauty of
        # having a build directory!)
        outfiles = self.copy_tree (self.build_dir, self.install_dir)

        # (Optionally) compile .py to .pyc
        # XXX hey! we can't control whether we optimize or not; that's up
        # to the invocation of the current Python interpreter (at least
        # according to the py_compile docs).  That sucks.

        if self.compile:
            from py_compile import compile

            for f in outfiles:
                # XXX can't assume this filename mapping! (what if
                # we're running under "python -O"?)

                # only compile the file if it is actually a .py file
                if f[-3:] == '.py':
                    out_fn = string.replace (f, '.py', '.pyc')

                    self.make_file (f, out_fn, compile, (f,),
                                    "byte-compiling %s" % f,
                                    "byte-compilation of %s skipped" % f)

        # XXX ignore self.optimize for now, since we don't really know if
        # we're compiling optimally or not, and couldn't pick what to do
        # even if we did know.  ;-(

    # run ()

# class InstallPy
<commit_msg>Renamed install_py.py to install_lib.py, since it now handles installing all Python modules, pure and extensions.<commit_after><|endoftext|>


<commit_before>import docker
import sys
from pprint import pprint
from tabulate import tabulate
import json
from datetime import datetime
import pretty
import re
import yaml

from dkr_core import cmd_to_json

def command() -> list:
    return ['container', 'c']

def help_summary(name: str) -> str:
    if name == 'c':
        return 'Alias for "container"'
    return "Various commands for containers"

def import_command(docker_client: docker.Client, args, state: dict):
    args.set_defaults(func=default)
    subparsers = args.add_subparsers(title="Container Commands")

    list_cmd = subparsers.add_parser('list', help="Lists containers")
    list_cmd.add_argument('-a', '--all', action='store_true', help='Include non-running containers')
    list_cmd.add_argument('-q', '--quiet', action='store_true', help='Only print IDs')
    list_cmd.add_argument('--json', action='store_true', help='Render all as json')
    list_cmd.add_argument('--pprint', action='store_true', help='Dump contents using python\'s pprint function')
    list_cmd.set_defaults(func=list_containers)

    inspect_cmd = subparsers.add_parser('inspect', help="Inspects the detail of an container")
    inspect_cmd.add_argument('container', help="The name or ID of the Container")
    inspect_cmd.add_argument('--json', action='store_true', help='Render all as json')
    inspect_cmd.add_argument('--pprint', action='store_true', help='Dump contents using python\'s pprint function')
    inspect_cmd.set_defaults(func=inspect_container)

    create_cmd = subparsers.add_parser('create', help="Create a new container")
    create_cmd.add_argument('--id', action='store_true', help="Display the ID of the created name instead of the name")
    # create_cmd.add_argument('-p', '--publish', nargs='*', help="Publish a container's port(s) to the host")
    create_cmd.add_argument('-o', '--option', action='append', help="Include a docker create option. See https://github.com/leftstache/dkr/blob/master/README.md for more information.")
    create_cmd.add_argument('--name', help="The name of the container")
    create_cmd.add_argument('image', help="The image to create the container from")
    create_cmd.add_argument('cmd', nargs="*", help="The command to run")
    create_cmd.set_defaults(func=create_container)

    start_cmd = subparsers.add_parser('start', help="Start an existing container")
    start_cmd.add_argument('container', nargs="+", help="The container to start")
    start_cmd.set_defaults(func=start_container)

def default(client: docker.Client, args, state: dict):
    print("No valid command specified. `{} container -h` for help.".format(sys.argv[0]))

def list_containers(client: docker.Client, args, state: dict):
    containers = client.containers(all=args.all, quiet=args.quiet)

    if args.pprint:
        pprint(containers)
        return

    if args.json:
        print(json.dumps(containers, indent=4, sort_keys=True))
        return

    table = []
    if args.quiet:
        headers = ()
    else:
        headers = ["ID", "NAME", "IMAGE", "CMD", "CREATED", "STATUS", "PORTS"]

    for container in containers:
        row = []
        table.append(row)

        if args.quiet:
            row.append(container['Id'])
            continue

        row.append(container['Id'][:12])
        row.append(container['Names'][0][1:])
        row.append(container['Image'])
        row.append(container['Command'])

        created_seconds = container['Created']
        created_date = datetime.fromtimestamp(created_seconds)
        row.append(re.sub(r"\.[0-9]+", '', pretty.date(created_date, short=True)))

        row.append(container['Status'])

        ports = ""
        if 'Ports' in container:
            ports = ', '.join([_port_string(p) for p in container['Ports']])
        row.append(ports)

    print(tabulate(table, headers=headers, tablefmt="plain"))

def inspect_container(docker_client: docker.Client, args, state: dict):
    if args.container == '-':
        args.container = state['last_container']

    container = docker_client.inspect_container(args.container)

    state['last_container'] = container['Id']

    if args.pprint:
        pprint(container)
        return

    if args.json:
        print(json.dumps(container, indent=4))
        return

    print(yaml.dump(container, default_flow_style=False))

def create_container(docker_client: docker.Client, args, state: dict):
    image = args.image
    if image == '-':
        image = state['last_image']
    state['last_image'] = image

    cmd = args.cmd if args.cmd else None
    name = args.name if args.name else None

    docker_args = {}

    if 'option' in args:
        user_docker_options = cmd_to_json.parse_options(args.option)
        if user_docker_options:
            docker_args.update(user_docker_options)

    docker_args['image'] = image
    docker_args['command'] = cmd
    docker_args['name'] = name

    if 'host_config' in docker_args:
        docker_args['host_config'] = docker_client.create_host_config(**docker_args['host_config'])

    container = docker_client.create_container(**docker_args)

    state['last_container'] = container['Id']

    if container['Warnings']:
        print("WARNING:", container['Warnings'], file=sys.stderr)

    if args.id:
        print(container['Id'])
    else:
        container = docker_client.inspect_container(container)
        print(container['Name'][1:])

def start_container(docker_client: docker.Client, args, state: dict):
    containers = args.container

    container = None
    for container in containers:
        if container == '-':
            container = state['last_container']

            docker_client.start(container)

    state['last_container'] = container

def _port_string(port_obj: dict) -> str:
    ip = "{}:".format(port_obj['IP']) if 'IP' in port_obj else ''
    private_port = port_obj['PrivatePort'] if 'PrivatePort' in port_obj else ''
    public_port = port_obj['PublicPort'] if 'PublicPort' in port_obj else ''
    port_type = "/{}".format(port_obj['Type']) if 'Type' in port_obj else ''

    if private_port and public_port:
        return "{}{}->{}{}".format(ip, public_port, private_port, port_type)

    if private_port:
        return "{}{}{}".format(ip, private_port, port_type)

    return ""
<commit_msg>run creates and starts container<commit_after>import docker
import sys
from pprint import pprint
from tabulate import tabulate
import json
from datetime import datetime
import pretty
import re
import yaml

from dkr_core import cmd_to_json

def command() -> list:
    return ['container', 'c']

def help_summary(name: str) -> str:
    if name == 'c':
        return 'Alias for "container"'
    return "Various commands for containers"

def import_command(docker_client: docker.Client, args, state: dict):
    args.set_defaults(func=default)
    subparsers = args.add_subparsers(title="Container Commands")

    list_cmd = subparsers.add_parser('list', help="Lists containers")
    list_cmd.add_argument('-a', '--all', action='store_true', help='Include non-running containers')
    list_cmd.add_argument('-q', '--quiet', action='store_true', help='Only print IDs')
    list_cmd.add_argument('--json', action='store_true', help='Render all as json')
    list_cmd.add_argument('--pprint', action='store_true', help='Dump contents using python\'s pprint function')
    list_cmd.set_defaults(func=list_containers)

    inspect_cmd = subparsers.add_parser('inspect', help="Inspects the detail of an container")
    inspect_cmd.add_argument('container', help="The name or ID of the Container")
    inspect_cmd.add_argument('--json', action='store_true', help='Render all as json')
    inspect_cmd.add_argument('--pprint', action='store_true', help='Dump contents using python\'s pprint function')
    inspect_cmd.set_defaults(func=inspect_container)

    create_cmd = subparsers.add_parser('create', help="Create a new container")
    create_cmd.set_defaults(func=create_container)

    run_cmd = subparsers.add_parser('run', help="Create a new container and start it")
    run_cmd.set_defaults(func=run_container)

    for cmd in [create_cmd, run_cmd]:
        cmd.add_argument('--id', action='store_true', help="Display the ID of the created name instead of the name")
        # cmd.add_argument('-p', '--publish', nargs='*', help="Publish a container's port(s) to the host")
        cmd.add_argument('-o', '--option', action='append', help="Include a docker create option. See https://github.com/leftstache/dkr/blob/master/README.md for more information.")
        cmd.add_argument('--name', help="The name of the container")
        cmd.add_argument('image', help="The image to create the container from")
        cmd.add_argument('cmd', nargs="*", help="The command to run")

    start_cmd = subparsers.add_parser('start', help="Start an existing container")
    start_cmd.add_argument('container', nargs="+", help="The container to start")
    start_cmd.set_defaults(func=start_container)

def default(client: docker.Client, args, state: dict):
    print("No valid command specified. `{} container -h` for help.".format(sys.argv[0]))

def list_containers(client: docker.Client, args, state: dict):
    containers = client.containers(all=args.all, quiet=args.quiet)

    if args.pprint:
        pprint(containers)
        return

    if args.json:
        print(json.dumps(containers, indent=4, sort_keys=True))
        return

    table = []
    if args.quiet:
        headers = ()
    else:
        headers = ["ID", "NAME", "IMAGE", "CMD", "CREATED", "STATUS", "PORTS"]

    for container in containers:
        row = []
        table.append(row)

        if args.quiet:
            row.append(container['Id'])
            continue

        row.append(container['Id'][:12])
        row.append(container['Names'][0][1:])
        row.append(container['Image'])
        row.append(container['Command'])

        created_seconds = container['Created']
        created_date = datetime.fromtimestamp(created_seconds)
        row.append(re.sub(r"\.[0-9]+", '', pretty.date(created_date, short=True)))

        row.append(container['Status'])

        ports = ""
        if 'Ports' in container:
            ports = ', '.join([_port_string(p) for p in container['Ports']])
        row.append(ports)

    print(tabulate(table, headers=headers, tablefmt="plain"))

def inspect_container(docker_client: docker.Client, args, state: dict):
    if args.container == '-':
        args.container = state['last_container']

    container = docker_client.inspect_container(args.container)

    state['last_container'] = container['Id']

    if args.pprint:
        pprint(container)
        return

    if args.json:
        print(json.dumps(container, indent=4))
        return

    print(yaml.dump(container, default_flow_style=False))

def create_container(docker_client: docker.Client, args, state: dict):
    image = args.image
    if image == '-':
        image = state['last_image']
    state['last_image'] = image

    cmd = args.cmd if args.cmd else None
    name = args.name if args.name else None

    docker_args = {}

    if 'option' in args:
        user_docker_options = cmd_to_json.parse_options(args.option)
        if user_docker_options:
            docker_args.update(user_docker_options)

    docker_args['image'] = image
    docker_args['command'] = cmd
    docker_args['name'] = name

    if 'host_config' in docker_args:
        docker_args['host_config'] = docker_client.create_host_config(**docker_args['host_config'])

    container = docker_client.create_container(**docker_args)

    state['last_container'] = container['Id']

    if container['Warnings']:
        print("WARNING:", container['Warnings'], file=sys.stderr)

    if args.id:
        print(container['Id'])
    else:
        container = docker_client.inspect_container(container)
        print(container['Name'][1:])

def start_container(docker_client: docker.Client, args, state: dict):
    containers = args.container

    started = start_containers(containers, docker_client, state, print_update=True)
    state['last_container'] = started[-1]

def start_containers(containers, docker_client, state, print_update=False) -> list:
    result = []
    for container in containers:
        if container == '-':
            container = state['last_container']
        docker_client.start(container)
        if print_update:
            print(container)
        result.append(container)
    return result

def run_container(docker_client: docker.Client, args, state: dict):
    create_container(docker_client, args, state)
    start_containers([state['last_container']], docker_client, state, print_update=False)

def _port_string(port_obj: dict) -> str:
    ip = "{}:".format(port_obj['IP']) if 'IP' in port_obj else ''
    private_port = port_obj['PrivatePort'] if 'PrivatePort' in port_obj else ''
    public_port = port_obj['PublicPort'] if 'PublicPort' in port_obj else ''
    port_type = "/{}".format(port_obj['Type']) if 'Type' in port_obj else ''

    if private_port and public_port:
        return "{}{}->{}{}".format(ip, public_port, private_port, port_type)

    if private_port:
        return "{}{}{}".format(ip, private_port, port_type)

    return ""
<|endoftext|>


<commit_before>class opencv(CmakeWig):
	tarball_uri = 'https://github.com/itseez/opencv/archive/$RELEASE_VERSION$.tar.gz'
	last_release_version ='v3.2.0'
	git_uri = 'https://github.com/itseez/opencv'
	dependencies = ['pkg-config']
	optional_dependencies = ['ffmpeg', 'opencv_contrib', 'numpy']
	supported_features = ['python', 'cuda', 'shared', 'tests', 'examples', 'ffmpeg', 'contrib', 'ipp']
	default_features = ['+shared', '-tests', '-examples', '-cuda', '+python', '+ffmpeg', '-ipp']

	def switch_ipp(self, on):
		self.cmake_flags += ['-DWITH_IPP=%s' % S.ONOFF(on)]

	def switch_contrib_on(self):
		self.require('opencv_contrib')
		self.cmake_flags += ['-DOPENCV_EXTRA_MODULES_PATH="%s"' % os.path.join(self.paths.src_dir, '../opencv_contrib/modules')]

	def switch_ffmpeg_on(self):
		self.require('ffmpeg')
		self.before_configure += [S.export(S.PKG_CONFIG_PATH, "$PREFIX/lib/pkgconfig")]

	def switch_python_on(self):
		self.cmake_flags += ['-DPYTHON2_PACKAGES_PATH="%s"' % S.PYTHON_DEFAULT_MODULE_PATH]
		self.require('numpy')
		self.switch('python2', True)

	def switch_cuda(self, on):
		self.cmake_flags += ['-DWITH_CUDA=%s' % S.ONOFF(on)]

	def switch_shared(self, on):
		self.switch('SHARED_LIBS', on)

	def switch_tests(self, on):
		self.switch('TESTS', on)
		self.switch('PERF_TESTS', on)

	def switch_examples(self, on):
		self.switch('EXAMPLES', on)

	def switch(self, feat_name, on):
		if feat_name not in ['SHARED_LIBS', 'TESTS', 'PERF_TESTS', 'EXAMPLES']:
			feat_name = 'opencv_%s' % feat_name
		self.cmake_flags += ['-DBUILD_%s=%s' % (feat_name, S.ONOFF(on))]
<commit_msg>Update opencv.py<commit_after>class opencv(CmakeWig):
	tarball_uri = 'https://github.com/itseez/opencv/archive/$RELEASE_VERSION$.tar.gz'
	last_release_version ='v3.2.0'
	git_uri = 'https://github.com/itseez/opencv'
	dependencies = ['pkg-config']
	optional_dependencies = ['ffmpeg', 'opencv_contrib', 'numpy']
	supported_features = ['python', 'cuda', 'shared', 'tests', 'examples', 'ffmpeg', 'contrib', 'ipp']
	default_features = ['+shared', '-tests', '-examples', '-cuda', '+python', '+ffmpeg', '-ipp']

	def switch_ipp(self, on):
		self.cmake_flags += ['-DWITH_IPP=%s' % S.ONOFF(on)]

	def switch_contrib_on(self):
		self.require('opencv_contrib')
		self.cmake_flags += ['-DOPENCV_EXTRA_MODULES_PATH="%s"' % os.path.join(self.paths.src_dir, '../opencv_contrib/modules')]

	def switch_ffmpeg_on(self):
		self.require('ffmpeg')
		self.before_configure += [S.export(S.PKG_CONFIG_PATH, "$PREFIX/lib/pkgconfig")]

	def switch_python_on(self):
		self.cmake_flags += ['-DPYTHON2_PACKAGES_PATH="%s"' % os.path.join(P.python_root, P.python_prefix_scheme[0])]
		self.require('numpy')
		self.switch('python2', True)

	def switch_cuda(self, on):
		self.cmake_flags += ['-DWITH_CUDA=%s' % S.ONOFF(on)]

	def switch_shared(self, on):
		self.switch('SHARED_LIBS', on)

	def switch_tests(self, on):
		self.switch('TESTS', on)
		self.switch('PERF_TESTS', on)

	def switch_examples(self, on):
		self.switch('EXAMPLES', on)

	def switch(self, feat_name, on):
		if feat_name not in ['SHARED_LIBS', 'TESTS', 'PERF_TESTS', 'EXAMPLES']:
			feat_name = 'opencv_%s' % feat_name
		self.cmake_flags += ['-DBUILD_%s=%s' % (feat_name, S.ONOFF(on))]
<|endoftext|>


<commit_before>from datetime import datetime
import json
import logging
import re

from django.conf import settings
import httplib2
import oauth2 as oauth

from rhino.models import Object, Account, Person, UserStream, Media, UserReplyStream
import rhino.poll.embedlam

log = logging.getLogger(__name__)

def account_for_twitter_user(userdata, person=None):
    try:
        account = Account.objects.get(service='twitter.com', ident=str(userdata['id']))
    except Account.DoesNotExist:
        if person is None:
            avatar = Media(
                width=48,
                height=48,
                image_url=userdata['profile_image_url'],
            )
            avatar.save()
            person = Person(
                display_name=userdata['name'],
                avatar=avatar,
                permalink_url='http://twitter.com/%s' % userdata['screen_name'],
            )
            person.save()
        account = Account(
            service='twitter.com',
            ident=str(userdata['id']),
            display_name=userdata['name'],
            person=person,

            status_background_color=userdata['profile_background_color'],
            status_background_image_url=userdata['profile_background_image_url'],
            status_background_tile=userdata['profile_background_tile'],
        )
        account.save()

    return account

def tweet_html(tweetdata):
    tweet = tweetdata['text']
    if 'entities' not in tweetdata:
        return tweet

    mutations = list()
    for urldata in tweetdata['entities'].get('urls', ()):
        url = urldata['expanded_url'] or urldata['url']
        mutations.append({
            'indices': urldata['indices'],
            'html': """%s""" % (url, url),
        })
    for mentiondata in tweetdata['entities'].get('user_mentions', ()):
        mutations.append({
            'indices': mentiondata['indices'],
            'html': """@%(screen_name)s""" % mentiondata,
        })
    for tagdata in tweetdata['entities'].get('hashtags', ()):
        mutations.append({
            'indices': tagdata['indices'],
            'html': """#%(text)s""" % tagdata,
        })

    for mutation in sorted(mutations, key=lambda x: x['indices'][0], reverse=True):
        indices = mutation['indices']
        tweet = tweet[:indices[0]] + mutation['html'] + tweet[indices[1]:]

    return tweet

url_re = re.compile(r"""
    (?: (?<= \A )
      | (?<= [\s.:;?\-\]<\(] ) )

    https?://
    [-\w;/?:@&=+$.!~*'()%,#]+
    [\w/]

    (?= \Z | [\s\.,!:;?\-\[\]>\)] )
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

mention_re = re.compile(r"""
    (?: (?<= \A ) | (?<= \s ) )
    @ (\w+)
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

tag_re = re.compile(r"""
    (?: (?<= \A ) | (?<= \s ) )  # BOT or whitespace
    \# (\w\S*\w)      # tag
    (?<! 's )         # but don't end with 's
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

def synthesize_entities(tweetdata):
    if 'entities' in tweetdata:
        return

    tweettext = tweetdata['text']
    ents = {
        'urls': [],
        'hashtags': [],
        'user_mentions': [],
    }

    for match in url_re.finditer(tweettext):
        ents['urls'].append({
            'expanded_url': None,
            'url': match.group(0),
            'indices': [match.start(), match.end()],
        })

    for match in mention_re.finditer(tweettext):
        ents['user_mentions'].append({
            'id': None,  # we would have to get this if we ever used it
            'name': match.group(1),  # TODO: get this from the API? ugh
            'screen_name': match.group(1),
            'indices': [match.start(), match.end()],
        })

    for match in tag_re.finditer(tweettext):
        ents['hashtags'].append({
            'text': match.group(1),
            'indices': [match.start(), match.end()],
        })

    tweetdata['entities'] = ents

def object_from_twitpic_url(url):
    mo = re.match(r'http://twitpic\.com/(\w+)', url)
    twitpic_id = mo.group(1)

    try:
        return Object.objects.get(service='twitpic.com', foreign_id=twitpic_id)
    except Object.DoesNotExist:
        pass

    h = httplib2.Http()
    resp, content = h.request('http://api.twitpic.com/2/media/show.json?id=%s' % twitpic_id)

    picdata = json.loads(content)
    userdata = picdata['user']
    # ugh, why did they rename these
    userdata['id'] = userdata['twitter_id']
    userdata['screen_name'] = userdata['username']
    userdata['profile_image_url'] = userdata['avatar_url']

    pic = Media(
        image_url='http://twitpic.com/show/large/%s' % twitpic_id,
        width=int(picdata['width']),
        height=int(picdata['height']),
    )
    pic.save()
    obj = Object(
        service='twitpic.com',
        foreign_id=twitpic_id,
        render_mode='image',
        title=picdata['message'],
        image=pic,
        author=account_for_twitter_user(userdata),
        time=datetime.strptime(picdata['timestamp'], '%Y-%m-%d %H:%M:%S'),
        permalink_url=url,
    )
    obj.save()
    return obj

def raw_object_for_tweet(tweetdata, client):
    """Returns the normalized Object for the given tweetdata, and whether
    that Object represents that tweet or the thing the tweet is sharing.

    This is returned as a tuple containing (a) whether the tweet is a
    share, and (b) the ``rhino.models.Object`` reference for that tweet
    data, in that order.

    """
    try:
        return False, Object.objects.get(service='twitter.com', foreign_id=str(tweetdata['id']))
    except Object.DoesNotExist:
        pass

    log.debug('Making new tweet for %s status #%d', tweetdata['user']['screen_name'], tweetdata['id'])

    in_reply_to = None
    if tweetdata.get('in_reply_to_status_id'):
        # Uh oh, gotta get that tweet.
        # TODO: remove the mention from the front of the tweet
        next_tweetid = tweetdata['in_reply_to_status_id']
        try:
            in_reply_to = Object.objects.get(service='twitter.com', foreign_id=str(next_tweetid))
        except Object.DoesNotExist:
            resp, content = client.request('http://api.twitter.com/1/statuses/show/%d.json'
                % next_tweetid)
            if resp.status != 200:
                raise ValueError("Unexpected %d %s response fetching tweet #%s up a reply chain for "
                    "%s's timeline" % (resp.status, resp.reason, next_tweetid, account.display_name))

            next_tweetdata = json.loads(content)
            synthesize_entities(next_tweetdata)
            log.debug("    Let's make a new tweet for %s status #%d", next_tweetdata['user']['screen_name'], next_tweetdata['id'])
            # If it's really a share, this tweet is transitively in reply to the shared thing, so this is fine.
            really_a_share, in_reply_to = raw_object_for_tweet(next_tweetdata, client)

    # Is this something other than a status?
    elif len(tweetdata['entities']['urls']) == 1:
        about_urldata = tweetdata['entities']['urls'][0]
        about_url = about_urldata['expanded_url'] or about_urldata['url']

        try:
            in_reply_to = rhino.poll.embedlam.object_for_url(about_url)
        except ValueError, exc:
            log.debug(str(exc))
        else:
            # If the tweet was only the object's url and its title, make it a share.
            tweettext = tweetdata['text']
            link_starts, link_ends = about_urldata['indices']
            tweettext = tweettext[:link_starts] + tweettext[link_ends:]
            tweettext = tweettext.lower()
            if in_reply_to.title:
                tweettext = tweettext.replace(in_reply_to.title.lower(), '')
            tweettext = re.sub(r'\s', '', tweettext)

            if not tweettext:
                return True, in_reply_to

    tweet = Object(
        service='twitter.com',
        foreign_id=str(tweetdata['id']),
        render_mode='status',
        body=tweet_html(tweetdata),
        time=datetime.strptime(tweetdata['created_at'], '%a %b %d %H:%M:%S +0000 %Y'),
        permalink_url='http://twitter.com/%s/status/%d'
            % (tweetdata['user']['screen_name'], tweetdata['id']),
        author=account_for_twitter_user(tweetdata['user']),
        in_reply_to=in_reply_to,
    )
    tweet.save()

    return False, tweet

def poll_twitter(account):
    user = account.person.user
    if user is None:
        return

    # Get that twitter user's home timeline.
    csr = oauth.Consumer(*settings.TWITTER_CONSUMER)
    token = oauth.Token(*account.authinfo.split(':', 1))
    client = oauth.Client(csr, token)
    resp, content = client.request('http://api.twitter.com/1/statuses/home_timeline.json?include_entities=true', 'GET')
    if resp.status != 200:
        raise ValueError("Unexpected %d %s response fetching %s's twitter timeline"
            % (resp.status, resp.reason, account.display_name))

    tl = json.loads(content)

    for orig_tweetdata in reversed(tl):
        try:
            # TODO: filter based on source?

            tweetdata = orig_tweetdata
            why_verb = 'post'
            try:
                tweetdata = orig_tweetdata['retweeted_status']
            except KeyError:
                pass
            else:
                why_verb = 'share'

            orig_actor = account_for_twitter_user(orig_tweetdata['user'])
            really_a_share, tweet = raw_object_for_tweet(tweetdata, client)
            if really_a_share:
                why_verb = 'share'

            # CASES:
            # real reply to...
            # real retweet of...
            # tweet with just a link
            # tweet with a link and custom text
            # tweet with a link and the link's target page title (found how?)

            if why_verb == 'post' and not tweet.in_reply_to:
                UserStream.objects.get_or_create(user=user, obj=tweet,
                    defaults={'why_account': tweet.author, 'why_verb': 'post', 'time': tweet.time})

            # But if it's really a reply?
            elif why_verb == 'post':
                root = tweet
                while root.in_reply_to is not None:
                    log.debug('Walking up from %r to %r', root, root.in_reply_to)
                    root = root.in_reply_to

                UserStream.objects.get_or_create(user=user, obj=root,
                    defaults={'why_account': tweet.author, 'why_verb': 'reply', 'time': tweet.time})

                # Now add a reply for each tweet in the thread.
                supertweet = tweet
                while supertweet.in_reply_to is not None:
                    UserReplyStream.objects.get_or_create(user=user, root=root, reply=supertweet,
                        defaults={'root_time': root.time, 'reply_time': supertweet.time})
                    supertweet = supertweet.in_reply_to

            elif why_verb == 'share':
                # Sharing is transitive, so really share the root.
                root = tweet
                while root.in_reply_to is not None:
                    log.debug('Walking up from %r to %r', root, root.in_reply_to)
                    root = root.in_reply_to

                UserStream.objects.get_or_create(user=user, obj=root,
                    defaults={'why_account': orig_actor, 'why_verb': 'share', 'time': tweet.time})

        except Exception, exc:
            log.exception(exc)
<commit_msg>Give more info about tweets the targets of which can't be imported<commit_after>from datetime import datetime
import json
import logging
import re

from django.conf import settings
import httplib2
import oauth2 as oauth

from rhino.models import Object, Account, Person, UserStream, Media, UserReplyStream
import rhino.poll.embedlam

log = logging.getLogger(__name__)

def account_for_twitter_user(userdata, person=None):
    try:
        account = Account.objects.get(service='twitter.com', ident=str(userdata['id']))
    except Account.DoesNotExist:
        if person is None:
            avatar = Media(
                width=48,
                height=48,
                image_url=userdata['profile_image_url'],
            )
            avatar.save()
            person = Person(
                display_name=userdata['name'],
                avatar=avatar,
                permalink_url='http://twitter.com/%s' % userdata['screen_name'],
            )
            person.save()
        account = Account(
            service='twitter.com',
            ident=str(userdata['id']),
            display_name=userdata['name'],
            person=person,

            status_background_color=userdata['profile_background_color'],
            status_background_image_url=userdata['profile_background_image_url'],
            status_background_tile=userdata['profile_background_tile'],
        )
        account.save()

    return account

def tweet_html(tweetdata):
    tweet = tweetdata['text']
    if 'entities' not in tweetdata:
        return tweet

    mutations = list()
    for urldata in tweetdata['entities'].get('urls', ()):
        url = urldata['expanded_url'] or urldata['url']
        mutations.append({
            'indices': urldata['indices'],
            'html': """%s""" % (url, url),
        })
    for mentiondata in tweetdata['entities'].get('user_mentions', ()):
        mutations.append({
            'indices': mentiondata['indices'],
            'html': """@%(screen_name)s""" % mentiondata,
        })
    for tagdata in tweetdata['entities'].get('hashtags', ()):
        mutations.append({
            'indices': tagdata['indices'],
            'html': """#%(text)s""" % tagdata,
        })

    for mutation in sorted(mutations, key=lambda x: x['indices'][0], reverse=True):
        indices = mutation['indices']
        tweet = tweet[:indices[0]] + mutation['html'] + tweet[indices[1]:]

    return tweet

url_re = re.compile(r"""
    (?: (?<= \A )
      | (?<= [\s.:;?\-\]<\(] ) )

    https?://
    [-\w;/?:@&=+$.!~*'()%,#]+
    [\w/]

    (?= \Z | [\s\.,!:;?\-\[\]>\)] )
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

mention_re = re.compile(r"""
    (?: (?<= \A ) | (?<= \s ) )
    @ (\w+)
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

tag_re = re.compile(r"""
    (?: (?<= \A ) | (?<= \s ) )  # BOT or whitespace
    \# (\w\S*\w)      # tag
    (?<! 's )         # but don't end with 's
""", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)

def synthesize_entities(tweetdata):
    if 'entities' in tweetdata:
        return

    tweettext = tweetdata['text']
    ents = {
        'urls': [],
        'hashtags': [],
        'user_mentions': [],
    }

    for match in url_re.finditer(tweettext):
        ents['urls'].append({
            'expanded_url': None,
            'url': match.group(0),
            'indices': [match.start(), match.end()],
        })

    for match in mention_re.finditer(tweettext):
        ents['user_mentions'].append({
            'id': None,  # we would have to get this if we ever used it
            'name': match.group(1),  # TODO: get this from the API? ugh
            'screen_name': match.group(1),
            'indices': [match.start(), match.end()],
        })

    for match in tag_re.finditer(tweettext):
        ents['hashtags'].append({
            'text': match.group(1),
            'indices': [match.start(), match.end()],
        })

    tweetdata['entities'] = ents

def object_from_twitpic_url(url):
    mo = re.match(r'http://twitpic\.com/(\w+)', url)
    twitpic_id = mo.group(1)

    try:
        return Object.objects.get(service='twitpic.com', foreign_id=twitpic_id)
    except Object.DoesNotExist:
        pass

    h = httplib2.Http()
    resp, content = h.request('http://api.twitpic.com/2/media/show.json?id=%s' % twitpic_id)

    picdata = json.loads(content)
    userdata = picdata['user']
    # ugh, why did they rename these
    userdata['id'] = userdata['twitter_id']
    userdata['screen_name'] = userdata['username']
    userdata['profile_image_url'] = userdata['avatar_url']

    pic = Media(
        image_url='http://twitpic.com/show/large/%s' % twitpic_id,
        width=int(picdata['width']),
        height=int(picdata['height']),
    )
    pic.save()
    obj = Object(
        service='twitpic.com',
        foreign_id=twitpic_id,
        render_mode='image',
        title=picdata['message'],
        image=pic,
        author=account_for_twitter_user(userdata),
        time=datetime.strptime(picdata['timestamp'], '%Y-%m-%d %H:%M:%S'),
        permalink_url=url,
    )
    obj.save()
    return obj

def raw_object_for_tweet(tweetdata, client):
    """Returns the normalized Object for the given tweetdata, and whether
    that Object represents that tweet or the thing the tweet is sharing.

    This is returned as a tuple containing (a) whether the tweet is a
    share, and (b) the ``rhino.models.Object`` reference for that tweet
    data, in that order.

    """
    try:
        return False, Object.objects.get(service='twitter.com', foreign_id=str(tweetdata['id']))
    except Object.DoesNotExist:
        pass

    log.debug('Making new tweet for %s status #%d', tweetdata['user']['screen_name'], tweetdata['id'])

    in_reply_to = None
    if tweetdata.get('in_reply_to_status_id'):
        # Uh oh, gotta get that tweet.
        # TODO: remove the mention from the front of the tweet
        next_tweetid = tweetdata['in_reply_to_status_id']
        try:
            in_reply_to = Object.objects.get(service='twitter.com', foreign_id=str(next_tweetid))
        except Object.DoesNotExist:
            resp, content = client.request('http://api.twitter.com/1/statuses/show/%d.json'
                % next_tweetid)
            if resp.status != 200:
                raise ValueError("Unexpected %d %s response fetching tweet #%s up a reply chain for "
                    "%s's timeline" % (resp.status, resp.reason, next_tweetid, account.display_name))

            next_tweetdata = json.loads(content)
            synthesize_entities(next_tweetdata)
            log.debug("    Let's make a new tweet for %s status #%d", next_tweetdata['user']['screen_name'], next_tweetdata['id'])
            # If it's really a share, this tweet is transitively in reply to the shared thing, so this is fine.
            really_a_share, in_reply_to = raw_object_for_tweet(next_tweetdata, client)

    # Is this something other than a status?
    elif len(tweetdata['entities']['urls']) == 1:
        about_urldata = tweetdata['entities']['urls'][0]
        about_url = about_urldata['expanded_url'] or about_urldata['url']

        try:
            in_reply_to = rhino.poll.embedlam.object_for_url(about_url)
        except ValueError, exc:
            log.error("Error making object from referent %s of %s's tweet %s", about_url, tweetdata['user']['screen_name'], tweetdata['id'])
            log.exception(exc)
        else:
            # If the tweet was only the object's url and its title, make it a share.
            tweettext = tweetdata['text']
            link_starts, link_ends = about_urldata['indices']
            tweettext = tweettext[:link_starts] + tweettext[link_ends:]
            tweettext = tweettext.lower()
            if in_reply_to.title:
                tweettext = tweettext.replace(in_reply_to.title.lower(), '')
            tweettext = re.sub(r'\s', '', tweettext)

            if not tweettext:
                return True, in_reply_to

    tweet = Object(
        service='twitter.com',
        foreign_id=str(tweetdata['id']),
        render_mode='status',
        body=tweet_html(tweetdata),
        time=datetime.strptime(tweetdata['created_at'], '%a %b %d %H:%M:%S +0000 %Y'),
        permalink_url='http://twitter.com/%s/status/%d'
            % (tweetdata['user']['screen_name'], tweetdata['id']),
        author=account_for_twitter_user(tweetdata['user']),
        in_reply_to=in_reply_to,
    )
    tweet.save()

    return False, tweet

def poll_twitter(account):
    user = account.person.user
    if user is None:
        return

    # Get that twitter user's home timeline.
    csr = oauth.Consumer(*settings.TWITTER_CONSUMER)
    token = oauth.Token(*account.authinfo.split(':', 1))
    client = oauth.Client(csr, token)
    resp, content = client.request('http://api.twitter.com/1/statuses/home_timeline.json?include_entities=true', 'GET')
    if resp.status != 200:
        raise ValueError("Unexpected %d %s response fetching %s's twitter timeline"
            % (resp.status, resp.reason, account.display_name))

    tl = json.loads(content)

    for orig_tweetdata in reversed(tl):
        try:
            # TODO: filter based on source?

            tweetdata = orig_tweetdata
            why_verb = 'post'
            try:
                tweetdata = orig_tweetdata['retweeted_status']
            except KeyError:
                pass
            else:
                why_verb = 'share'

            orig_actor = account_for_twitter_user(orig_tweetdata['user'])
            really_a_share, tweet = raw_object_for_tweet(tweetdata, client)
            if really_a_share:
                why_verb = 'share'

            # CASES:
            # real reply to...
            # real retweet of...
            # tweet with just a link
            # tweet with a link and custom text
            # tweet with a link and the link's target page title (found how?)

            if why_verb == 'post' and not tweet.in_reply_to:
                UserStream.objects.get_or_create(user=user, obj=tweet,
                    defaults={'why_account': tweet.author, 'why_verb': 'post', 'time': tweet.time})

            # But if it's really a reply?
            elif why_verb == 'post':
                root = tweet
                while root.in_reply_to is not None:
                    log.debug('Walking up from %r to %r', root, root.in_reply_to)
                    root = root.in_reply_to

                UserStream.objects.get_or_create(user=user, obj=root,
                    defaults={'why_account': tweet.author, 'why_verb': 'reply', 'time': tweet.time})

                # Now add a reply for each tweet in the thread.
                supertweet = tweet
                while supertweet.in_reply_to is not None:
                    UserReplyStream.objects.get_or_create(user=user, root=root, reply=supertweet,
                        defaults={'root_time': root.time, 'reply_time': supertweet.time})
                    supertweet = supertweet.in_reply_to

            elif why_verb == 'share':
                # Sharing is transitive, so really share the root.
                root = tweet
                while root.in_reply_to is not None:
                    log.debug('Walking up from %r to %r', root, root.in_reply_to)
                    root = root.in_reply_to

                UserStream.objects.get_or_create(user=user, obj=root,
                    defaults={'why_account': orig_actor, 'why_verb': 'share', 'time': tweet.time})

        except Exception, exc:
            log.exception(exc)
<|endoftext|>


<commit_before>#!/usr/bin/python2.4
#
# Copyright (c) 2006-2007 rPath, Inc.  All rights reserved.
#
"""
Simple client that communicates with rMake.
"""

import errno
import os
import sys

from conary import conarycfg
from conary import errors as conaryerrors
from conary.lib import cfg, log
from conary.lib import options

from rmake import constants
from rmake import errors

sys.excepthook = errors.genExcepthook(debug=False)

from rmake import compat
from rmake import plugins

from rmake.build import buildcfg
from rmake.cmdline import command
from rmake.cmdline import helper

class RmakeMain(options.MainHandler):
    name = 'rmake'
    version = constants.version

    abstractCommand = command.rMakeCommand
    configClass = buildcfg.BuildConfiguration

    useConaryOptions = False

    commandList = command._commands

    def usage(self, rc=1, showAll=False):
        print 'rmake: front end to rMake build tool'
        if not showAll:
            print
            print 'Common Commands (use "rmake help" for the full list)'
        return options.MainHandler.usage(self, rc, showAll=showAll)

    def initializePlugins(self, argv):
        p = plugins.getPluginManager(argv, buildcfg.BuildConfiguration)
        p.callClientHook('client_preInit', self, argv)
        return p

    def getConfigFile(self, argv):
        pluginManager = self.initializePlugins(argv)
        if '--skip-default-config' in argv:
            argv.remove('--skip-default-config')
            read = False
        else:
            read = True

        buildConfig = buildcfg.BuildConfiguration(readConfigFiles=read)
        conaryConfig = conarycfg.ConaryConfiguration(readConfigFiles=read)
        return buildConfig, conaryConfig, pluginManager

    def runCommand(self, thisCommand, (buildConfig, conaryConfig,
                                       pluginManager), argSet, args):
        pluginManager.callClientHook('client_preCommand', self, thisCommand,
                                     (buildConfig, conaryConfig), argSet, args)
        compat.checkRequiredVersions()
        thisCommand.verbose = (log.getVerbosity() <= log.INFO)
        if args[1] != 'help':
            # NOTE: the help system assumes that the base level of output
            # you want is "warning", but rmake is more verbose than that.
            # Due to limitations in how configurable the help system is,
            # I can't easily fix that.  Someday I should though.  For now,
            # if we're running help, we make log.WARNING the default level,
            # and otherwise log.INFO is the default.
            log.setMinVerbosity(log.INFO)

        # don't let the buildFlavor be overridden yet
        client = helper.rMakeHelper(buildConfig=buildConfig)

        pluginManager.callClientHook('client_preCommand2', self, client,
                                     thisCommand)

        try:
            return options.MainHandler.runCommand(self, thisCommand, client,
                                                  buildConfig, argSet, args)
        except errors.BadParameters:
            if not thisCommand.verbose:
                log.setVerbosity(log.WARNING)
            thisCommand.usage()
            raise

def main(argv):
    log.setVerbosity(log.WARNING)
    rmakeMain = RmakeMain()
    try:
        argv = list(argv)
        debugAll = '--debug-all' in argv
        if debugAll:
            debuggerException = Exception
            argv.remove('--debug-all')
        else:
            debuggerException = errors.RmakeInternalError
        sys.excepthook = errors.genExcepthook(debug=debugAll,
                                              debugCtrlC=debugAll)
        compat.ConaryVersion().checkRequiredVersion()
        return RmakeMain().main(argv, debuggerException=debuggerException)
    except debuggerException, err:
        raise
    except errors.OpenError, err:
        log.error(str(err) + ' -- check to see that the server is running.')
        return 1
    except (errors.RmakeError, conaryerrors.ConaryError, cfg.ParseError,
            conaryerrors.CvcError), err:
        log.error(err)
        return 1
    except IOError, e:
        # allow broken pipe to exit
        if e.errno != errno.EPIPE:
            raise
    except KeyboardInterrupt:
        return 1
    return 0
<commit_msg>Remove unnecessary line<commit_after>#!/usr/bin/python2.4
#
# Copyright (c) 2006-2007 rPath, Inc.  All rights reserved.
#
"""
Simple client that communicates with rMake.
"""

import errno
import os
import sys

from conary import conarycfg
from conary import errors as conaryerrors
from conary.lib import cfg, log
from conary.lib import options

from rmake import constants
from rmake import errors

sys.excepthook = errors.genExcepthook(debug=False)

from rmake import compat
from rmake import plugins

from rmake.build import buildcfg
from rmake.cmdline import command
from rmake.cmdline import helper

class RmakeMain(options.MainHandler):
    name = 'rmake'
    version = constants.version

    abstractCommand = command.rMakeCommand
    configClass = buildcfg.BuildConfiguration

    useConaryOptions = False

    commandList = command._commands

    def usage(self, rc=1, showAll=False):
        print 'rmake: front end to rMake build tool'
        if not showAll:
            print
            print 'Common Commands (use "rmake help" for the full list)'
        return options.MainHandler.usage(self, rc, showAll=showAll)

    def initializePlugins(self, argv):
        p = plugins.getPluginManager(argv, buildcfg.BuildConfiguration)
        p.callClientHook('client_preInit', self, argv)
        return p

    def getConfigFile(self, argv):
        pluginManager = self.initializePlugins(argv)
        if '--skip-default-config' in argv:
            argv.remove('--skip-default-config')
            read = False
        else:
            read = True

        buildConfig = buildcfg.BuildConfiguration(readConfigFiles=read)
        conaryConfig = conarycfg.ConaryConfiguration(readConfigFiles=read)
        return buildConfig, conaryConfig, pluginManager

    def runCommand(self, thisCommand, (buildConfig, conaryConfig,
                                       pluginManager), argSet, args):
        pluginManager.callClientHook('client_preCommand', self, thisCommand,
                                     (buildConfig, conaryConfig), argSet, args)
        compat.checkRequiredVersions()
        thisCommand.verbose = (log.getVerbosity() <= log.INFO)
        if args[1] != 'help':
            # NOTE: the help system assumes that the base level of output
            # you want is "warning", but rmake is more verbose than that.
            # Due to limitations in how configurable the help system is,
            # I can't easily fix that.  Someday I should though.  For now,
            # if we're running help, we make log.WARNING the default level,
            # and otherwise log.INFO is the default.
            log.setMinVerbosity(log.INFO)

        # don't let the buildFlavor be overridden yet
        client = helper.rMakeHelper(buildConfig=buildConfig)

        pluginManager.callClientHook('client_preCommand2', self, client,
                                     thisCommand)

        try:
            return options.MainHandler.runCommand(self, thisCommand, client,
                                                  buildConfig, argSet, args)
        except errors.BadParameters:
            if not thisCommand.verbose:
                log.setVerbosity(log.WARNING)
            thisCommand.usage()
            raise

def main(argv):
    log.setVerbosity(log.WARNING)
    try:
        argv = list(argv)
        debugAll = '--debug-all' in argv
        if debugAll:
            debuggerException = Exception
            argv.remove('--debug-all')
        else:
            debuggerException = errors.RmakeInternalError
        sys.excepthook = errors.genExcepthook(debug=debugAll,
                                              debugCtrlC=debugAll)
        compat.ConaryVersion().checkRequiredVersion()
        return RmakeMain().main(argv, debuggerException=debuggerException)
    except debuggerException, err:
        raise
    except errors.OpenError, err:
        log.error(str(err) + ' -- check to see that the server is running.')
        return 1
    except (errors.RmakeError, conaryerrors.ConaryError, cfg.ParseError,
            conaryerrors.CvcError), err:
        log.error(err)
        return 1
    except IOError, e:
        # allow broken pipe to exit
        if e.errno != errno.EPIPE:
            raise
    except KeyboardInterrupt:
        return 1
    return 0
<|endoftext|>


<commit_before># Adapted from http://www.hackerthreads.org/Topic-42395
from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref, c_char, c_uint, addressof
import win32con, win32api, win32gui, atexit
from keyboard_event import KeyboardEvent, KEY_DOWN, KEY_UP

def press_keycode(keycode):
    win32api.keybd_event(keycode, 0, 0, 0)

def release_keycode(keycode):
    win32api.keybd_event(keycode, 0, 0x2, 0)

def _to_ascii(keycode, scancode):
    state = (c_char * 256)()
    windll.user32.GetKeyboardState(byref(state))
    lpChar = (c_char * 2)()
    #nSize = windll.user32.ToAsciiEx(c_uint(keycode),
    nSize = windll.user32.ToAscii(c_uint(keycode),
                                  c_uint(scancode),
                                  addressof(state),
                                  addressof(lpChar),
                                   #c_uint(windll.user32.GetKeyboardLayout(0)),
                                  None)

    if nSize >= 1:
        return u''.join(map(unichr, filter(lambda i: i, map(ord, lpChar))))
    else:
        return None

def listen(handlers):
    """
    Calls `handlers` for each keyboard event received. This is a blocking call.
    """
    event_types = {win32con.WM_KEYDOWN: KEY_DOWN,
                   win32con.WM_KEYUP: KEY_UP,
                   0x104: KEY_DOWN, # WM_SYSKEYDOWN, used for Alt key.
                   0x105: KEY_UP, # WM_SYSKEYUP, used for Alt key.
                  }

    def low_level_handler(nCode, wParam, lParam):
        """
        Processes a low level Windows keyboard event.
        """
        event_type = event_types[wParam]
        keycode = lParam[0]
        scancode = lParam[1]
        alt_pressed = lParam[2] == 32
        time = lParam[3]
        char = _to_ascii(keycode, scancode)
        print is_keycode_pressed(keycode)

        event = KeyboardEvent(event_type, keycode, scancode, char,
                              alt_pressed, time)

        for handler in handlers:
            handler(event)

        # Be a good neighbor and call the next hook.
        return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam)

    # Our low level handler signature.
    CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
    # Convert the Python handler into C pointer.
    pointer = CMPFUNC(low_level_handler)

    # Hook both key up and key down events for common keys (non-system).
    hook_id = windll.user32.SetWindowsHookExA(win32con.WH_KEYBOARD_LL, pointer,
                                             win32api.GetModuleHandle(None), 0)

    # Register to remove the hook when the interpreter exits. Unfortunately a
    # try/finally block doesn't seem to work here.
    atexit.register(windll.user32.UnhookWindowsHookEx, hook_id)

    while True:
        msg = win32gui.GetMessage(None, 0, 0)
        win32gui.TranslateMessage(byref(msg))
        win32gui.DispatchMessage(byref(msg))
<commit_msg>Remove unnecessary print that broke things<commit_after># Adapted from http://www.hackerthreads.org/Topic-42395
from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref, c_char, c_uint, addressof
import win32con, win32api, win32gui, atexit
from keyboard_event import KeyboardEvent, KEY_DOWN, KEY_UP

def press_keycode(keycode):
    win32api.keybd_event(keycode, 0, 0, 0)

def release_keycode(keycode):
    win32api.keybd_event(keycode, 0, 0x2, 0)

def _to_ascii(keycode, scancode):
    state = (c_char * 256)()
    windll.user32.GetKeyboardState(byref(state))
    lpChar = (c_char * 2)()
    #nSize = windll.user32.ToAsciiEx(c_uint(keycode),
    nSize = windll.user32.ToAscii(c_uint(keycode),
                                  c_uint(scancode),
                                  addressof(state),
                                  addressof(lpChar),
                                   #c_uint(windll.user32.GetKeyboardLayout(0)),
                                  None)

    if nSize >= 1:
        return u''.join(map(unichr, filter(lambda i: i, map(ord, lpChar))))
    else:
        return None

def listen(handlers):
    """
    Calls `handlers` for each keyboard event received. This is a blocking call.
    """
    event_types = {win32con.WM_KEYDOWN: KEY_DOWN,
                   win32con.WM_KEYUP: KEY_UP,
                   0x104: KEY_DOWN, # WM_SYSKEYDOWN, used for Alt key.
                   0x105: KEY_UP, # WM_SYSKEYUP, used for Alt key.
                  }

    def low_level_handler(nCode, wParam, lParam):
        """
        Processes a low level Windows keyboard event.
        """
        event_type = event_types[wParam]
        keycode = lParam[0]
        scancode = lParam[1]
        alt_pressed = lParam[2] == 32
        time = lParam[3]
        char = _to_ascii(keycode, scancode)

        event = KeyboardEvent(event_type, keycode, scancode, char,
                              alt_pressed, time)

        for handler in handlers:
            handler(event)

        # Be a good neighbor and call the next hook.
        return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam)

    # Our low level handler signature.
    CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
    # Convert the Python handler into C pointer.
    pointer = CMPFUNC(low_level_handler)

    # Hook both key up and key down events for common keys (non-system).
    hook_id = windll.user32.SetWindowsHookExA(win32con.WH_KEYBOARD_LL, pointer,
                                             win32api.GetModuleHandle(None), 0)

    # Register to remove the hook when the interpreter exits. Unfortunately a
    # try/finally block doesn't seem to work here.
    atexit.register(windll.user32.UnhookWindowsHookEx, hook_id)

    while True:
        msg = win32gui.GetMessage(None, 0, 0)
        win32gui.TranslateMessage(byref(msg))
        win32gui.DispatchMessage(byref(msg))
<|endoftext|>