<commit_before>import datetime
from decimal import Decimal

BIRTHDAY = datetime.date(2012, 6, 5)
def age():
    age = datetime.date.today() - BIRTHDAY
    return "%d days" % age.days

db = None # This global is wired in wireup. It's an instance of
          # gittip.postgres.PostgresManager.
AMOUNTS= [Decimal(a) for a in ('0.00', '0.08', '0.16', '0.32', '0.64', '1.28')]

__version__ = "~~VERSION~~"

def get_tip(tipper, tippee):
    """Given two user ids, return a Decimal.
    """
    TIP = """\

        SELECT amount
          FROM tips
         WHERE tipper=%s
           AND tippee=%s
      ORDER BY mtime DESC
         LIMIT 1

    """
    rec = db.fetchone(TIP, (tipper, tippee))
    if rec is None:
        tip = Decimal(0.00)
    else:
        tip = rec['amount']
    return tip

def get_tipjar(participant_id, pronoun="their", claimed=False):
    """Given a participant id, return a unicode.
    """

    # Compute the amount.
    # ===================

    TIPJAR = """\

        SELECT sum(amount) AS tipjar
          FROM ( SELECT DISTINCT ON (tipper)
                        amount
                      , tipper
                   FROM tips
                   JOIN participants p ON p.id = tipper
                  WHERE tippee=%s
                    AND last_bill_result = ''
               ORDER BY tipper
                      , mtime DESC
                ) AS foo

    """
    rec = db.fetchone(TIPJAR, (participant_id,))
    if rec is None:
        amount = None
    else:
        amount = rec['tipjar']  # might be None

    if amount is None:
        amount = Decimal(0.00)

    # Compute a unicode describing the amount.
    # ========================================
    # This is down here because we use it in multiple places in the app,
    # basically in the claimed participant page and the non-claimed GitHub page
    # (hopefully soon to be Facebook and Twitter as well).

    if pronoun not in ('your', 'their'):
        raise Exception("Unknown, um, pronoun: %s" % pronoun)

    if amount == 0:
        if pronoun == "your":
            tipjar = u"have no backed tips."
        elif pronoun == "their":
            tipjar = u"has no backed tips."
    else:
        if pronoun == "your":
            tipjar = u"have $%s in backed tips."
        elif pronoun == "their":
            tipjar = u"has $%s in backed tips."
        tipjar %= amount

    # We're opt-in.
    # =============
    # If the user hasn't claimed the tipjar then the tips are only pledges,
    # we're not going to actually collect money on their behalf.

    if not claimed:
        tipjar = tipjar.replace("backed", "pledged")

    return tipjar

def get_tips_and_total(tipper, for_payday=False):
    """Given a participant id, return a list and a Decimal.

    This function is used to populate a participant's page for their own
    viewing pleasure, and also by the payday function.

    """
    if for_payday:

        # For payday we want the oldest relationship to be paid first.
        order_by = "ctime ASC"

        # This is where it gets crash-proof.
        # ==================================
        # We need to account for the fact that we may have crashed during
        # Payday and we're re-running that function. We only want to select
        # tips that existed before Payday started, but haven't been processed
        # as part of this Payday yet.
        #
        # It's a bug if the paydays subselect returns > 1 rows.
        #
        # XXX If we crash during Payday and we rerun it after a timezone
        # change, will we get burned? How?

        ts_filter = """\

               AND mtime < %s
               AND ( SELECT id
                       FROM transfers
                      WHERE tipper=tips.tipper
                        AND tippee=tips.tippee
                        AND timestamp >= %s
                    ) IS NULL

        """
        args = (tipper, for_payday, for_payday)
    else:
        order_by = "amount DESC"
        ts_filter = ""
        args = (tipper,)

    TIPS = """\

        SELECT * FROM (
            SELECT DISTINCT ON (tippee)
                   amount
                 , tippee
                 , ctime
              FROM tips
             WHERE tipper = %%s
               %s
          ORDER BY tippee
                 , mtime DESC
        ) AS foo
        ORDER BY %s
               , tippee

    """ % (ts_filter, order_by)
    tips = list(db.fetchall(TIPS, args))
    total = sum([tip['amount'] for tip in tips])
    if not total:
        total = Decimal('0.00')
    return tips, total

# canonizer
# =========
# This is an Aspen hook to ensure that requests are served on a certain root
# URL, even if multiple domains point to the application.

class X: pass
canonical_scheme = None
canonical_host = None

def canonize(request):
    """Enforce a certain scheme and hostname. Store these on request as well.
    """
    scheme = request.headers.get('X-Forwarded-Proto', 'http') # per Heroku
    host = request.headers['Host']
    bad_scheme = scheme != canonical_scheme
    bad_host = bool(canonical_host) and (host != canonical_host)
                # '' and False => ''
    if bad_scheme or bad_host:
        url = '%s://%s/' % (canonical_scheme, canonical_host)
        request.redirect(url, permanent=True)
<commit_msg>Setting version to 1.2.14 in gittip/__init__.py.<commit_after>import datetime
from decimal import Decimal

BIRTHDAY = datetime.date(2012, 6, 5)
def age():
    age = datetime.date.today() - BIRTHDAY
    return "%d days" % age.days

db = None # This global is wired in wireup. It's an instance of
          # gittip.postgres.PostgresManager.
AMOUNTS= [Decimal(a) for a in ('0.00', '0.08', '0.16', '0.32', '0.64', '1.28')]

__version__ = "1.2.14"

def get_tip(tipper, tippee):
    """Given two user ids, return a Decimal.
    """
    TIP = """\

        SELECT amount
          FROM tips
         WHERE tipper=%s
           AND tippee=%s
      ORDER BY mtime DESC
         LIMIT 1

    """
    rec = db.fetchone(TIP, (tipper, tippee))
    if rec is None:
        tip = Decimal(0.00)
    else:
        tip = rec['amount']
    return tip

def get_tipjar(participant_id, pronoun="their", claimed=False):
    """Given a participant id, return a unicode.
    """

    # Compute the amount.
    # ===================

    TIPJAR = """\

        SELECT sum(amount) AS tipjar
          FROM ( SELECT DISTINCT ON (tipper)
                        amount
                      , tipper
                   FROM tips
                   JOIN participants p ON p.id = tipper
                  WHERE tippee=%s
                    AND last_bill_result = ''
               ORDER BY tipper
                      , mtime DESC
                ) AS foo

    """
    rec = db.fetchone(TIPJAR, (participant_id,))
    if rec is None:
        amount = None
    else:
        amount = rec['tipjar']  # might be None

    if amount is None:
        amount = Decimal(0.00)

    # Compute a unicode describing the amount.
    # ========================================
    # This is down here because we use it in multiple places in the app,
    # basically in the claimed participant page and the non-claimed GitHub page
    # (hopefully soon to be Facebook and Twitter as well).

    if pronoun not in ('your', 'their'):
        raise Exception("Unknown, um, pronoun: %s" % pronoun)

    if amount == 0:
        if pronoun == "your":
            tipjar = u"have no backed tips."
        elif pronoun == "their":
            tipjar = u"has no backed tips."
    else:
        if pronoun == "your":
            tipjar = u"have $%s in backed tips."
        elif pronoun == "their":
            tipjar = u"has $%s in backed tips."
        tipjar %= amount

    # We're opt-in.
    # =============
    # If the user hasn't claimed the tipjar then the tips are only pledges,
    # we're not going to actually collect money on their behalf.

    if not claimed:
        tipjar = tipjar.replace("backed", "pledged")

    return tipjar

def get_tips_and_total(tipper, for_payday=False):
    """Given a participant id, return a list and a Decimal.

    This function is used to populate a participant's page for their own
    viewing pleasure, and also by the payday function.

    """
    if for_payday:

        # For payday we want the oldest relationship to be paid first.
        order_by = "ctime ASC"

        # This is where it gets crash-proof.
        # ==================================
        # We need to account for the fact that we may have crashed during
        # Payday and we're re-running that function. We only want to select
        # tips that existed before Payday started, but haven't been processed
        # as part of this Payday yet.
        #
        # It's a bug if the paydays subselect returns > 1 rows.
        #
        # XXX If we crash during Payday and we rerun it after a timezone
        # change, will we get burned? How?

        ts_filter = """\

               AND mtime < %s
               AND ( SELECT id
                       FROM transfers
                      WHERE tipper=tips.tipper
                        AND tippee=tips.tippee
                        AND timestamp >= %s
                    ) IS NULL

        """
        args = (tipper, for_payday, for_payday)
    else:
        order_by = "amount DESC"
        ts_filter = ""
        args = (tipper,)

    TIPS = """\

        SELECT * FROM (
            SELECT DISTINCT ON (tippee)
                   amount
                 , tippee
                 , ctime
              FROM tips
             WHERE tipper = %%s
               %s
          ORDER BY tippee
                 , mtime DESC
        ) AS foo
        ORDER BY %s
               , tippee

    """ % (ts_filter, order_by)
    tips = list(db.fetchall(TIPS, args))
    total = sum([tip['amount'] for tip in tips])
    if not total:
        total = Decimal('0.00')
    return tips, total

# canonizer
# =========
# This is an Aspen hook to ensure that requests are served on a certain root
# URL, even if multiple domains point to the application.

class X: pass
canonical_scheme = None
canonical_host = None

def canonize(request):
    """Enforce a certain scheme and hostname. Store these on request as well.
    """
    scheme = request.headers.get('X-Forwarded-Proto', 'http') # per Heroku
    host = request.headers['Host']
    bad_scheme = scheme != canonical_scheme
    bad_host = bool(canonical_host) and (host != canonical_host)
                # '' and False => ''
    if bad_scheme or bad_host:
        url = '%s://%s/' % (canonical_scheme, canonical_host)
        request.redirect(url, permanent=True)
<|endoftext|>


<commit_before>import os

import shouter
import shell

class Initializer:
    def __init__(self, config):
        self.repoName = config.gitRepoName
        self.clonedRepoName = config.clonedGitRepoName
        self.author = config.user

    @staticmethod
    def createignore():
        newline = "\n"
        with open(".gitignore", "w") as ignore:
            ignore.write(".jazz5" + newline)
            ignore.write(".metadata" + newline)
            ignore.write(".jazzShed" + newline)

    def initalize(self):
        shell.execute("git init --bare " + self.repoName)
        shouter.shout("Repository was created in " + os.getcwd())
        shell.execute("git clone " + self.repoName)
        os.chdir(self.clonedRepoName)
        shell.execute("git config push.default current")
        self.createignore()

    @staticmethod
    def initialcommitandpush():
        shouter.shout("Initial git add")
        shell.execute("git add -A", os.devnull)
        shouter.shout("Finished initial git add, starting commit")
        shell.execute("git commit -m %s -q" % shell.quote("Initial Commit"))
        shouter.shout("Finished commit")
        shell.execute("git push origin master")
        shouter.shout("Finished push")

class Commiter:
    commitcounter = 0

    @staticmethod
    def addandcommit(changeentry):
        comment = Commiter.replacegitcreatingfilesymbol(changeentry.comment)
        Commiter.replaceauthor(changeentry.author, changeentry.email)
        shell.execute("git add -A")
        shell.execute("git commit -m %s --date %s --author=%s"
                      % (shell.quote(comment), shell.quote(changeentry.date), changeentry.getgitauthor()))
        Commiter.commitcounter += 1
        if Commiter.commitcounter is 30:
            shouter.shout("30 Commits happend, push current branch to avoid out of memory")
            Commiter.pushbranch("")
            Commiter.commitcounter = 0

    @staticmethod
    def replacegitcreatingfilesymbol(comment):
        return Commiter.replacewords(" to ", comment, "-->", "->", ">")

    @staticmethod
    def replacewords(replacedwith, word, *replacingstrings):
        for replacingstring in replacingstrings:
            if replacingstring in word:
                word = word.replace(replacingstring, replacedwith)
        return word

    @staticmethod
    def replaceauthor(author, email):
        shell.execute("git config --replace-all user.name " + shell.quote(author))
        shell.execute("git config --replace-all user.email " + email)

    @staticmethod
    def branch(branchname):
        branchexist = shell.execute("git show-ref --verify --quiet refs/heads/" + branchname)
        if branchexist is 0:
            shell.execute("git checkout " + branchname)
        else:
            shell.execute("git checkout -b " + branchname)

    @staticmethod
    def pushbranch(branchname):
        if branchname:
            shouter.shout("Final push of branch " + branchname)
        shell.execute("git push origin " + branchname)
<commit_msg>added shout after git commit<commit_after>import os

import shouter
import shell

class Initializer:
    def __init__(self, config):
        self.repoName = config.gitRepoName
        self.clonedRepoName = config.clonedGitRepoName
        self.author = config.user

    @staticmethod
    def createignore():
        newline = "\n"
        with open(".gitignore", "w") as ignore:
            ignore.write(".jazz5" + newline)
            ignore.write(".metadata" + newline)
            ignore.write(".jazzShed" + newline)

    def initalize(self):
        shell.execute("git init --bare " + self.repoName)
        shouter.shout("Repository was created in " + os.getcwd())
        shell.execute("git clone " + self.repoName)
        os.chdir(self.clonedRepoName)
        shell.execute("git config push.default current")
        self.createignore()

    @staticmethod
    def initialcommitandpush():
        shouter.shout("Initial git add")
        shell.execute("git add -A", os.devnull)
        shouter.shout("Finished initial git add, starting commit")
        shell.execute("git commit -m %s -q" % shell.quote("Initial Commit"))
        shouter.shout("Finished commit")
        shell.execute("git push origin master")
        shouter.shout("Finished push")

class Commiter:
    commitcounter = 0

    @staticmethod
    def addandcommit(changeentry):
        comment = Commiter.replacegitcreatingfilesymbol(changeentry.comment)
        Commiter.replaceauthor(changeentry.author, changeentry.email)
        shell.execute("git add -A")
        shell.execute("git commit -m %s --date %s --author=%s"
                      % (shell.quote(comment), shell.quote(changeentry.date), changeentry.getgitauthor()))
        Commiter.commitcounter += 1
        if Commiter.commitcounter is 30:
            shouter.shout("30 Commits happend, push current branch to avoid out of memory")
            Commiter.pushbranch("")
            Commiter.commitcounter = 0
        shouter.shout("Commited change in local git repository")

    @staticmethod
    def replacegitcreatingfilesymbol(comment):
        return Commiter.replacewords(" to ", comment, "-->", "->", ">")

    @staticmethod
    def replacewords(replacedwith, word, *replacingstrings):
        for replacingstring in replacingstrings:
            if replacingstring in word:
                word = word.replace(replacingstring, replacedwith)
        return word

    @staticmethod
    def replaceauthor(author, email):
        shell.execute("git config --replace-all user.name " + shell.quote(author))
        shell.execute("git config --replace-all user.email " + email)

    @staticmethod
    def branch(branchname):
        branchexist = shell.execute("git show-ref --verify --quiet refs/heads/" + branchname)
        if branchexist is 0:
            shell.execute("git checkout " + branchname)
        else:
            shell.execute("git checkout -b " + branchname)

    @staticmethod
    def pushbranch(branchname):
        if branchname:
            shouter.shout("Final push of branch " + branchname)
        shell.execute("git push origin " + branchname)
<|endoftext|>


<commit_before>#!/usr/bin/python

import sys
import os
import re
import commands
from optparse import OptionParser

FILE_MATCHER = re.compile('File \'(.*)\'')
EXECUTED_MATCHER = re.compile('Lines executed:([0-9.]+)% of ([0-9]+)')

def FindObjectFiles(directory):
  results = []
  for root, dirs, files in os.walk(directory):
    for file in files:
      (name, ext) = os.path.splitext(file)
      if ext == '.o':
        results.append(os.path.join(root, file))
  return results

def ParseGcovOutput(output, srcRoot, exceptDirectory):
  results = []
  item = {}

  lines = output.splitlines()
  for line in lines:
    if line == '':
      if 'file' in item:
        results.append(item)
      item = {}
      continue

    m = FILE_MATCHER.match(line)
    if m != None:
      path = m.group(1)
      fullpath = os.path.realpath(path)
      relpath = os.path.relpath(path, srcRoot)
      if (fullpath.startswith(os.path.realpath(srcRoot)) and
          (exceptDirectory == None or
           not relpath.startswith(exceptDirectory))):
        item['file'] = relpath
        item['gcov'] = os.path.realpath(os.path.basename(path) + '.gcov')
      continue

    m = EXECUTED_MATCHER.match(line)
    if m != None:
      item['executed'] = float(m.group(1))
      item['executable'] = int(m.group(2))
      continue

  return results

def PrintResult(results):
  maxSrcLength = 0
  for result in results:
    maxSrcLength = max(maxSrcLength, len(result['file']))

  print '    %    executable source'
  print 'executed      lines file'
  fmt = '  %6.2f      %5d %-' + str(maxSrcLength) + 's %s'
  for result in results:
    if result.get('executable', 0) != 0:
      print fmt % (
          result.get('executed', 0.0), result.get('executable', 0),
          result.get('file', ''), result.get('gcov', ''))

def GetExecuted(item):
  return item.get('executed', 0.0)

def GenerateCovReport(buildDirectory, srcRoot, exceptDirectory, outPath):
  # find object files
  objectFiles = FindObjectFiles(buildDirectory)

  # generate command
  command = 'gcov';
  for file in objectFiles:
    command = command + ' \'' + file + '\''

  # execute command
  (status, output) = commands.getstatusoutput(command)

  if status != 0:
    raise IOError('gcov command failed.')

  results = ParseGcovOutput(output, srcRoot, exceptDirectory)
  results = sorted(results, key=GetExecuted, reverse=True)

  # print result
  PrintResult(results)

def main(argv):
  parser = OptionParser()
  parser.add_option('-d', '--dir', dest='dir', default='.',
                   help='Directory for searching object files', metavar='DIR')
  parser.add_option('-s', '--source', dest='source', default='.',
                   help='Root directory of sources', metavar='DIR')
  parser.add_option('-e', '--except', dest='except_', default=None,
                    help='Directory to except', metavar='DIR')
  parser.add_option('-o', '--out', dest='out', default='coverage.txt',
                   help='Output file name', metavar='FILE')
  (options, args) = parser.parse_args()

  GenerateCovReport(options.dir, options.source, options.except_, options.out)

  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv))
<commit_msg>update gen_cov_report.py<commit_after>#!/usr/bin/python

import sys
import os
import re
import subprocess
from optparse import OptionParser

FILE_MATCHER = re.compile('File \'(.*)\'')
EXECUTED_MATCHER = re.compile('Lines executed:([0-9.]+)% of ([0-9]+)')

def FindObjectFiles(directory):
  results = []
  for root, dirs, files in os.walk(directory):
    for file in files:
      (name, ext) = os.path.splitext(file)
      if ext == '.o':
        results.append(os.path.join(root, file))
  return results

def ParseGcovOutput(output, srcRoot, exceptDirectory):
  results = []
  item = {}

  lines = output.splitlines()
  for line in lines:
    if line == '':
      if 'file' in item:
        results.append(item)
      item = {}
      continue

    m = FILE_MATCHER.match(line)
    if m != None:
      path = m.group(1)
      fullpath = os.path.realpath(path)
      relpath = os.path.relpath(path, srcRoot)
      if (fullpath.startswith(os.path.realpath(srcRoot)) and
          (exceptDirectory == None or
           not relpath.startswith(exceptDirectory))):
        item['file'] = relpath
        item['gcov'] = os.path.realpath(os.path.basename(path) + '.gcov')
      continue

    m = EXECUTED_MATCHER.match(line)
    if m != None:
      item['executed'] = float(m.group(1))
      item['executable'] = int(m.group(2))
      continue

  return results

def PrintResult(results):
  maxSrcLength = 0
  for result in results:
    maxSrcLength = max(maxSrcLength, len(result['file']))

  print ('    %    executable source')
  print ('executed      lines file')
  fmt = '  {0:6.2f}      {1:5d} {2:' + str(maxSrcLength) + '} {3}'
  for result in results:
    if result.get('executable', 0) != 0:
      print (fmt.format(
          result.get('executed', 0.0), result.get('executable', 0),
          result.get('file', ''), result.get('gcov', '')))

def GetExecuted(item):
  return item.get('executed', 0.0)

def GenerateCovReport(buildDirectory, srcRoot, exceptDirectory, outPath):
  # find object files
  objectFiles = FindObjectFiles(buildDirectory)

  # generate command
  command = 'gcov';
  for file in objectFiles:
    command = command + ' \'' + file + '\''

  # execute command
  (status, output) = subprocess.getstatusoutput(command)

  if status != 0:
    raise IOError('gcov command failed.')

  results = ParseGcovOutput(output, srcRoot, exceptDirectory)
  results = sorted(results, key=GetExecuted, reverse=True)

  # print result
  PrintResult(results)

def main(argv):
  parser = OptionParser()
  parser.add_option('-d', '--dir', dest='dir', default='.',
                   help='Directory for searching object files', metavar='DIR')
  parser.add_option('-s', '--source', dest='source', default='.',
                   help='Root directory of sources', metavar='DIR')
  parser.add_option('-e', '--except', dest='except_', default=None,
                    help='Directory to except', metavar='DIR')
  parser.add_option('-o', '--out', dest='out', default='coverage.txt',
                   help='Output file name', metavar='FILE')
  (options, args) = parser.parse_args()

  GenerateCovReport(options.dir, options.source, options.except_, options.out)

  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv))
<|endoftext|>


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

from deform import Form, ValidationFailure
from fanstatic import Group
from fanstatic import Library
from fanstatic import Resource
from js.jquery import jquery
from js.jquery_form import jquery_form
from js.jquery_maskedinput import jquery_maskedinput
from js.jquery_maskmoney import jquery_maskmoney
from js.jquery_sortable import jquery_sortable
from js.jquery_timepicker_addon import timepicker
from js.jqueryui import ui_autocomplete
from js.jqueryui import ui_datepicker
from js.jqueryui import ui_sortable
from js.modernizr import modernizr
from js.select2 import select2
from js.tinymce import tinymce
from pkg_resources import resource_filename

deform_dir = resource_filename(
    "deform",
    "static")
library = Library(
    "deform",
    deform_dir)

deform_js = Resource(
    library,
    "scripts/deform.js",
    depends=[jquery, ])

deform_form_css = Resource(
    library,
    "css/form.css")
deform_beautify_css = Resource(
    library,
    "css/beautify.css")

deform_css = Group([deform_form_css, deform_beautify_css, ])

deform_basic = Group([deform_form_css, deform_js, ])
deform = Group([deform_css, deform_js, ])

modernizr = Resource(
    library,
    'scripts/modernizr.custom.input-types-and-atts.js')

typeahead_js = Resource(
    library,
    'scripts/typeahead.min.js',
    depends=[jquery, ])
typeahead_css = Resource(
    library,
    'css/typeahead.css')
typeahead = Group([typeahead_js, typeahead_css])

fileupload = Resource(
    library,
    'scripts/file_upload.js')

pickadate_js_legacy = Resource(
    library,
    'pickadate/legacy.js')
pickadate_js_base = Resource(
    library,
    'pickadate/picker.js',
    depends=[pickadate_js_legacy, ])
pickadate_js_date = Resource(
    library,
    'pickadate/picker.date.js',
    depends=[pickadate_js_base, ])
pickadate_js_time = Resource(
    library,
    'pickadate/picker.time.js',
    depends=[pickadate_js_base, ])
pickadate_js = Group([
    pickadate_js_date,
    pickadate_js_time, ])
pickadate_css_base = Resource(
    library,
    'pickadate/themes/default.css')
pickadate_css_date = Resource(
    library,
    'pickadate/themes/default.date.css',
    depends=[pickadate_css_base, ])
pickadate_css_time = Resource(
    library,
    'pickadate/themes/default.time.css',
    depends=[pickadate_css_base, ])
pickadate_css = Group([
    pickadate_css_date,
    pickadate_css_time, ])

pickadate = Group([pickadate_js, pickadate_css, ])

resource_mapping = {
    'datetimepicker': [timepicker, ],
    'deform': [deform_js, ],
    'fileupload': [fileupload, ],
    'jquery': [jquery, ],
    'jquery.form': [jquery_form, ],
    'jquery.maskMoney': [jquery_maskmoney, ],
    'jquery.maskedinput': [jquery_maskedinput, ],
    'jqueryui': [ui_autocomplete, ui_datepicker, ui_sortable, ],
    'modernizr': [modernizr, ],
    'pickadate': [pickadate, ],
    'select2': [select2, ],
    'sortable': [jquery_sortable, ],
    'tinymce': [tinymce, ],
    'typeahead': [typeahead, ],
}

def auto_need(form):
    """Automatically ``need()`` the relevant Fanstatic resources for a form.

    This function automatically utilises libraries in the ``js.*`` namespace
    (such as ``js.jquery``, ``js.tinymce`` and so forth) to allow Fanstatic
    to better manage these resources (caching, minifications) and avoid
    duplication across the rest of your application.
    """

    requirements = form.get_widget_requirements()

    for library, version in requirements:
        resources = resource_mapping[library]
        if not isinstance(resources, list):  # pragma: no cover (bw compat only)
            resources = [resources]
        for resource in resources:
            resource.need()

    if form.use_ajax:
        jquery_form.need()

def includeme(config=None):

    _marker = object()

    def form_render(self, appstruct=_marker, **kw):

        if appstruct is not _marker:  # pragma: no cover  (copied from deform)
            kw['appstruct'] = appstruct

        html = super(Form, self).render(**kw)
        auto_need(self)

        return html

    def validationfailure_render(self):

        auto_need(self.field)

        return self.field.widget.serialize(self.field, self.cstruct)

    def patch_deform():

        Form.render = form_render
        ValidationFailure.render = validationfailure_render

    patch_deform()
<commit_msg>Fix pickadate translation. Added fanstatic for it<commit_after># -*- coding: utf-8 -*-

from deform import Form, ValidationFailure
from fanstatic import Group
from fanstatic import Library
from fanstatic import Resource
from js.jquery import jquery
from js.jquery_form import jquery_form
from js.jquery_maskedinput import jquery_maskedinput
from js.jquery_maskmoney import jquery_maskmoney
from js.jquery_sortable import jquery_sortable
from js.jquery_timepicker_addon import timepicker
from js.jqueryui import ui_autocomplete
from js.jqueryui import ui_datepicker
from js.jqueryui import ui_sortable
from js.modernizr import modernizr
from js.select2 import select2
from js.tinymce import tinymce
from pkg_resources import resource_filename

deform_dir = resource_filename(
    "deform",
    "static")
library = Library(
    "deform",
    deform_dir)

deform_js = Resource(
    library,
    "scripts/deform.js",
    depends=[jquery, ])

deform_form_css = Resource(
    library,
    "css/form.css")
deform_beautify_css = Resource(
    library,
    "css/beautify.css")

deform_css = Group([deform_form_css, deform_beautify_css, ])

deform_basic = Group([deform_form_css, deform_js, ])
deform = Group([deform_css, deform_js, ])

modernizr = Resource(
    library,
    'scripts/modernizr.custom.input-types-and-atts.js')

typeahead_js = Resource(
    library,
    'scripts/typeahead.min.js',
    depends=[jquery, ])
typeahead_css = Resource(
    library,
    'css/typeahead.css')
typeahead = Group([typeahead_js, typeahead_css])

fileupload = Resource(
    library,
    'scripts/file_upload.js')

pickadate_js_legacy = Resource(
    library,
    'pickadate/legacy.js')
pickadate_js_base = Resource(
    library,
    'pickadate/picker.js',
    depends=[pickadate_js_legacy, ])
pickadate_js_date = Resource(
    library,
    'pickadate/picker.date.js',
    depends=[pickadate_js_base, ])
pickadate_js_time = Resource(
    library,
    'pickadate/picker.time.js',
    depends=[pickadate_js_base, ])
pickadate_js = Group([
    pickadate_js_date,
    pickadate_js_time, ])
pickadate_css_base = Resource(
    library,
    'pickadate/themes/default.css')
pickadate_css_date = Resource(
    library,
    'pickadate/themes/default.date.css',
    depends=[pickadate_css_base, ])
pickadate_css_time = Resource(
    library,
    'pickadate/themes/default.time.css',
    depends=[pickadate_css_base, ])
pickadate_css = Group([
    pickadate_css_date,
    pickadate_css_time, ])

pickadate = Group([pickadate_js, pickadate_css, ])

pickadate_ar = Resource(
    library,
    'pickadate/translations/ar.js',
    depends=[pickadate])

pickadate_bg = Resource(
    library,
    'pickadate/translations/bg_BG.js',
    depends=[pickadate])

pickadate_bs_BA = Resource(
    library,
    'pickadate/translations/bs_BA.js',
    depends=[pickadate])

pickadate_ca_ES = Resource(
    library,
    'pickadate/translations/ca_ES.js',
    depends=[pickadate])

pickadate_cs_CZ = Resource(
    library,
    'pickadate/translations/cs_CZ.js',
    depends=[pickadate])

pickadate_da_DK = Resource(
    library,
    'pickadate/translations/da_DK.js',
    depends=[pickadate])

pickadate_de = Resource(
    library,
    'pickadate/translations/de_DE.js',
    depends=[pickadate])

pickadate_el_GR = Resource(
    library,
    'pickadate/translations/el_GR.js',
    depends=[pickadate])

pickadate_es = Resource(
    library,
    'pickadate/translations/es_ES.js',
    depends=[pickadate])

pickadate_et_EE = Resource(
    library,
    'pickadate/translations/et_EE.js',
    depends=[pickadate])

pickadate_eu_ES = Resource(
    library,
    'pickadate/translations/eu_ES.js',
    depends=[pickadate])

pickadate_fa_ir = Resource(
    library,
    'pickadate/translations/fa_ir.js',
    depends=[pickadate])

pickadate_fi = Resource(
    library,
    'pickadate/translations/fi_FI.js',
    depends=[pickadate])

pickadate_fr = Resource(
    library,
    'pickadate/translations/fr_FR.js',
    depends=[pickadate])

pickadate_gl_ES = Resource(
    library,
    'pickadate/translations/gl_ES.js',
    depends=[pickadate])

pickadate_he_IL = Resource(
    library,
    'pickadate/translations/he_IL.js',
    depends=[pickadate])

pickadate_hi_IN = Resource(
    library,
    'pickadate/translations/hi_IN.js',
    depends=[pickadate])

pickadate_hr = Resource(
    library,
    'pickadate/translations/hr_HR.js',
    depends=[pickadate])

pickadate_hu = Resource(
    library,
    'pickadate/translations/hu_HU.js',
    depends=[pickadate])

pickadate_id = Resource(
    library,
    'pickadate/translations/id_ID.js',
    depends=[pickadate])

pickadate_is = Resource(
    library,
    'pickadate/translations/is_IS.js',
    depends=[pickadate])

pickadate_it = Resource(
    library,
    'pickadate/translations/it_IT.js',
    depends=[pickadate])

pickadate_ja_JP = Resource(
    library,
    'pickadate/translations/ja_JP.js',
    depends=[pickadate])

pickadate_ko_KR = Resource(
    library,
    'pickadate/translations/ko_KR.js',
    depends=[pickadate])

pickadate_lt = Resource(
    library,
    'pickadate/translations/lt_LT.js',
    depends=[pickadate])

pickadate_lv = Resource(
    library,
    'pickadate/translations/lv_LV.js',
    depends=[pickadate])

pickadate_nb_NO = Resource(
    library,
    'pickadate/translations/nb_NO.js',
    depends=[pickadate])

pickadate_ne_NP = Resource(
    library,
    'pickadate/translations/ne_NP.js',
    depends=[pickadate])

pickadate_nl = Resource(
    library,
    'pickadate/translations/nl_NL.js',
    depends=[pickadate])

pickadate_pl = Resource(
    library,
    'pickadate/translations/pl_PL.js',
    depends=[pickadate])

pickadate_pt_BR = Resource(
    library,
    'pickadate/translations/pt_BR.js',
    depends=[pickadate])

pickadate_pt = Resource(
    library,
    'pickadate/translations/pt_PT.js',
    depends=[pickadate])

pickadate_ro = Resource(
    library,
    'pickadate/translations/ro_RO.js',
    depends=[pickadate])

pickadate_ru = Resource(
    library,
    'pickadate/translations/ru_RU.js',
    depends=[pickadate])

pickadate_sl_SI = Resource(
    library,
    'pickadate/translations/sl_SI.js',
    depends=[pickadate])

pickadate_sv_SE = Resource(
    library,
    'pickadate/translations/sv_SE.js',
    depends=[pickadate])

pickadate_th = Resource(
    library,
    'pickadate/translations/th_TH.js',
    depends=[pickadate])

pickadate_tr = Resource(
    library,
    'pickadate/translations/tr_TR.js',
    depends=[pickadate])

pickadate_uk_UA = Resource(
    library,
    'pickadate/translations/uk_UA.js',
    depends=[pickadate])

pickadate_vi_VN = Resource(
    library,
    'pickadate/translations/vi_VN.js',
    depends=[pickadate])

pickadate_zh_CN = Resource(
    library,
    'pickadate/translations/zh_CN.js',
    depends=[pickadate])

pickadate_zh_TW = Resource(
    library,
    'pickadate/translations/zh_TW.js',
    depends=[pickadate])

pickadate_locales = {
    'pickadate_ar': [pickadate_ar, ],
    'pickadate_bg': [pickadate_bg, ],
    'pickadate_bs_BA': [pickadate_bs_BA, ],
    'pickadate_ca_ES': [pickadate_ca_ES, ],
    'pickadate_cs_CZ': [pickadate_cs_CZ, ],
    'pickadate_da_DK': [pickadate_da_DK, ],
    'pickadate_de': [pickadate_de, ],
    'pickadate_el_GR': [pickadate_el_GR, ],
    'pickadate_es': [pickadate_es, ],
    'pickadate_en': pickadate_js,
    'pickadate_et_EE': [pickadate_et_EE, ],
    'pickadate_eu_ES': [pickadate_eu_ES, ],
    'pickadate_fa_ir': [pickadate_fa_ir, ],
    'pickadate_fi': [pickadate_fi, ],
    'pickadate_fr': [pickadate_fr, ],
    'pickadate_gl_ES': [pickadate_gl_ES, ],
    'pickadate_he_IL': [pickadate_he_IL, ],
    'pickadate_hi_IN': [pickadate_hi_IN, ],
    'pickadate_hr': [pickadate_hr, ],
    'pickadate_hu': [pickadate_hu, ],
    'pickadate_id': [pickadate_id, ],
    'pickadate_is': [pickadate_is, ],
    'pickadate_it': [pickadate_it, ],
    'pickadate_ja_JP': [pickadate_ja_JP, ],
    'pickadate_ko_KR': [pickadate_ko_KR, ],
    'pickadate_lt': [pickadate_lt, ],
    'pickadate_lv': [pickadate_lv, ],
    'pickadate_nb_NO': [pickadate_nb_NO, ],
    'pickadate_ne_NP': [pickadate_ne_NP, ],
    'pickadate_nl': [pickadate_nl, ],
    'pickadate_pl': [pickadate_pl, ],
    'pickadate_pt_BR': [pickadate_pt_BR, ],
    'pickadate_pt': [pickadate_pt, ],
    'pickadate_ro': [pickadate_ro, ],
    'pickadate_ru': [pickadate_ru, ],
    'pickadate_sl_SI': [pickadate_sl_SI, ],
    'pickadate_sv_SE': [pickadate_sv_SE, ],
    'pickadate_th': [pickadate_th, ],
    'pickadate_tr': [pickadate_tr, ],
    'pickadate_uk_UA': [pickadate_uk_UA, ],
    'pickadate_vi_VN': [pickadate_vi_VN, ],
    'pickadate_zh_CN': [pickadate_zh_CN, ],
    'pickadate_zh_TW': [pickadate_zh_TW, ],
}

resource_mapping = {
    'datetimepicker': [timepicker, ],
    'deform': [deform_js, ],
    'fileupload': [fileupload, ],
    'jquery': [jquery, ],
    'jquery.form': [jquery_form, ],
    'jquery.maskMoney': [jquery_maskmoney, ],
    'jquery.maskedinput': [jquery_maskedinput, ],
    'jqueryui': [ui_autocomplete, ui_datepicker, ui_sortable, ],
    'modernizr': [modernizr, ],
    'pickadate': [pickadate, ],
    'select2': [select2, ],
    'sortable': [jquery_sortable, ],
    'tinymce': [tinymce, ],
    'typeahead': [typeahead, ],
}

def auto_need(form):
    """Automatically ``need()`` the relevant Fanstatic resources for a form.

    This function automatically utilises libraries in the ``js.*`` namespace
    (such as ``js.jquery``, ``js.tinymce`` and so forth) to allow Fanstatic
    to better manage these resources (caching, minifications) and avoid
    duplication across the rest of your application.
    """

    requirements = form.get_widget_requirements()

    for library, version in requirements:
        resources = resource_mapping[library]
        if not isinstance(resources, list):  # pragma: no cover (bw compat only)
            resources = [resources]
        for resource in resources:
            resource.need()

    if form.use_ajax:
        jquery_form.need()

def set_pickadate_locales():
    from deform import widget
    for key, value in pickadate_locales.items():
        resource_mapping[key] = value
        rendered = None
        if isinstance(value, list):
            rendered = value[0].render('deform:static')
        elif isinstance(value, Group):
            rendered = []
            for assest in value.list_assets():
                rendered.append(assest.render('deform:static'))
        else:
            rendered = value
        widget.default_resource_registry.set_js_resources(key, None, rendered)

def includeme(config=None):

    _marker = object()

    def form_render(self, appstruct=_marker, **kw):

        if appstruct is not _marker:  # pragma: no cover  (copied from deform)
            kw['appstruct'] = appstruct

        html = super(Form, self).render(**kw)
        auto_need(self)

        return html

    def validationfailure_render(self):

        auto_need(self.field)

        return self.field.widget.serialize(self.field, self.cstruct)

    def patch_deform():

        Form.render = form_render
        ValidationFailure.render = validationfailure_render
        set_pickadate_locales()

    patch_deform()
<|endoftext|>


<commit_before>#!/usr/local/bin/python -t
# $Id$

"""Gnuplot_test.py -- Exercise the Gnuplot.py module.

Copyright (C) 1998,1999 Michael Haggerty

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; it is
available at <http://www.fsf.org/copyleft/gpl.html>, or by writing to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.

"""

__cvs_version__ = 'CVS version $Revision$'

import sys, math
from Numeric import *
import Gnuplot
gp = Gnuplot # abbreviation

def wait():
    raw_input('Please press return...\n')

def main():
    """Exercise the Gnuplot module."""

    # Make a temporary file:
    file1 = gp.TempFile() # will be deleted upon exit
    f = open(file1.filename, 'w')
    for x in arange(100)/5. - 10.:
        f.write('%s %s %s\n' % (x, math.cos(x), math.sin(x)))
    f.close()

    g = gp.Gnuplot()
    print 'Generate a File from a filename'
    g.plot(gp.File(file1.filename))
    wait()
    print 'Generate a File given a TempFile object'
    g.plot(gp.File(file1))
    wait()

    g.title('Title')
    g.xlabel('x')
    g.ylabel('y')
    print 'Set title and axis labels'
    g.replot()
    wait()

    print 'Style lines'
    g.plot(gp.File(file1.filename, with='lines'))
    wait()
    print 'using=1, using=(1,)'
    g.plot(gp.File(file1.filename, using=1, with='lines'),
           gp.File(file1.filename, using=(1,), with='points'))
    wait()
    print 'using=(1,2), using="1:3"'
    g.plot(gp.File(file1.filename, using=(1,2)),
           gp.File(file1.filename, using='1:3'))
    wait()
    print 'title=None'
    g.plot(gp.File(file1.filename, title=None))
    wait()
    print 'title="title"'
    g.plot(gp.File(file1.filename, title='title'))
    wait()

    print 'Test changing File attributes after construction:'
    f = gp.File(file1.filename)
    print 'Original'
    g.plot(f)
    wait()
    print 'Style linespoints'
    f.set_option(with='linespoints')
    g.plot(f)
    wait()
    print 'using=(1,3)'
    f.set_option(using=(1,3))
    g.plot(f)
    wait()
    print 'title=None'
    f.set_option(title=None)
    g.plot(f)
    wait()

    g.ylabel('x^2') # take advantage of enhanced postscript mode
    print ('\n******** Generating postscript file '
           '"gnuplot_test_plot.ps" ********\n')
    g.hardcopy('gnuplot_test_plot.ps', enhanced=1, color=1)

    # Demonstrate a 3-d plot:
    # set up x and y values at which the function will be tabulated:
    x = arange(35)/2.0
    y = arange(30)/10.0 - 1.5
    # Make a 2-d array containing a function of x and y.  First create
    # xm and ym which contain the x and y values in a matrix form that
    # can be `broadcast' into a matrix of the appropriate shape:
    xm = x[:,NewAxis]
    ym = y[NewAxis,:]
    m = (sin(xm) + 0.1*xm) - ym**2
    g('set parametric')
    g('set data style lines')
    g('set hidden')
    g('set contour base')
    g.xlabel('x')
    g.ylabel('y')
    # The `binary=1' option would cause communication with gnuplot to
    # be in binary format, which is considerably faster and uses less
    # disk space.  (This only works with the splot command due to
    # limitations of gnuplot.)  `binary=1' is the default, but here we
    # disable binary because older versions of gnuplot don't allow
    # binary data.  Change this to `binary=1' (or omit the binary
    # option) to get the advantage of binary format.
    g.splot(gp.GridData(m,x,y, binary=0))

    # Delay so the user can see the plots:
    sys.stderr.write('Three plots should have appeared on your screen '
                     '(they may be overlapping).\n')
    wait()

if __name__ == '__main__':
    main()

<commit_msg>Added more tests.<commit_after>#!/usr/local/bin/python -t
# $Id$

"""Gnuplot_test.py -- Exercise the Gnuplot.py module.

Copyright (C) 1998,1999 Michael Haggerty

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; it is
available at <http://www.fsf.org/copyleft/gpl.html>, or by writing to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.

"""

__cvs_version__ = 'CVS version $Revision$'

import sys, math
import Numeric
from Numeric import *
import Gnuplot
gp = Gnuplot # abbreviation

def wait():
    raw_input('Please press return...\n')

def main():
    """Exercise the Gnuplot module."""

    # Make a temporary file:
    file1 = gp.TempFile() # will be deleted upon exit
    f = open(file1.filename, 'w')
    for x in arange(100)/5. - 10.:
        f.write('%s %s %s\n' % (x, math.cos(x), math.sin(x)))
    f.close()

    g = gp.Gnuplot()

    ############### test Func ########################################
    print 'Plot a gnuplot-generated function'
    g.plot(gp.Func('sin(x)'))
    wait()

    print 'Set title and axis labels and try replot()'
    g.title('Title')
    g.xlabel('x')
    g.ylabel('y')
    g.replot()
    wait()

    print 'Style linespoints'
    g.plot(gp.Func('sin(x)', with='linespoints'))
    wait()
    print 'title=None'
    g.plot(gp.Func('sin(x)', title=None))
    wait()
    print 'title="Sine of x"'
    g.plot(gp.Func('sin(x)', title='Sine of x'))
    wait()

    print 'Change Func attributes after construction:'
    f = gp.Func('sin(x)')
    print 'Original'
    g.plot(f)
    wait()
    print 'Style linespoints'
    f.set_option(with='linespoints')
    g.plot(f)
    wait()
    print 'title=None'
    f.set_option(title=None)
    g.plot(f)
    wait()
    print 'title="Sine of x"'
    f.set_option(title='Sine of x')
    g.plot(f)
    wait()

    ############### test File ########################################
    print 'Generate a File from a filename'
    g.plot(gp.File(file1.filename))
    wait()
    print 'Generate a File given a TempFile object'
    g.plot(gp.File(file1))
    wait()

    print 'Style lines'
    g.plot(gp.File(file1.filename, with='lines'))
    wait()
    print 'using=1, using=(1,)'
    g.plot(gp.File(file1.filename, using=1, with='lines'),
           gp.File(file1.filename, using=(1,), with='points'))
    wait()
    print 'using=(1,2), using="1:3"'
    g.plot(gp.File(file1.filename, using=(1,2)),
           gp.File(file1.filename, using='1:3'))
    wait()
    print 'title=None'
    g.plot(gp.File(file1.filename, title=None))
    wait()
    print 'title="title"'
    g.plot(gp.File(file1.filename, title='title'))
    wait()

    print 'Change File attributes after construction:'
    f = gp.File(file1.filename)
    print 'Original'
    g.plot(f)
    wait()
    print 'Style linespoints'
    f.set_option(with='linespoints')
    g.plot(f)
    wait()
    print 'using=(1,3)'
    f.set_option(using=(1,3))
    g.plot(f)
    wait()
    print 'title=None'
    f.set_option(title=None)
    g.plot(f)
    wait()

    ############### test Data ########################################
    x = arange(100)/5. - 10.
    y1 = Numeric.cos(x)
    y2 = Numeric.sin(x)
    d = Numeric.array((x,y1,y2))

    print 'Plot Data, specified column-by-column'
    g.plot(gp.Data(x,y1))
    wait()
    print 'Plot Data, specified by an array'
    g.plot(gp.Data(d))
    wait()
    print 'with="lp 4 4"'
    g.plot(gp.Data(d, with='lp 4 4'))
    wait()
    print 'cols=0'
    g.plot(gp.Data(d, cols=0))
    wait()
    print 'cols=(0,1), cols=(0,2)'
    g.plot(gp.Data(d, cols=(0,1)),
           gp.Data(d, cols=(0,2)))
    wait()
    print 'title=None'
    g.plot(gp.Data(d, title=None))
    wait()
    print 'title="Cosine of x"'
    g.plot(gp.Data(d, title='Cosine of x'))
    wait()

    ############### test shortcuts ###################################
    print 'plot Func and Data using shortcuts'
    g.plot('sin(x)', d)
    wait()

    ############### test GridData ####################################
    # set up x and y values at which the function will be tabulated:
    x = arange(35)/2.0
    y = arange(30)/10.0 - 1.5
    # Make a 2-d array containing a function of x and y.  First create
    # xm and ym which contain the x and y values in a matrix form that
    # can be `broadcast' into a matrix of the appropriate shape:
    xm = x[:,NewAxis]
    ym = y[NewAxis,:]
    m = (sin(xm) + 0.1*xm) - ym**2
    g('set parametric')
    g('set data style lines')
    g('set hidden')
    g('set contour base')
    g.xlabel('x')
    g.ylabel('y')
    # The `binary=1' option would cause communication with gnuplot to
    # be in binary format, which is considerably faster and uses less
    # disk space.  (This only works with the splot command due to
    # limitations of gnuplot.)  `binary=1' is the default, but here we
    # disable binary because older versions of gnuplot don't allow
    # binary data.  Change this to `binary=1' (or omit the binary
    # option) to get the advantage of binary format.
    g.splot(gp.GridData(m,x,y, binary=0))

    ############### test HardCopy ####################################
    g.ylabel('x^2') # take advantage of enhanced postscript mode
    print ('\n******** Generating postscript file '
           '"gnuplot_test_plot.ps" ********\n')
    g.hardcopy('gnuplot_test_plot.ps', enhanced=1, color=1)

if __name__ == '__main__':
    main()

<|endoftext|>


<commit_before>

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')bz9gujog#hg6#gn*egifv3t)zf-h9+uwhwn(kk+hz$xr60kf+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

BASE_API_URL = "http://localhost:8000"

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gogong.v1',
)

MIDDLEWARE_CLASSES = (
    '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',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'gogong.urls'

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

WSGI_APPLICATION = 'gogong.wsgi.application'

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

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

# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/

STATIC_URL = '/static/'
<commit_msg>added env set base URL<commit_after>

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')bz9gujog#hg6#gn*egifv3t)zf-h9+uwhwn(kk+hz$xr60kf+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

BASE_API_URL = "http://localhost:8000"
BASE_API_URL_ENV = os.environ.get('BASE_URL')
if BASE_API_URL_ENV:
    print("Base URL set as:", BASE_API_URL_ENV)
    BASE_API_URL = BASE_API_URL_ENV

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gogong.v1',
)

MIDDLEWARE_CLASSES = (
    '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',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'gogong.urls'

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

WSGI_APPLICATION = 'gogong.wsgi.application'

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

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

# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/

STATIC_URL = '/static/'
<|endoftext|>


<commit_before>#############################################################################
#
# Copyright (c) 2010 by Casey Duncan
# All Rights Reserved.
#
# This software is subject to the provisions of the MIT License
# A copy of the license should accompany this distribution.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#
#############################################################################
"""Control systems for binding controls to game logic"""

import grease
from pyglet.window import key

class KeyControls(grease.System):
	"""System that maps subclass-defined action methods to keys.

	Keys may be mapped in the subclass definition using decorators
	defined here as class methods or at runtime using the ``bind_key_*``
	instance methods.

	See :ref:`an example implementation in the tutorial <tut-controls-example>`.
	"""
	MODIFIER_MASK = ~(key.MOD_NUMLOCK | key.MOD_SCROLLLOCK | key.MOD_CAPSLOCK)
	"""The MODIFIER_MASK allows you to filter out modifier keys that should be
	ignored by the application. By default, numlock and scrolllock are
	ignored.
	"""

	world = None
	""":class:`grease.World` object this system is bound to"""

	def __init__(self):
		self._key_press_map = {}
		self._key_release_map = {}
		self._key_hold_map = {}
		for name in self.__class__.__dict__:
			member = getattr(self, name)
			if hasattr(member, '_grease_hold_key_binding'):
				for binding in member._grease_hold_key_binding:
					self.bind_key_hold(member, *binding)
			if hasattr(member, '_grease_press_key_binding'):
				for binding in member._grease_press_key_binding:
					self.bind_key_press(member, *binding)
			if hasattr(member, '_grease_release_key_binding'):
				for binding in member._grease_release_key_binding:
					self.bind_key_release(member, *binding)
		self.held_keys = set()

	## decorator methods for binding methods to key input events ##

	@classmethod
	def key_hold(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is held down"""
		def bind(f):
			if not hasattr(f, '_grease_hold_key_binding'):
				f._grease_hold_key_binding = []
			f._grease_hold_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	@classmethod
	def key_press(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is initially depressed"""
		def bind(f):
			if not hasattr(f, '_grease_press_key_binding'):
				f._grease_press_key_binding = []
			f._grease_press_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	@classmethod
	def key_release(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is released"""
		def bind(f):
			if not hasattr(f, '_grease_release_key_binding'):
				f._grease_release_key_binding = []
			f._grease_release_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	## runtime binding methods ##

	def bind_key_hold(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is
		held down, this replaces any existing key hold binding for this key.
		To unbind the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_hold_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_hold_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def bind_key_press(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is initially
		pressed, this replaces any existing key hold binding for this key. To unbind
		the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_press_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_press_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def bind_key_release(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is releaseed,
		this replaces any existing key hold binding for this key. To unbind
		the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_release_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_release_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def step(self, dt):
		"""invoke held key functions"""
		already_run = set()
		for key in self.held_keys:
			func = self._key_hold_map.get(key)
			if func is not None and func not in already_run:
				already_run.add(func)
				func(dt)

	def on_key_press(self, key, modifiers):
		"""Handle pyglet key press. Invoke key press methods and
		activate key hold functions
		"""
		key_mod = (key, modifiers & self.MODIFIER_MASK)
		if key_mod in self._key_press_map:
			self._key_press_map[key_mod]()
		self.held_keys.add(key_mod)

	def on_key_release(self, key, modifiers):
		"""Handle pyglet key release. Invoke key release methods and
		deactivate key hold functions
		"""
		key_mod = (key, modifiers & self.MODIFIER_MASK)
		if key_mod in self._key_release_map:
			self._key_release_map[key_mod]()
		self.held_keys.discard(key_mod)

if __name__ == '__main__':
	import pyglet

	class TestKeyControls(KeyControls):

		MODIFIER_MASK = ~(key.MOD_NUMLOCK | key.MOD_SCROLLLOCK | key.MOD_CTRL)

		remapped = False

		@KeyControls.key_hold(key.UP)
		@KeyControls.key_hold(key.W)
		def up(self, dt):
			print 'UP!'

		@KeyControls.key_hold(key.LEFT)
		@KeyControls.key_hold(key.A)
		def left(self, dt):
			print 'LEFT!'

		@KeyControls.key_hold(key.RIGHT)
		@KeyControls.key_hold(key.D)
		def right(self, dt):
			print 'RIGHT!'

		@KeyControls.key_hold(key.DOWN)
		@KeyControls.key_hold(key.S)
		def down(self, dt):
			print 'DOWN!'

		@KeyControls.key_press(key.SPACE)
		def fire(self):
			print 'FIRE!'

		@KeyControls.key_press(key.R)
		def remap_keys(self):
			if not self.remapped:
				self.bind_key_hold(None, key.W)
				self.bind_key_hold(None, key.A)
				self.bind_key_hold(None, key.S)
				self.bind_key_hold(None, key.D)
				self.bind_key_hold(self.up, key.I)
				self.bind_key_hold(self.left, key.J)
				self.bind_key_hold(self.right, key.L)
				self.bind_key_hold(self.down, key.K)
			else:
				self.bind_key_hold(None, key.I)
				self.bind_key_hold(None, key.J)
				self.bind_key_hold(None, key.K)
				self.bind_key_hold(None, key.L)
				self.bind_key_hold(self.up, key.W)
				self.bind_key_hold(self.left, key.A)
				self.bind_key_hold(self.right, key.D)
				self.bind_key_hold(self.down, key.S)
			self.remapped = not self.remapped

	window = pyglet.window.Window()
	window.clear()
	controls = TestKeyControls()
	window.push_handlers(controls)
	pyglet.clock.schedule_interval(controls.step, 0.5)
	pyglet.app.run()

<commit_msg>Fix MODIFER_MASK docstring<commit_after>#############################################################################
#
# Copyright (c) 2010 by Casey Duncan
# All Rights Reserved.
#
# This software is subject to the provisions of the MIT License
# A copy of the license should accompany this distribution.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#
#############################################################################
"""Control systems for binding controls to game logic"""

import grease
from pyglet.window import key

class KeyControls(grease.System):
	"""System that maps subclass-defined action methods to keys.

	Keys may be mapped in the subclass definition using decorators
	defined here as class methods or at runtime using the ``bind_key_*``
	instance methods.

	See :ref:`an example implementation in the tutorial <tut-controls-example>`.
	"""
	MODIFIER_MASK = ~(key.MOD_NUMLOCK | key.MOD_SCROLLLOCK | key.MOD_CAPSLOCK)
	"""The MODIFIER_MASK allows you to filter out modifier keys that should be
	ignored by the application. By default, capslock, numlock, and scrolllock
	are ignored.
	"""

	world = None
	""":class:`grease.World` object this system is bound to"""

	def __init__(self):
		self._key_press_map = {}
		self._key_release_map = {}
		self._key_hold_map = {}
		for name in self.__class__.__dict__:
			member = getattr(self, name)
			if hasattr(member, '_grease_hold_key_binding'):
				for binding in member._grease_hold_key_binding:
					self.bind_key_hold(member, *binding)
			if hasattr(member, '_grease_press_key_binding'):
				for binding in member._grease_press_key_binding:
					self.bind_key_press(member, *binding)
			if hasattr(member, '_grease_release_key_binding'):
				for binding in member._grease_release_key_binding:
					self.bind_key_release(member, *binding)
		self.held_keys = set()

	## decorator methods for binding methods to key input events ##

	@classmethod
	def key_hold(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is held down"""
		def bind(f):
			if not hasattr(f, '_grease_hold_key_binding'):
				f._grease_hold_key_binding = []
			f._grease_hold_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	@classmethod
	def key_press(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is initially depressed"""
		def bind(f):
			if not hasattr(f, '_grease_press_key_binding'):
				f._grease_press_key_binding = []
			f._grease_press_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	@classmethod
	def key_release(cls, symbol, modifiers=0):
		"""Decorator to bind a method to be executed where a key is released"""
		def bind(f):
			if not hasattr(f, '_grease_release_key_binding'):
				f._grease_release_key_binding = []
			f._grease_release_key_binding.append((symbol, modifiers & cls.MODIFIER_MASK))
			return f
		return bind

	## runtime binding methods ##

	def bind_key_hold(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is
		held down, this replaces any existing key hold binding for this key.
		To unbind the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_hold_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_hold_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def bind_key_press(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is initially
		pressed, this replaces any existing key hold binding for this key. To unbind
		the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_press_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_press_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def bind_key_release(self, method, key, modifiers=0):
		"""Bind a method to a key at runtime to be invoked when the key is releaseed,
		this replaces any existing key hold binding for this key. To unbind
		the key entirely, pass ``None`` for method.
		"""
		if method is not None:
			self._key_release_map[key, modifiers & self.MODIFIER_MASK] = method
		else:
			try:
				del self._key_release_map[key, modifiers & self.MODIFIER_MASK]
			except KeyError:
				pass

	def step(self, dt):
		"""invoke held key functions"""
		already_run = set()
		for key in self.held_keys:
			func = self._key_hold_map.get(key)
			if func is not None and func not in already_run:
				already_run.add(func)
				func(dt)

	def on_key_press(self, key, modifiers):
		"""Handle pyglet key press. Invoke key press methods and
		activate key hold functions
		"""
		key_mod = (key, modifiers & self.MODIFIER_MASK)
		if key_mod in self._key_press_map:
			self._key_press_map[key_mod]()
		self.held_keys.add(key_mod)

	def on_key_release(self, key, modifiers):
		"""Handle pyglet key release. Invoke key release methods and
		deactivate key hold functions
		"""
		key_mod = (key, modifiers & self.MODIFIER_MASK)
		if key_mod in self._key_release_map:
			self._key_release_map[key_mod]()
		self.held_keys.discard(key_mod)

if __name__ == '__main__':
	import pyglet

	class TestKeyControls(KeyControls):

		MODIFIER_MASK = ~(key.MOD_NUMLOCK | key.MOD_SCROLLLOCK | key.MOD_CTRL)

		remapped = False

		@KeyControls.key_hold(key.UP)
		@KeyControls.key_hold(key.W)
		def up(self, dt):
			print 'UP!'

		@KeyControls.key_hold(key.LEFT)
		@KeyControls.key_hold(key.A)
		def left(self, dt):
			print 'LEFT!'

		@KeyControls.key_hold(key.RIGHT)
		@KeyControls.key_hold(key.D)
		def right(self, dt):
			print 'RIGHT!'

		@KeyControls.key_hold(key.DOWN)
		@KeyControls.key_hold(key.S)
		def down(self, dt):
			print 'DOWN!'

		@KeyControls.key_press(key.SPACE)
		def fire(self):
			print 'FIRE!'

		@KeyControls.key_press(key.R)
		def remap_keys(self):
			if not self.remapped:
				self.bind_key_hold(None, key.W)
				self.bind_key_hold(None, key.A)
				self.bind_key_hold(None, key.S)
				self.bind_key_hold(None, key.D)
				self.bind_key_hold(self.up, key.I)
				self.bind_key_hold(self.left, key.J)
				self.bind_key_hold(self.right, key.L)
				self.bind_key_hold(self.down, key.K)
			else:
				self.bind_key_hold(None, key.I)
				self.bind_key_hold(None, key.J)
				self.bind_key_hold(None, key.K)
				self.bind_key_hold(None, key.L)
				self.bind_key_hold(self.up, key.W)
				self.bind_key_hold(self.left, key.A)
				self.bind_key_hold(self.right, key.D)
				self.bind_key_hold(self.down, key.S)
			self.remapped = not self.remapped

	window = pyglet.window.Window()
	window.clear()
	controls = TestKeyControls()
	window.push_handlers(controls)
	pyglet.clock.schedule_interval(controls.step, 0.5)
	pyglet.app.run()

<|endoftext|>


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

import http.client
import time
import zlib

import lxml.html

BOROUGH_NAMES = ['Mitte', 'Friedrichshain-Kreuzberg', 'Pankow',
                 'Charlottenburg-Wilmersdorf', 'Spandau',
                 'Steglitz-Zehlendorf', 'Tempelhof-Schöneberg',
                 'Neukölln', 'Treptow-Köpenick', 'Marzahn-Hellersdorf',
                 'Lichtenberg', 'Reinickendorf']
BOROUGH_SLUGS = [b.lower().replace('ö', 'oe') for b in BOROUGH_NAMES]
BOROUGH_ID_DICT = dict(zip(BOROUGH_SLUGS, range(1,13)))

class Calendar():
    def __init__(self):
        self.events = []

    def add_event(self, event):
        self.events.append(event)

    def ics(self):
        if not self.events:
            return None
        ics = []
        ics.append('BEGIN:VCALENDAR')
        ics.append('VERSION:2.0')
        ics.append('PRODID:https://elchenberg.me')
        ics.append('X-WR-CALNAME:BVV %s: %s' % (self.borough,
                                                self.committee))
        ics.append('BEGIN:VTIMEZONE')
        ics.append('TZID:Europe/Berlin')
        ics.append('BEGIN:DAYLIGHT')
        ics.append('TZOFFSETFROM:+0100')
        ics.append('TZOFFSETTO:+0200')
        ics.append('TZNAME:CEST')
        ics.append('DTSTART:19700329T020000')
        ics.append('RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=3')
        ics.append('END:DAYLIGHT')
        ics.append('BEGIN:STANDARD')
        ics.append('TZOFFSETFROM:+0200')
        ics.append('TZOFFSETTO:+0100')
        ics.append('TZNAME:CET')
        ics.append('DTSTART:19701025T030000')
        ics.append('RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10')
        ics.append('END:STANDARD')
        ics.append('END:VTIMEZONE')
        for event in self.events:
            ics.append(event.ics())
        ics.append('END:VCALENDAR')
        return '\r\n'.join(ics)

class Event():
    def __init__(self):
        self.url = None

    def ics(self):
        ics = []
        ics.append('BEGIN:VEVENT')
        ics.append('UID:%s' % self.uid)
        ics.append('DTSTAMP:%s' % self.dtstamp)
        ics.append('DTSTART;TZID=Europe/Berlin:%s' % self.dtstart)
        ics.append('SUMMARY:%s' % self.summary)
        if self.url:
            ics.append('DESCRIPTION:%s\\n%s' % (self.description, self.url))
            ics.append('URL:%s' % self.url)
        else:
            ics.append('DESCRIPTION:%s' % self.description)
        ics.append('END:VEVENT')
        return '\r\n'.join(ics)

REQUEST_WAIT = 3
SESSION = http.client.HTTPSConnection('www.berlin.de', timeout=6)
request_time = time.time()

def get_response_text(url):
    global request_time

    elapsed_time = time.time() - request_time
    if elapsed_time < REQUEST_WAIT:
        time.sleep(REQUEST_WAIT - elapsed_time)

    SESSION.request('GET', url, headers={'Accept-Encoding': 'gzip'})
    print('GET', url)
    response = SESSION.getresponse()
    request_time = time.time()

    # assert response.status == 200
    # assert response.getheader('Content-Encoding') == 'gzip'

    gzip_data = response.read()

    # Tested decompression using different window size and buffer size values.
    # The only working window size values are 31 and 47 so I am going for 47
    # because it is in the range where the logarithm 'automatically accepts
    # either the zlib or gzip format'.
    # As for buffer size it seems to be best to go with the default value.
    # https://docs.python.org/3/library/zlib.html#zlib.decompress
    raw_data = zlib.decompress(gzip_data, 47)

    try:
        response_text = raw_data.decode('latin-1', 'strict')
    except UnicodeDecodeError:
        response_text = raw_data.decode('windows-1252', 'strict')
    return response_text

def get_date_query():
    today = time.localtime()
    year, month = today[0:2]
    template = 'YYV=%s&MMV=%s&YYB=%s&MMB=%s'
    date_query = template % (year, month, year, month + 1)
    if month > 12:
        date_query = template % (year, month, year + 1, 1)
    return date_query

def is_borough_id(obj):
    try:
        obj = int(obj)
        if not 1 <= obj <= 12:
            raise ValueError()
        return True
    except ValueError:
        return False

def get_borough_id(obj):
    if is_borough_id(obj):
        return int(obj)
    string = str(obj)
    string = string.lower()
    string = string.replace('ö', 'oe')
    error_message = 'No known/valid borough found in \'%s\'.' % str(obj)
    try:
        return BOROUGH_ID_DICT[string]
    except KeyError:
        # More lines of code but also
        # more readable than a next() statement:
        for borough in BOROUGH_ID_DICT:
            if borough in string:
                return BOROUGH_ID_DICT[borough]
        raise ValueError(error_message)

def get_borough_name(obj):
    if is_borough_id(obj):
        return BOROUGH_NAMES[int(obj)-1]
    else:
        return BOROUGH_NAMES[get_borough_id(obj)-1]

def get_borough_slug(obj):
    if is_borough_id(obj):
        return BOROUGH_SLUGS[int(obj)-1]
    else:
        return BOROUGH_SLUGS[get_borough_id(obj)-1]

HTML_TEMPLATE = (
    '<!DOCTYPE html>'
    ''
    ''
    '<meta charset="UTF-8">'
    '<meta name="viewport" '
        'content="width=device-width, initial-scale=1.0">'
    '<title>'
        'Gremienkalender der Berliner '
        'Bezirksverordnetenversammlungen'
    '</title>'
    ''
    ''
    ''
    ''
    '
'
        'Gremienkalender der Berliner '
        'Bezirksverordnetenversammlungen'
    '
'
    '
'
        'Kalender der Sitzungstermine der '
        'Berliner Bezirksverordnetenversammlungen, '
        'ihrer Ausschüsse und sonstiger Gremien '
        'als iCalender-Dateien (.ics) '
        'zum Abspeichern oder Abonnieren.'
    '
'
    '
'
        'Die Kalender werden zweimal täglich '
        '– gegen 8 Uhr und gegen 16 Uhr – '
        'mit den Sitzungsterminen im offiziellen Dokumentationssystem '
        'der Bezirksverordnetenversammlungen '
        'abgeglichen und aktualisiert.'
    '
'
    '
'
        'Ich freue mich über Anregungen per '
        'Email helge at elchenberg dot me oder '
        'Twitter '
        'twitter.com/elchenberg.'
    '
'
    ''
    '%s'
    ''
    ''
)
SECT_TEMPLATE = (
    '
'
    '
%s
'
    '
%s
'
    '
'
)
ITEM_TEMPLATE = (
    '
'
    '%s'
    '
'
)

def main():
    with open('input.txt', 'r') as textfile:
        borough_urls = [line.strip() for line in textfile.readlines()]

    boroughs = []
    for borough_url in borough_urls:
        response_text = get_response_text(borough_url)
        html_parser = lxml.html.fromstring(response_text)
        # html_parser.make_links_absolute(url)

        committee_ids = set()
        committee_list = html_parser.cssselect('#GRA')[0]
        for element in committee_list:
            text_inactive = 'inaktiv' in element.text_content()
            class_inactive = element.get('class') == 'calWeek'
            if text_inactive or class_inactive:
                continue
            committee_id = int(element.get('value'))
            committee_ids.add(committee_id)

        if not committee_ids:
            continue

        boroughs.append({
            'slug': get_borough_slug(borough_url),
            'name': get_borough_name(borough_url),
            'id': get_borough_id(borough_url),
            'url': borough_url,
            'committees': sorted(committee_ids)
        })

    html_data = {}
    date_query = get_date_query()
    for borough in boroughs:
        b_name = borough['name']
        b_slug = borough['slug']
        b_url = borough['url']

        html_data[b_name] = []

        for c_id in borough['committees']:
            c_url = '%s?GRA=%s' % (b_url, c_id)

            url = '%s&%s' % (c_url, date_query)
            response_text = get_response_text(url)
            html_parser = lxml.html.fromstring(response_text)
            html_parser.make_links_absolute(c_url)

            calendar_rows = html_parser.cssselect('.zl12')
            calendar_rows += html_parser.cssselect('.zl11')
            if not calendar_rows:
                continue

            c_name = html_parser.cssselect('.tl1')[0][0].text_content()
            c_name = c_name.split('Sitzungen des Gremiums ')[1]
            c_name = c_name.split(' im Zeitraum')[0]

            calendar = Calendar()
            calendar.borough = b_name
            calendar.committee = c_name
            calendar.url = c_url
            for row in calendar_rows:
                event_date = row[0].text_content().strip()
                event_time = row[1].text_content().strip()
                if not (event_date and event_time):
                    continue
                datetime = '%s %s' % (event_date[4:], event_time[:5])
                datetime = time.strptime(datetime, '%d.%m.%Y %H:%M')

                event = Event()
                event.summary = '%s: %s' % (b_name, c_name)
                event.description = row[3].text_content().strip()
                if len(row[3]):
                    event.url = row[3][0].get('href')

                event.dtstart = time.strftime('%Y%m%dT%H%M%S', datetime)
                event.duration = 'PT2H'

                now_utc = time.localtime()
                event.dtstamp = time.strftime('%Y%m%dT%H%M%SZ', now_utc)

                uid_domain = '%03d.%s.berlin.de' % (c_id, b_slug)
                uid_local = event.dtstart
                event.uid = '%s@%s' % (uid_local, uid_domain)

                calendar.add_event(event)

            if calendar.ics():
                filename_template = '%s-%03d.ics'
                filename = filename_template % (b_slug, c_id)
                with open(filename, 'w') as icsfile:
                    icsfile.write(calendar.ics())
                html_data[b_name].append([filename, c_name])

    html_sections = ''
    for borough in sorted(html_data):
        items = html_data[borough]
        items = ''.join([ITEM_TEMPLATE % (a, t) for a, t in items])
        section = SECT_TEMPLATE % (borough, items)
        html_sections += section
    html_string = HTML_TEMPLATE % html_sections
    with open('index.html', 'w') as htmlfile:
        htmlfile.write(html_string)

if __name__ == '__main__':
    main()
<commit_msg>Minor HTML update<commit_after># !/usr/bin/env python3
# -*- coding: utf-8 -*-

import http.client
import time
import zlib

import lxml.html

BOROUGH_NAMES = ['Mitte', 'Friedrichshain-Kreuzberg', 'Pankow',
                 'Charlottenburg-Wilmersdorf', 'Spandau',
                 'Steglitz-Zehlendorf', 'Tempelhof-Schöneberg',
                 'Neukölln', 'Treptow-Köpenick', 'Marzahn-Hellersdorf',
                 'Lichtenberg', 'Reinickendorf']
BOROUGH_SLUGS = [b.lower().replace('ö', 'oe') for b in BOROUGH_NAMES]
BOROUGH_ID_DICT = dict(zip(BOROUGH_SLUGS, range(1,13)))

class Calendar():
    def __init__(self):
        self.events = []

    def add_event(self, event):
        self.events.append(event)

    def ics(self):
        if not self.events:
            return None
        ics = []
        ics.append('BEGIN:VCALENDAR')
        ics.append('VERSION:2.0')
        ics.append('PRODID:https://elchenberg.me')
        ics.append('X-WR-CALNAME:BVV %s: %s' % (self.borough,
                                                self.committee))
        ics.append('BEGIN:VTIMEZONE')
        ics.append('TZID:Europe/Berlin')
        ics.append('BEGIN:DAYLIGHT')
        ics.append('TZOFFSETFROM:+0100')
        ics.append('TZOFFSETTO:+0200')
        ics.append('TZNAME:CEST')
        ics.append('DTSTART:19700329T020000')
        ics.append('RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=3')
        ics.append('END:DAYLIGHT')
        ics.append('BEGIN:STANDARD')
        ics.append('TZOFFSETFROM:+0200')
        ics.append('TZOFFSETTO:+0100')
        ics.append('TZNAME:CET')
        ics.append('DTSTART:19701025T030000')
        ics.append('RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10')
        ics.append('END:STANDARD')
        ics.append('END:VTIMEZONE')
        for event in self.events:
            ics.append(event.ics())
        ics.append('END:VCALENDAR')
        return '\r\n'.join(ics)

class Event():
    def __init__(self):
        self.url = None

    def ics(self):
        ics = []
        ics.append('BEGIN:VEVENT')
        ics.append('UID:%s' % self.uid)
        ics.append('DTSTAMP:%s' % self.dtstamp)
        ics.append('DTSTART;TZID=Europe/Berlin:%s' % self.dtstart)
        ics.append('SUMMARY:%s' % self.summary)
        if self.url:
            ics.append('DESCRIPTION:%s\\n%s' % (self.description, self.url))
            ics.append('URL:%s' % self.url)
        else:
            ics.append('DESCRIPTION:%s' % self.description)
        ics.append('END:VEVENT')
        return '\r\n'.join(ics)

REQUEST_WAIT = 3
SESSION = http.client.HTTPSConnection('www.berlin.de', timeout=6)
request_time = time.time()

def get_response_text(url):
    global request_time

    elapsed_time = time.time() - request_time
    if elapsed_time < REQUEST_WAIT:
        time.sleep(REQUEST_WAIT - elapsed_time)

    SESSION.request('GET', url, headers={'Accept-Encoding': 'gzip'})
    print('GET', url)
    response = SESSION.getresponse()
    request_time = time.time()

    # assert response.status == 200
    # assert response.getheader('Content-Encoding') == 'gzip'

    gzip_data = response.read()

    # Tested decompression using different window size and buffer size values.
    # The only working window size values are 31 and 47 so I am going for 47
    # because it is in the range where the logarithm 'automatically accepts
    # either the zlib or gzip format'.
    # As for buffer size it seems to be best to go with the default value.
    # https://docs.python.org/3/library/zlib.html#zlib.decompress
    raw_data = zlib.decompress(gzip_data, 47)

    try:
        response_text = raw_data.decode('latin-1', 'strict')
    except UnicodeDecodeError:
        response_text = raw_data.decode('windows-1252', 'strict')
    return response_text

def get_date_query():
    today = time.localtime()
    year, month = today[0:2]
    template = 'YYV=%s&MMV=%s&YYB=%s&MMB=%s'
    date_query = template % (year, month, year, month + 1)
    if month > 12:
        date_query = template % (year, month, year + 1, 1)
    return date_query

def is_borough_id(obj):
    try:
        obj = int(obj)
        if not 1 <= obj <= 12:
            raise ValueError()
        return True
    except ValueError:
        return False

def get_borough_id(obj):
    if is_borough_id(obj):
        return int(obj)
    string = str(obj)
    string = string.lower()
    string = string.replace('ö', 'oe')
    error_message = 'No known/valid borough found in \'%s\'.' % str(obj)
    try:
        return BOROUGH_ID_DICT[string]
    except KeyError:
        # More lines of code but also
        # more readable than a next() statement:
        for borough in BOROUGH_ID_DICT:
            if borough in string:
                return BOROUGH_ID_DICT[borough]
        raise ValueError(error_message)

def get_borough_name(obj):
    if is_borough_id(obj):
        return BOROUGH_NAMES[int(obj)-1]
    else:
        return BOROUGH_NAMES[get_borough_id(obj)-1]

def get_borough_slug(obj):
    if is_borough_id(obj):
        return BOROUGH_SLUGS[int(obj)-1]
    else:
        return BOROUGH_SLUGS[get_borough_id(obj)-1]

HTML_TEMPLATE = (
    '<!DOCTYPE html>'
    ''
    ''
    '<meta charset="UTF-8">'
    '<meta name="viewport" '
        'content="width=device-width, initial-scale=1.0">'
    '<title>'
        'Gremienkalender der Berliner '
        'Bezirksverordnetenversammlungen'
    '</title>'
    ''
    ''
    ''
    ''
    '
'
        'Gremienkalender der Berliner '
        'Bezirksverordnetenversammlungen'
    '
'
    '
'
        'Sitzungskalender der Gremien der'
        'Berliner Bezirksverordnetenversammlungen '
        'als iCalender-Dateien (.ics) '
        'zum Abspeichern oder Abonnieren.'
    '
'
    '
'
        'Die Kalender werden zweimal täglich '
        '– gegen 8 Uhr und gegen 16 Uhr – '
        'mit den Sitzungsterminen im offiziellen Dokumentationssystem '
        'der Bezirksverordnetenversammlungen '
        'abgeglichen und aktualisiert.'
    '
'
    '
'
        'Ich freue mich über Anregungen per '
        'Email helge at elchenberg dot me oder '
        'Twitter '
        'twitter.com/elchenberg.'
    '
'
    ''
    '%s'
    ''
    ''
)
SECT_TEMPLATE = (
    '
'
    '
%s
'
    '
%s
'
    '
'
)
ITEM_TEMPLATE = (
    '
'
    '%s'
    '
'
)

def main():
    with open('input.txt', 'r') as textfile:
        borough_urls = [line.strip() for line in textfile.readlines()]

    boroughs = []
    for borough_url in borough_urls:
        response_text = get_response_text(borough_url)
        html_parser = lxml.html.fromstring(response_text)
        # html_parser.make_links_absolute(url)

        committee_ids = set()
        committee_list = html_parser.cssselect('#GRA')[0]
        for element in committee_list:
            text_inactive = 'inaktiv' in element.text_content()
            class_inactive = element.get('class') == 'calWeek'
            if text_inactive or class_inactive:
                continue
            committee_id = int(element.get('value'))
            committee_ids.add(committee_id)

        if not committee_ids:
            continue

        boroughs.append({
            'slug': get_borough_slug(borough_url),
            'name': get_borough_name(borough_url),
            'id': get_borough_id(borough_url),
            'url': borough_url,
            'committees': sorted(committee_ids)
        })

    html_data = {}
    date_query = get_date_query()
    for borough in boroughs:
        b_name = borough['name']
        b_slug = borough['slug']
        b_url = borough['url']

        html_data[b_name] = []

        for c_id in borough['committees']:
            c_url = '%s?GRA=%s' % (b_url, c_id)

            url = '%s&%s' % (c_url, date_query)
            response_text = get_response_text(url)
            html_parser = lxml.html.fromstring(response_text)
            html_parser.make_links_absolute(c_url)

            calendar_rows = html_parser.cssselect('.zl12')
            calendar_rows += html_parser.cssselect('.zl11')
            if not calendar_rows:
                continue

            c_name = html_parser.cssselect('.tl1')[0][0].text_content()
            c_name = c_name.split('Sitzungen des Gremiums ')[1]
            c_name = c_name.split(' im Zeitraum')[0]

            calendar = Calendar()
            calendar.borough = b_name
            calendar.committee = c_name
            calendar.url = c_url
            for row in calendar_rows:
                event_date = row[0].text_content().strip()
                event_time = row[1].text_content().strip()
                if not (event_date and event_time):
                    continue
                datetime = '%s %s' % (event_date[4:], event_time[:5])
                datetime = time.strptime(datetime, '%d.%m.%Y %H:%M')

                event = Event()
                event.summary = '%s: %s' % (b_name, c_name)
                event.description = row[3].text_content().strip()
                if len(row[3]):
                    event.url = row[3][0].get('href')

                event.dtstart = time.strftime('%Y%m%dT%H%M%S', datetime)
                event.duration = 'PT2H'

                now_utc = time.localtime()
                event.dtstamp = time.strftime('%Y%m%dT%H%M%SZ', now_utc)

                uid_domain = '%03d.%s.berlin.de' % (c_id, b_slug)
                uid_local = event.dtstart
                event.uid = '%s@%s' % (uid_local, uid_domain)

                calendar.add_event(event)

            if calendar.ics():
                filename_template = '%s-%03d.ics'
                filename = filename_template % (b_slug, c_id)
                with open(filename, 'w') as icsfile:
                    icsfile.write(calendar.ics())
                html_data[b_name].append([filename, c_name])

    html_sections = ''
    for borough in sorted(html_data):
        items = html_data[borough]
        items = ''.join([ITEM_TEMPLATE % (a, t) for a, t in items])
        section = SECT_TEMPLATE % (borough, items)
        html_sections += section
    html_string = HTML_TEMPLATE % html_sections
    with open('index.html', 'w') as htmlfile:
        htmlfile.write(html_string)

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


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

from optparse import OptionParser
import socket
import sys
import httplib
import json

PASS = 0
FAIL = 1

adservers = {}
adservers["east"] = ["prd-useast-service-adserver-c-01.prd.yb0t.cc",
                     "prd-useast-service-adserver-d-01.prd.yb0t.cc",
                     "prd-useast-service-adserver-e-01.prd.yb0t.cc"]
adservers["west"] = ["prd-uswest-service-adserver-a-01.prd.yb0t.cc",
                     "prd-uswest-service-adserver-b-01.prd.yb0t.cc",
                     "prd-uswest-service-adserver-c-01.prd.yb0t.cc"]

def get_bongo_host(server, app):
    try:
        con = httplib.HTTPConnection(server, timeout=45)
        con.request("GET","/v2/apps/" + app)
        data = con.getresponse()
        if data.status >= 300:
            print "get_bongo_host: Recieved non-2xx response= %s" % (data.status)
            sys.exit(FAIL)
        json_data = json.loads(data.read())
        host = "%s:%s" % (json_data['app']['tasks'][0]['host'],json_data['app']['tasks'][0]['ports'][0])
        con.close()
        return host
    except Exception, e:
        print "get_bongo_host: %s :exception caught" % (e)
        sys.exit(FAIL)

def get_status(host, region):
    try:
        output = "\n"
        con = httplib.HTTPConnection(host,timeout=45)
        for i in range(len(adservers[region])):
            con.request("GET","/v1/adserver/health/" + adservers[region][i])
            data = con.getresponse()
            if data.status >= 300:
                output = output + "%s status: Recieved non-2xx response= %s \n" % (adservers[region][i], data.status)
            else:
                json_data = json.loads(data.read())
                if json_data['status'] == 1:
                    output = output + "%s status: %s \n" % (adservers[region][i], json_data['msg'])
        con.close()
        if output == "\n":
            print "mirror-maker on addservers are fine"
            sys.exit(PASS)
        else:
            print output
            sys.exit(FAIL)
    except Exception, e:
        print "get_status: %s :exception caught" % (e)
        sys.exit(FAIL)

if __name__=="__main__":
    parser = OptionParser()
    parser.add_option("-s", dest="server", action="store", default="localhost:8080", help="Marathon Cluster address with port no")
    parser.add_option("-a", dest="app", action="store", default="bongo.useast.prod", help="App Id to retrieve the slave address")
    parser.add_option("-r", dest="region", action="store", default="east", help="Region for which adservers health has to be checked")
    (options, args) = parser.parse_args()
    host = get_bongo_host(options.server, options.app)
    get_status(host, options.region)
<commit_msg>update the messages in adserver and choose-goose plugins<commit_after>#!/usr/bin/env python

from optparse import OptionParser
import socket
import sys
import httplib
import json

PASS = 0
FAIL = 1

adservers = {}
adservers["east"] = ["prd-useast-service-adserver-c-01.prd.yb0t.cc",
                     "prd-useast-service-adserver-d-01.prd.yb0t.cc",
                     "prd-useast-service-adserver-e-01.prd.yb0t.cc"]
adservers["west"] = ["prd-uswest-service-adserver-a-01.prd.yb0t.cc",
                     "prd-uswest-service-adserver-b-01.prd.yb0t.cc",
                     "prd-uswest-service-adserver-c-01.prd.yb0t.cc"]

def get_bongo_host(server, app):
    try:
        con = httplib.HTTPConnection(server, timeout=45)
        con.request("GET","/v2/apps/" + app)
        data = con.getresponse()
        if data.status >= 300:
            print "get_bongo_host: Recieved non-2xx response= %s" % (data.status)
            sys.exit(FAIL)
        json_data = json.loads(data.read())
        host = "%s:%s" % (json_data['app']['tasks'][0]['host'],json_data['app']['tasks'][0]['ports'][0])
        con.close()
        return host
    except Exception, e:
        print "get_bongo_host: %s :exception caught" % (e)
        sys.exit(FAIL)

def get_status(host, region):
    try:
        output = "\n"
        con = httplib.HTTPConnection(host,timeout=45)
        for i in range(len(adservers[region])):
            con.request("GET","/v1/adserver/health/" + adservers[region][i])
            data = con.getresponse()
            if data.status >= 300:
                output = output + "%s status: Recieved non-2xx response= %s \n" % (adservers[region][i], data.status)
            else:
                json_data = json.loads(data.read())
                if json_data['status'] == 1:
                    output = output + "%s status: %s \n" % (adservers[region][i], json_data['msg'])
        con.close()
        if output == "\n":
            print "mirror-maker on adservers are fine"
            sys.exit(PASS)
        else:
            print output
            sys.exit(FAIL)
    except Exception, e:
        print "get_status: %s :exception caught" % (e)
        sys.exit(FAIL)

if __name__=="__main__":
    parser = OptionParser()
    parser.add_option("-s", dest="server", action="store", default="localhost:8080", help="Marathon Cluster address with port no")
    parser.add_option("-a", dest="app", action="store", default="bongo.useast.prod", help="App Id to retrieve the slave address")
    parser.add_option("-r", dest="region", action="store", default="east", help="Region for which adservers health has to be checked")
    (options, args) = parser.parse_args()
    host = get_bongo_host(options.server, options.app)
    get_status(host, options.region)
<|endoftext|>


<commit_before>#!/usr/bin/env python
"""Generate dbt files for telemetry.

Data directory for telemetry records:
    https://github.com/wandb/analytics/tree/master/dbt/data

Usage:
    ./client/tools/telemetry-tool.py --output-dir analytics/dbt/data/
"""

import argparse
import csv
import os
from typing import Any, List

from wandb.proto import wandb_telemetry_pb2 as tpb

DEFAULT_DIR: str = "analytics/dbt/data"
parser = argparse.ArgumentParser()
parser.add_argument(
    "--output-dir", default=DEFAULT_DIR if os.path.exists(DEFAULT_DIR) else ""
)
parser.add_argument(
    "--output-telemetry-record-types", default="map_run_cli_telemetry_record_types.csv"
)
parser.add_argument("--output-imports", default="map_run_cli_imports.csv")
parser.add_argument("--output-features", default="map_run_cli_features.csv")
parser.add_argument("--output-environments", default="map_run_cli_environments.csv")
parser.add_argument("--output-labels", default="map_run_cli_labels.csv")
args = parser.parse_args()

def write_csv(record: str, fields: List[Any]):
    record_arg = "output_{}s".format(record)
    fname = os.path.join(args.output_dir, getattr(args, record_arg))
    print("Writing:", fname)
    with open(fname, "w") as fp:
        writer = csv.DictWriter(fp, fieldnames=[record, "key"], lineterminator="\n")
        writer.writeheader()
        for f in fields:
            writer.writerow({record: f.name, "key": f.number})

def main():
    telemetry_records = list(tpb.TelemetryRecord.DESCRIPTOR.fields)
    write_csv(record="telemetry_record_type", fields=telemetry_records)

    import_records = list(tpb.Imports.DESCRIPTOR.fields)
    write_csv(record="import", fields=import_records)

    feature_records = list(tpb.Feature.DESCRIPTOR.fields)
    write_csv(record="feature", fields=feature_records)

    env_records = list(tpb.Env.DESCRIPTOR.fields)
    write_csv(record="environment", fields=env_records)

    label_records = list(tpb.Labels.DESCRIPTOR.fields)
    write_csv(record="label", fields=label_records)

if __name__ == "__main__":
    main()
<commit_msg>Skip private fields when generating analytics csvs (#2874)<commit_after>#!/usr/bin/env python
"""Generate dbt files for telemetry.

Data directory for telemetry records:
    https://github.com/wandb/analytics/tree/master/dbt/data

Usage:
    ./client/tools/telemetry-tool.py --output-dir analytics/dbt/data/
"""

import argparse
import csv
import os
from typing import Any, List

from wandb.proto import wandb_telemetry_pb2 as tpb

DEFAULT_DIR: str = "analytics/dbt/data"
parser = argparse.ArgumentParser()
parser.add_argument(
    "--output-dir", default=DEFAULT_DIR if os.path.exists(DEFAULT_DIR) else ""
)
parser.add_argument(
    "--output-telemetry-record-types", default="map_run_cli_telemetry_record_types.csv"
)
parser.add_argument("--output-imports", default="map_run_cli_imports.csv")
parser.add_argument("--output-features", default="map_run_cli_features.csv")
parser.add_argument("--output-environments", default="map_run_cli_environments.csv")
parser.add_argument("--output-labels", default="map_run_cli_labels.csv")
args = parser.parse_args()

def write_csv(record: str, fields: List[Any]):
    record_arg = "output_{}s".format(record)
    fname = os.path.join(args.output_dir, getattr(args, record_arg))
    print("Writing:", fname)
    with open(fname, "w") as fp:
        writer = csv.DictWriter(fp, fieldnames=[record, "key"], lineterminator="\n")
        writer.writeheader()
        for f in fields:
            # lets skip private fields
            if f.name.startswith("_"):
                continue
            writer.writerow({record: f.name, "key": f.number})

def main():
    telemetry_records = list(tpb.TelemetryRecord.DESCRIPTOR.fields)
    write_csv(record="telemetry_record_type", fields=telemetry_records)

    import_records = list(tpb.Imports.DESCRIPTOR.fields)
    write_csv(record="import", fields=import_records)

    feature_records = list(tpb.Feature.DESCRIPTOR.fields)
    write_csv(record="feature", fields=feature_records)

    env_records = list(tpb.Env.DESCRIPTOR.fields)
    write_csv(record="environment", fields=env_records)

    label_records = list(tpb.Labels.DESCRIPTOR.fields)
    write_csv(record="label", fields=label_records)

if __name__ == "__main__":
    main()
<|endoftext|>