<commit_before>"""Beam Optics functions."""

import math as _math
import numpy as _np
from mathphys import constants as _c
from mathphys import units as _u

def calc_U0(beam_energy, I2):
    """Calculate U0 [keV] from beam energy [GeV] and I2 [1/m]."""
    U0 = _c.rad_cgamma/(2*_math.pi)*(beam_energy)**4*I2*1e+6
    return U0

def calc_overvoltage(Vrf, U0):
    """Calculate cavity overvoltage factor.

    U0:  energy loss per turn [keV]
    Vrf: rf total voltage  [MV]
    """
    q = Vrf*1e3/U0
    return q

def calc_rf_acceptance(U0, mcf, h, q, energy):
    """Calculate RF energy acceptance.

    U0:     energy loss per turn [keV]
    mcf:    momentum compaction factor
    h:      harmonic_number
    q:      overvoltage
    energy: beam energy [GeV]
    """
    eRF = _math.sqrt(
        2*U0/(_math.pi*mcf*h*(energy*1e6)) *
        (_math.sqrt(q**2-1)-_math.acos(1/q)))
    return eRF

def calc_natural_energy_spread(energy, I2, I3, I4):
    """Calculate energy dispersion.

    energy: beam energy [GeV]
    I2:     second radiation integral [1/m]
    I3:     third radiation integral [1/m²]
    I4:     fouth radiation integral [1/m]
    """
    brho, velocity, beta, gamma = beam_rigidity(energy=energy)
    sigmae = _math.sqrt(_c.Cq * gamma**2 * I3/(2*I2+I4))
    return sigmae

def calc_natural_bunch_length(
        energy, circumference, sigmae, U0, mcf, h, Vrf, hcavity=False):
    """Calculate natural bunch length [m].

    energy:        beam energy [GeV]
    circumference: ring circumference [m]
    sigmae:        natural energy spread
    U0:            energy loss per turn [keV]
    mcf:           momentum compaction factor
    h:             harmonic number
    Vrf:           total rf voltage [MV]
    hcavity:       flag indicating that a 3rd order harmonic cavity is present
    """
    if hcavity:
        Qs = _math.sqrt(
            mcf*h*_math.sqrt((Vrf/1e6)**2-(U0/1e3)**2) /
            (2*_math.pi*(energy/1e9)))
        sigmal = 0.432343807*(mcf*h*_math.pi*sigmae/Qs)**0.5 * \
            circumference/(2*_math.pi*h)
    else:
        Qs = 0.0
        sigmal = sigmae * circumference * \
            _math.sqrt(mcf*(energy*1e9) /
                       (2*_math.pi*h*((Vrf*1e6)**2-(U0*1e3)**2)**0.5))
    return sigmal, Qs

def beam_rigidity(**kwargs):
    """Beam rigidity."""
    electron_rest_energy_eV = _c.electron_rest_energy * _u.joule_2_eV
    electron_rest_energy_GeV = electron_rest_energy_eV * _u.eV_2_GeV

    # checks arguments and make necessary conversions
    if len(kwargs) != 1:
        raise Exception('beam rigidity accepts only one argument')
    for k in kwargs:
        if isinstance(kwargs[k], (list, tuple)):
            kwargs[k] = _np.array(kwargs[k])

    if 'brho' in kwargs:
        k = kwargs['brho'] / \
            (electron_rest_energy_eV/_c.light_speed)
        kwargs['gamma'] = _np.sqrt(1.0+k**2)
    if 'velocity' in kwargs:
        kwargs['beta'] = kwargs['velocity'] / _c.light_speed
    if 'beta' in kwargs:
        kwargs['gamma'] = 1.0 / \
            _np.sqrt((1.0 + kwargs['beta'])*(1.0 - kwargs['beta']))
    if 'gamma' in kwargs:
        kwargs['energy'] = kwargs['gamma'] * electron_rest_energy_GeV

    energy = kwargs['energy']
    gamma = kwargs['gamma'] if 'gamma' in kwargs else \
        energy / electron_rest_energy_GeV

    if isinstance(energy, _np.ndarray):
        if _np.any(energy < electron_rest_energy_GeV):
            raise ValueError('Electron energy less than rest energy!')
        beta = kwargs['beta'] if 'beta' in kwargs else \
            _np.sqrt(((gamma-1.0)/gamma)*((gamma+1.0)/gamma))
    else:
        if energy < electron_rest_energy_GeV:
            # raise ValueError('Electron energy less than rest energy!')
            beta = 0.0
        else:
            beta = _math.sqrt(((gamma-1.0)/gamma)*((gamma+1.0)/gamma))
    velocity = kwargs['velocity'] if 'velocity' in kwargs else \
        _c.light_speed * beta
    brho = kwargs['brho'] if 'brho' in kwargs else \
        beta * (energy * _u.GeV_2_eV) / _c.light_speed

    return brho, velocity, beta, gamma, energy

def calc_number_of_electrons(energy, current, circumference):
    """Calculate numbe of electrons.

    energy:        beam energy [GeV]
    current:       beam current [mA]
    circumference: ring circumference [m]
    """
    brho, velocity, beta, gamma = beam_rigidity(energy)
    mA = 1e-3 / _c.elementary_charge * circumference / velocity
    Np = current * mA
    return Np
<commit_msg>Add comment<commit_after>"""Beam Optics functions."""

import math as _math
import numpy as _np
from mathphys import constants as _c
from mathphys import units as _u

def calc_U0(beam_energy, I2):
    """Calculate U0 [keV] from beam energy [GeV] and I2 [1/m]."""
    U0 = _c.rad_cgamma/(2*_math.pi)*(beam_energy)**4*I2*1e+6
    return U0

def calc_overvoltage(Vrf, U0):
    """Calculate cavity overvoltage factor.

    U0:  energy loss per turn [keV]
    Vrf: rf total voltage  [MV]
    """
    q = Vrf*1e3/U0
    return q

def calc_rf_acceptance(U0, mcf, h, q, energy):
    """Calculate RF energy acceptance.

    U0:     energy loss per turn [keV]
    mcf:    momentum compaction factor
    h:      harmonic_number
    q:      overvoltage
    energy: beam energy [GeV]
    """
    eRF = _math.sqrt(
        2*U0/(_math.pi*mcf*h*(energy*1e6)) *
        (_math.sqrt(q**2-1)-_math.acos(1/q)))
    return eRF

def calc_natural_energy_spread(energy, I2, I3, I4):
    """Calculate energy dispersion.

    energy: beam energy [GeV]
    I2:     second radiation integral [1/m]
    I3:     third radiation integral [1/m²]
    I4:     fouth radiation integral [1/m]
    """
    brho, velocity, beta, gamma = beam_rigidity(energy=energy)
    sigmae = _math.sqrt(_c.Cq * gamma**2 * I3/(2*I2+I4))
    return sigmae

def calc_natural_bunch_length(
        energy, circumference, sigmae, U0, mcf, h, Vrf, hcavity=False):
    """Calculate natural bunch length [m].

    energy:        beam energy [GeV]
    circumference: ring circumference [m]
    sigmae:        natural energy spread
    U0:            energy loss per turn [keV]
    mcf:           momentum compaction factor
    h:             harmonic number
    Vrf:           total rf voltage [MV]
    hcavity:       flag indicating that a 3rd order harmonic cavity is present
    """
    if hcavity:
        Qs = _math.sqrt(
            mcf*h*_math.sqrt((Vrf/1e6)**2-(U0/1e3)**2) /
            (2*_math.pi*(energy/1e9)))
        sigmal = 0.432343807*(mcf*h*_math.pi*sigmae/Qs)**0.5 * \
            circumference/(2*_math.pi*h)
    else:
        Qs = 0.0
        sigmal = sigmae * circumference * \
            _math.sqrt(mcf*(energy*1e9) /
                       (2*_math.pi*h*((Vrf*1e6)**2-(U0*1e3)**2)**0.5))
    return sigmal, Qs

# NOTE: This function is used in siriuspy!
def beam_rigidity(**kwargs):
    """Beam rigidity."""
    electron_rest_energy_eV = _c.electron_rest_energy * _u.joule_2_eV
    electron_rest_energy_GeV = electron_rest_energy_eV * _u.eV_2_GeV

    # checks arguments and make necessary conversions
    if len(kwargs) != 1:
        raise Exception('beam rigidity accepts only one argument')
    for k in kwargs:
        if isinstance(kwargs[k], (list, tuple)):
            kwargs[k] = _np.array(kwargs[k])

    if 'brho' in kwargs:
        k = kwargs['brho'] / \
            (electron_rest_energy_eV/_c.light_speed)
        kwargs['gamma'] = _np.sqrt(1.0+k**2)
    if 'velocity' in kwargs:
        kwargs['beta'] = kwargs['velocity'] / _c.light_speed
    if 'beta' in kwargs:
        kwargs['gamma'] = 1.0 / \
            _np.sqrt((1.0 + kwargs['beta'])*(1.0 - kwargs['beta']))
    if 'gamma' in kwargs:
        kwargs['energy'] = kwargs['gamma'] * electron_rest_energy_GeV

    energy = kwargs['energy']
    gamma = kwargs['gamma'] if 'gamma' in kwargs else \
        energy / electron_rest_energy_GeV

    if isinstance(energy, _np.ndarray):
        if _np.any(energy < electron_rest_energy_GeV):
            raise ValueError('Electron energy less than rest energy!')
        beta = kwargs['beta'] if 'beta' in kwargs else \
            _np.sqrt(((gamma-1.0)/gamma)*((gamma+1.0)/gamma))
    else:
        if energy < electron_rest_energy_GeV:
            # raise ValueError('Electron energy less than rest energy!')
            beta = 0.0
        else:
            beta = _math.sqrt(((gamma-1.0)/gamma)*((gamma+1.0)/gamma))
    velocity = kwargs['velocity'] if 'velocity' in kwargs else \
        _c.light_speed * beta
    brho = kwargs['brho'] if 'brho' in kwargs else \
        beta * (energy * _u.GeV_2_eV) / _c.light_speed

    return brho, velocity, beta, gamma, energy

def calc_number_of_electrons(energy, current, circumference):
    """Calculate numbe of electrons.

    energy:        beam energy [GeV]
    current:       beam current [mA]
    circumference: ring circumference [m]
    """
    brho, velocity, beta, gamma = beam_rigidity(energy)
    mA = 1e-3 / _c.elementary_charge * circumference / velocity
    Np = current * mA
    return Np
<|endoftext|>


<commit_before>#! /usr/bin/python

from __future__ import print_function

import sys

with open(sys.argv[1], "r") as f:
    lines = f.readlines()

class Player:
    def __init__(self, name):
        self.name = name
        self.opponent = {}
        self.vs_opponent = {}
        self.games_vs = {}
        self.points_for = 0
        self.points_against = 0

    def won_game(self, rslt):
        sc1, sc2, turn = rslt
        return (sc1 > sc2) or (sc1 == sc2 and turn == 2)

    # op -> name of opponent
    # game -> game number against this opponent
    # myscore -> score for this player for this game
    # opscore -> score for opponent for this game
    # turn -> 1 if first player, 2 if second player
    def add_result(self, op, game, myscore, opscore, turn):
        self.points_for += myscore
        self.points_against += opscore
        if op not in self.opponent:
            self.opponent[op] = [(), (), (), (), ()]
            self.vs_opponent[op] = 0
            self.games_vs[op] = 0
        self.opponent[op][game - 1] = (myscore, opscore, turn)
        self.games_vs[op] += 1
        if self.won_game(self.opponent[op][game - 1]):
            self.vs_opponent[op] += 1

    def fmt_result(self, oplist):
        won = 0
        for i in oplist:
            if i in self.opponent:
                for score in self.opponent[i]:
                    if score:
                        if self.won_game(score):
                            print("1  ", end="")
                            won += 1
                        else:
                            print("0  ", end="")
                    else:
                        print("   ", end="")
            else:
                print("               ", end="")
            print("| ", end="")
        print("%2s" % won)

#
# Format of the file we're reading in:
# - lines which start with "p " give the player name
# - lines which start with "g " provide game results
# - all other lines are ignored
#
# Example of p:
# p player1
# p player2
#
# Example of g:
# g 3 player1:23,player2:45
#
# Format is: "game_number player:score,player:score"
#

player = {}
maxlen = 0
for l in lines:
    l = l.rstrip()
    if not l:
        continue
    v = l.split()
    if v[0] == "p":
        player[v[1]] = (Player(v[1]))
        maxlen = max(maxlen, len(v[1]))
    elif v[0] == "g":
        game = int(v[1])
        rslt = v[2].split(",")
        p1 = rslt[0].split(":")
        p2 = rslt[1].split(":")
        p1sc = int(p1[1])
        p2sc = int(p2[1])

        if p1[0] not in player:
            print("Player %s not defined" % p1[0])
            sys.exit(1)
        if p2[0] not in player:
            print("Player %s not defined" % p2[0])
            sys.exit(1)

        player[p1[0]].add_result(p2[0], game, p1sc, p2sc, 1)
        player[p2[0]].add_result(p1[0], game, p2sc, p1sc, 2)

fmt = "%%%ss" % maxlen
lfmt = "  %%-%ss" % maxlen
pad = 15 - maxlen  # 15 magic number comes from 5 games * 3 spaces per game
plist = sorted(player, key=lambda s: s.lower())

print("Game Results:")
print(fmt % "", end="")
for p in plist:
    print(lfmt % p, end="")
    print(" " * pad, end="")
print("")

print(fmt % "", end="")
print(" ", end="")
for p in plist:
    print(" 1  2  3  4  5  |", end="")
print(" Total Games Won")

for p in plist:
    print(fmt % p, end="")
    print(": ", end="")
    player[p].fmt_result(plist)

print("---")

print("Match Results:")
for p in plist:
    wins = 0
    losses = 0
    for op in player[p].vs_opponent:
        if player[p].games_vs[op] < 5:
            continue
        rslt = player[p].vs_opponent[op]
        if rslt > 2:
            wins += 1
        elif rslt <= 2:
            losses += 1
    if wins > 0 or losses > 0:
        print("%s%s: " % (" " * (pad - len(p)), p), end="")
        match = list()

        def sing_or_pl(score, sing, pl):
            if score == 1:
                return "%s %s" % (score, sing)
            return "%s %s" % (score, pl)

        if wins > 0:
            match.append(sing_or_pl(wins, "win", "wins"))
        if losses > 0:
            match.append(sing_or_pl(losses, "loss", "losses"))
        print(", ".join(match))

print("---")

print("Total Points:")
for p in plist:
    print(lfmt % p, end="")
    print(" %10s points for / %10s points against" % \
            (player[p].points_for, player[p].points_against))
<commit_msg>write dashes for diagonal<commit_after>#! /usr/bin/python

from __future__ import print_function

import sys

with open(sys.argv[1], "r") as f:
    lines = f.readlines()

class Player:
    def __init__(self, name):
        self.name = name
        self.opponent = {}
        self.vs_opponent = {}
        self.games_vs = {}
        self.points_for = 0
        self.points_against = 0

    def won_game(self, rslt):
        sc1, sc2, turn = rslt
        return (sc1 > sc2) or (sc1 == sc2 and turn == 2)

    # op -> name of opponent
    # game -> game number against this opponent
    # myscore -> score for this player for this game
    # opscore -> score for opponent for this game
    # turn -> 1 if first player, 2 if second player
    def add_result(self, op, game, myscore, opscore, turn):
        self.points_for += myscore
        self.points_against += opscore
        if op not in self.opponent:
            self.opponent[op] = [(), (), (), (), ()]
            self.vs_opponent[op] = 0
            self.games_vs[op] = 0
        self.opponent[op][game - 1] = (myscore, opscore, turn)
        self.games_vs[op] += 1
        if self.won_game(self.opponent[op][game - 1]):
            self.vs_opponent[op] += 1

    def fmt_result(self, oplist):
        won = 0
        for i in oplist:
            if i in self.opponent:
                for score in self.opponent[i]:
                    if score:
                        if self.won_game(score):
                            print("1  ", end="")
                            won += 1
                        else:
                            print("0  ", end="")
                    else:
                        print("   ", end="")
            elif i == self.name:
                print("-  -  -  -  -  ", end="")
            else:
                print("               ", end="")
            print("| ", end="")
        print("%2s" % won)

#
# Format of the file we're reading in:
# - lines which start with "p " give the player name
# - lines which start with "g " provide game results
# - all other lines are ignored
#
# Example of p:
# p player1
# p player2
#
# Example of g:
# g 3 player1:23,player2:45
#
# Format is: "game_number player:score,player:score"
#

player = {}
maxlen = 0
for l in lines:
    l = l.rstrip()
    if not l:
        continue
    v = l.split()
    if v[0] == "p":
        player[v[1]] = (Player(v[1]))
        maxlen = max(maxlen, len(v[1]))
    elif v[0] == "g":
        game = int(v[1])
        rslt = v[2].split(",")
        p1 = rslt[0].split(":")
        p2 = rslt[1].split(":")
        p1sc = int(p1[1])
        p2sc = int(p2[1])

        if p1[0] not in player:
            print("Player %s not defined" % p1[0])
            sys.exit(1)
        if p2[0] not in player:
            print("Player %s not defined" % p2[0])
            sys.exit(1)

        player[p1[0]].add_result(p2[0], game, p1sc, p2sc, 1)
        player[p2[0]].add_result(p1[0], game, p2sc, p1sc, 2)

fmt = "%%%ss" % maxlen
lfmt = "  %%-%ss" % maxlen
pad = 15 - maxlen  # 15 magic number comes from 5 games * 3 spaces per game
plist = sorted(player, key=lambda s: s.lower())

print("Game Results:")
print(fmt % "", end="")
for p in plist:
    print(lfmt % p, end="")
    print(" " * pad, end="")
print("")

print(fmt % "", end="")
print(" ", end="")
for p in plist:
    print(" 1  2  3  4  5  |", end="")
print(" Total Games Won")

for p in plist:
    print(fmt % p, end="")
    print(": ", end="")
    player[p].fmt_result(plist)

print("---")

print("Match Results:")
for p in plist:
    wins = 0
    losses = 0
    for op in player[p].vs_opponent:
        if player[p].games_vs[op] < 5:
            continue
        rslt = player[p].vs_opponent[op]
        if rslt > 2:
            wins += 1
        elif rslt <= 2:
            losses += 1
    if wins > 0 or losses > 0:
        print("%s%s: " % (" " * (pad - len(p)), p), end="")
        match = list()

        def sing_or_pl(score, sing, pl):
            if score == 1:
                return "%s %s" % (score, sing)
            return "%s %s" % (score, pl)

        if wins > 0:
            match.append(sing_or_pl(wins, "win", "wins"))
        if losses > 0:
            match.append(sing_or_pl(losses, "loss", "losses"))
        print(", ".join(match))

print("---")

print("Total Points:")
for p in plist:
    print(lfmt % p, end="")
    print(" %10s points for / %10s points against" % \
            (player[p].points_for, player[p].points_against))
<|endoftext|>


<commit_before>import personalBestCache
import userStatsCache
from common.ddog import datadogClient
from common.files import fileBuffer, fileLocks
from common.web import schiavo

try:
	with open("version") as f:
		VERSION = f.read().strip()
except:
	VERSION = "Unknown"
ACHIEVEMENTS_VERSION = 0

DATADOG_PREFIX = "lets"
db = None
redis = None
conf = None
application = None
pool = None
pascoa = {}

busyThreads = 0
debug = False
sentry = False

# Cache and objects
fLocks = fileLocks.fileLocks()
userStatsCache = userStatsCache.userStatsCache()
personalBestCache = personalBestCache.personalBestCache()
fileBuffers = fileBuffer.buffersList()
dog = datadogClient.datadogClient()
schiavo = schiavo.schiavo()
achievementClasses = {}<commit_msg>Bump achievements version<commit_after>import personalBestCache
import userStatsCache
from common.ddog import datadogClient
from common.files import fileBuffer, fileLocks
from common.web import schiavo

try:
	with open("version") as f:
		VERSION = f.read().strip()
except:
	VERSION = "Unknown"
ACHIEVEMENTS_VERSION = 1

DATADOG_PREFIX = "lets"
db = None
redis = None
conf = None
application = None
pool = None
pascoa = {}

busyThreads = 0
debug = False
sentry = False

# Cache and objects
fLocks = fileLocks.fileLocks()
userStatsCache = userStatsCache.userStatsCache()
personalBestCache = personalBestCache.personalBestCache()
fileBuffers = fileBuffer.buffersList()
dog = datadogClient.datadogClient()
schiavo = schiavo.schiavo()
achievementClasses = {}<|endoftext|>


<commit_before><commit_msg>Implement drive gain, and depletion over time<commit_after><|endoftext|>


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

from django.conf import settings
import os

# add analytics templates
settings.TEMPLATE_DIRS += (os.path.realpath(os.path.dirname(__file__)+ "/../../templates"),)

# patch to create a new certificates tab
from openstack_dashboard.dashboards.project.loadbalancers.tabs import LoadBalancerTabs
from avidashboard.dashboards.project.loadbalancers.tabs import CertificatesTab
from avidashboard.dashboards.project.loadbalancers.tabs import AviUITab
LoadBalancerTabs.tabs += (CertificatesTab,)

if getattr(settings, "AVI_ANALYTICS_TAB_ENABLED", False):
    LoadBalancerTabs.tabs += (AviUITab,)

if getattr(settings, "AVI_LBAAS_FULL_UI", False):
    LoadBalancerTabs.tabs = (AviUITab,)

# patch to add relevant URLs
from openstack_dashboard.dashboards.project.loadbalancers.urls import urlpatterns
from avidashboard.dashboards.project.loadbalancers.urls import urlpatterns as avi_urls
urlpatterns.extend(avi_urls)

# patch to add a new row action link in the pools table
from openstack_dashboard.dashboards.project.loadbalancers.tables import PoolsTable
from avidashboard.dashboards.project.loadbalancers.tables import (
    AssociateCertificateLink, DisassociateCertificateLink)
PoolsTable._meta.row_actions += (AssociateCertificateLink, DisassociateCertificateLink)
PoolsTable.base_actions[AssociateCertificateLink.name] = AssociateCertificateLink()
PoolsTable.base_actions[DisassociateCertificateLink.name] = DisassociateCertificateLink()

# patch to modify addvip help message
from openstack_dashboard.dashboards.project.loadbalancers.workflows import AddVipAction
AddVipAction.help_text += ("\n\n\nIMPORTANT: If you are configuring SSL Offload with "
                           "unencrypted HTTP to your pool members, select 'HTTP' "
                           "in the Protocol field\n\n\n")

# patch to ignore SEs in addmember action (courtesy: Eric Peterson, TWC)
from openstack_dashboard.dashboards.project.loadbalancers.workflows \
    import AddMemberAction

oldAddMemberActionInit = AddMemberAction.__init__

def newAddMemberActionInit(self, request, *args, **kwargs):
    from openstack_dashboard import api
    real_svr_list = api.nova.server_list

    try:

        def filtered_nova_list(request):
            instances, more = real_svr_list(request)
            instances = [instance for instance
                         in instances
                         if 'AVICNTRL' not in instance.metadata]
            return instances, more

        api.nova.server_list = filtered_nova_list
        oldAddMemberActionInit(self, request, *args, **kwargs)
    finally:
        api.nova.server_list = real_svr_list

AddMemberAction.__init__ = newAddMemberActionInit

# patch to add cert information in pool table
from openstack_dashboard.dashboards.project.loadbalancers import tables \
    as lbtables
from avidashboard.api import avi
old_get_data = lbtables.UpdatePoolsRow.get_data

def add_pool_vip_info(pool, request):
    pool.cert = None
    if pool.vip_id:
        try:
            vip = avi.get_vip(request, pool.vip_id)
            cert = avi.get_vip_cert(vip)
            if cert:
                pool.cert = cert
            http_port = avi.get_vip_http_port(vip)
            if http_port > 0:
                pool.http_port = http_port
        except Exception as e:
            print "Error in obtaining certificate info: %s" % e
    return pool

def new_get_data(self, request, pool_id):
    pool = old_get_data(self, request, pool_id)
    return add_pool_vip_info(pool, request)

lbtables.UpdatePoolsRow.get_data = new_get_data

old_get_vip_name = lbtables.get_vip_name
from django.utils.safestring import SafeText

def get_vip_name(pool):
    ret_string = old_get_vip_name(pool)
    if hasattr(pool, "cert") and pool.cert:
        ret_string += "\n
\n Certificate: %s\n" % pool.cert
        if hasattr(pool, "http_port") and pool.http_port > 0:
            ret_string += "\n
\n HTTP Redirect: Port %s\n" % pool.http_port
        ret_string = SafeText(ret_string)
    return ret_string

lbtables.PoolsTable.base_columns['vip_name'].transform = get_vip_name

from openstack_dashboard.api import lbaas
old_pool_list = lbaas._pool_list

def new_pool_list(request, expand_subnet=False, expand_vip=False, **kwargs):
    plist = old_pool_list(request, expand_subnet, expand_vip, **kwargs)
    for pool in plist:
        add_pool_vip_info(pool, request)
    return plist

lbaas._pool_list = new_pool_list
<commit_msg>Update __init__.py<commit_after># Copyright 2015 Avi Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from django.conf import settings
import os

# add analytics templates
settings.TEMPLATE_DIRS += (os.path.realpath(os.path.dirname(__file__)+ "/../../templates"),)

# patch to create a new certificates tab
from openstack_dashboard.dashboards.project.loadbalancers.tabs import LoadBalancerTabs
from openstack_dashboard.dashboards.project.loadbalancers.panel import \
    LoadBalancer as LoadBalancerPanel
from avidashboard.dashboards.project.loadbalancers.tabs import CertificatesTab
from avidashboard.dashboards.project.loadbalancers.tabs import AviUITab
LoadBalancerTabs.tabs += (CertificatesTab,)

if getattr(settings, "AVI_ANALYTICS_TAB_ENABLED", False):
    LoadBalancerTabs.tabs += (AviUITab,)

if getattr(settings, "AVI_LBAAS_FULL_UI", False):
    LoadBalancerTabs.tabs = (AviUITab,)
    # if the full ui is present, we want to make sure the panel shows up
    LoadBalancerPanel.allowed = lambda x, y: True

# patch to add relevant URLs
from openstack_dashboard.dashboards.project.loadbalancers.urls import urlpatterns
from avidashboard.dashboards.project.loadbalancers.urls import urlpatterns as avi_urls
urlpatterns.extend(avi_urls)

# patch to add a new row action link in the pools table
from openstack_dashboard.dashboards.project.loadbalancers.tables import PoolsTable
from avidashboard.dashboards.project.loadbalancers.tables import (
    AssociateCertificateLink, DisassociateCertificateLink)
PoolsTable._meta.row_actions += (AssociateCertificateLink, DisassociateCertificateLink)
PoolsTable.base_actions[AssociateCertificateLink.name] = AssociateCertificateLink()
PoolsTable.base_actions[DisassociateCertificateLink.name] = DisassociateCertificateLink()

# patch to modify addvip help message
from openstack_dashboard.dashboards.project.loadbalancers.workflows import AddVipAction
AddVipAction.help_text += ("\n\n\nIMPORTANT: If you are configuring SSL Offload with "
                           "unencrypted HTTP to your pool members, select 'HTTP' "
                           "in the Protocol field\n\n\n")

# patch to ignore SEs in addmember action (courtesy: Eric Peterson, TWC)
from openstack_dashboard.dashboards.project.loadbalancers.workflows \
    import AddMemberAction

oldAddMemberActionInit = AddMemberAction.__init__

def newAddMemberActionInit(self, request, *args, **kwargs):
    from openstack_dashboard import api
    real_svr_list = api.nova.server_list

    try:

        def filtered_nova_list(request):
            instances, more = real_svr_list(request)
            instances = [instance for instance
                         in instances
                         if 'AVICNTRL' not in instance.metadata]
            return instances, more

        api.nova.server_list = filtered_nova_list
        oldAddMemberActionInit(self, request, *args, **kwargs)
    finally:
        api.nova.server_list = real_svr_list

AddMemberAction.__init__ = newAddMemberActionInit

# patch to add cert information in pool table
from openstack_dashboard.dashboards.project.loadbalancers import tables \
    as lbtables
from avidashboard.api import avi
old_get_data = lbtables.UpdatePoolsRow.get_data

def add_pool_vip_info(pool, request):
    pool.cert = None
    if pool.vip_id:
        try:
            vip = avi.get_vip(request, pool.vip_id)
            cert = avi.get_vip_cert(vip)
            if cert:
                pool.cert = cert
            http_port = avi.get_vip_http_port(vip)
            if http_port > 0:
                pool.http_port = http_port
        except Exception as e:
            print "Error in obtaining certificate info: %s" % e
    return pool

def new_get_data(self, request, pool_id):
    pool = old_get_data(self, request, pool_id)
    return add_pool_vip_info(pool, request)

lbtables.UpdatePoolsRow.get_data = new_get_data

old_get_vip_name = lbtables.get_vip_name
from django.utils.safestring import SafeText

def get_vip_name(pool):
    ret_string = old_get_vip_name(pool)
    if hasattr(pool, "cert") and pool.cert:
        ret_string += "\n
\n Certificate: %s\n" % pool.cert
        if hasattr(pool, "http_port") and pool.http_port > 0:
            ret_string += "\n
\n HTTP Redirect: Port %s\n" % pool.http_port
        ret_string = SafeText(ret_string)
    return ret_string

lbtables.PoolsTable.base_columns['vip_name'].transform = get_vip_name

from openstack_dashboard.api import lbaas
old_pool_list = lbaas._pool_list

def new_pool_list(request, expand_subnet=False, expand_vip=False, **kwargs):
    plist = old_pool_list(request, expand_subnet, expand_vip, **kwargs)
    for pool in plist:
        add_pool_vip_info(pool, request)
    return plist

lbaas._pool_list = new_pool_list
<|endoftext|>


<commit_before>import sys
from PyQt4 import QtGui, QtCore
import exifread
import re
import glob
import os
import shutil

class Photochooser(QtGui.QWidget):
    WIDTH = 1200
    HEIGHT = 800

    dir = ''
    copyDir = ''
    deleteDir = ''
    files = []
    currentFileIndex = 0
    currentFile = ''
    label = None

    # buttons
    copyBtn = None
    deleteBtn = None
    softDeleteBtn = None

    def __init__(self):
        super(Photochooser, self).__init__()

        self.label = QtGui.QLabel(self)

        self.initButtons()
        self.initFiles()

        self.showFile(self.getFirstFile())

    def initFiles(self):
        while True:
            currentDir = self.openDir()
            self.files = glob.glob(os.path.join(currentDir, '*.jpg'))

            # if dir contains any images then break, continue choosing dir otherwise
            if 0 < len(self.files):
                self.copyDir = os.path.join(currentDir, 'copy')
                self.deleteDir = os.path.join(currentDir, 'delete')
                print(self.copyDir)
                break

    def initButtons(self):
        # buttons
        self.copyBtn = QtGui.QPushButton('Copy!', self)
        self.copyBtn.clicked.connect(lambda: self.copyPhoto())
        self.copyBtn.resize(self.copyBtn.sizeHint())
        self.copyBtn.move(5, 5)

        # prevents button from getting focused, required for arrow support in windows
        self.copyBtn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.deleteBtn = QtGui.QPushButton('Delete!', self)
        self.deleteBtn.clicked.connect(lambda: self.deletePhoto())
        self.deleteBtn.resize(self.deleteBtn.sizeHint())
        self.deleteBtn.move(5, 30)

        # prevents button from getting focused, required for arrow support in windows
        self.deleteBtn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.softDeleteBtn = QtGui.QPushButton('Delete?', self)
        self.softDeleteBtn.clicked.connect(lambda: self.softDeletePhoto())
        self.softDeleteBtn.resize(self.softDeleteBtn.sizeHint())
        self.softDeleteBtn.move(5, 55)

        # prevents button from getting focused, required for arrow support in windows
        self.softDeleteBtn.setFocusPolicy(QtCore.Qt.NoFocus)

    def resetButtons(self):
        self.copyBtn.setText('Copy!')
        self.deleteBtn.setText('Delete!')
        self.softDeleteBtn.setText('Delete?')

    def showFile(self, filename):
        self.resetButtons()

        self.currentFile = filename

        f = open(filename, 'rb')

        pixmap = QtGui.QPixmap(filename)
        pixmap = pixmap.scaledToWidth(self.WIDTH)

        try:
            tags = exifread.process_file(f)
            rotationTag = tags['Image Orientation']
            # print(rotationTag)

            rotation = re.search('[0-9]+', str(rotationTag)).group(0)
            transform = QtGui.QTransform()
            transform.rotate(float(rotation))
            pixmap = pixmap.transformed(transform)
        except:
            pass

        self.label.setPixmap(pixmap)
        self.resize(min(pixmap.width(), self.WIDTH), min(pixmap.height(), self.HEIGHT))

        # Show window
        self.show()

    def getFirstFile(self):
        return self.files[0]

    def getNextFile(self):
        try:
            nextFile = self.files[self.currentFileIndex + 1]
            self.currentFileIndex += 1

            return nextFile
        except:
            return False

    def getPrevFile(self):
        if 0 > self.currentFileIndex - 1:
            return False

        try:
            prevFile = self.files[self.currentFileIndex - 1]
            self.currentFileIndex -= 1

            return prevFile
        except:
            return False

    def openDir(self):
        return QtGui.QFileDialog.getExistingDirectory()

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Right or e.key() == QtCore.Qt.Key_Period:
            nextFile = self.getNextFile()
            # print(nextFile)
            if False != nextFile:
                self.showFile(nextFile)
        elif e.key() == QtCore.Qt.Key_Left or e.key() == QtCore.Qt.Key_Comma:
            prevFile = self.getPrevFile()
            # print(prevFile)
            if False != prevFile:
                self.showFile(prevFile)
        elif e.key() == QtCore.Qt.Key_C:
            self.copyPhoto()
        elif e.key() == QtCore.Qt.Key_D:
            self.softDeletePhoto()
        elif e.key() == QtCore.Qt.Key_Backspace:
            self.deletePhoto()

        QtGui.QWidget.keyPressEvent(self, e)

    def copyPhoto(self):
        if not os.path.exists(self.copyDir):
            os.makedirs(self.copyDir)

        shutil.copy2(self.currentFile, self.copyDir)

        self.copyBtn.setText('Copied')

    def softDeletePhoto(self):
        if not os.path.exists(self.deleteDir):
            os.makedirs(self.deleteDir)

        shutil.move(self.currentFile, self.deleteDir)
        self.__afterDeletePhoto()

        self.softDeleteBtn.setText('Deleted')

    def deletePhoto(self):
        os.remove(self.currentFile)
        self.__afterDeletePhoto()

        self.deleteBtn.setText('Deleted')

    def __afterDeletePhoto(self):
        del self.files[self.currentFileIndex]
        # decrement current file index, because deleting file from list moves all next files one index down
        # now getting next file would get proper next file
        self.currentFileIndex -= 1

        nextFile = self.getNextFile()
        if False != nextFile:
            self.showFile(nextFile)
        else:
            # its a little tricky, but to get previous file the index must be incremented so getting prev file wold get proper previous file
            self.currentFileIndex += 1

            prevFile = self.getPrevFile()
            if False != prevFile:
                self.showFile(prevFile)
            else:
                t = QtGui.QMessageBox.information(
                    self,
                    'No files in directory',
                    'Chosen directory does not contain any images',
                    QtGui.QMessageBox.Ok
                )
                print(t)
                exit()

# Create an PyQT4 application object.
a = QtGui.QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = Photochooser()

# Set window title
w.setWindowTitle("Photo Chooser")

sys.exit(a.exec_())
<commit_msg>names convention fix scaling images to maximized window RC<commit_after>import sys
from PyQt4 import QtGui, QtCore
import exifread
import re
import glob
import os
import shutil

class Photochooser(QtGui.QWidget):
    app_width = 1200
    app_height = 800

    dir = ''
    copy_dir = ''
    delete_dir = ''
    files = []
    current_file_index = 0
    current_file = ''
    label = None

    # buttons
    copy_btn = None
    delete_btn = None
    soft_delete_btn = None

    def __init__(self, screen_width, screen_height):
        super(Photochooser, self).__init__()

        self.app_width = screen_width
        self.app_height = screen_height
        self.label = QtGui.QLabel(self)

        self.init_buttons()
        self.init_files()

        self.show_file(self.get_first_file())

        self.showMaximized()

    def init_files(self):
        while True:
            currentDir = self.open_dir()
            self.files.extend(glob.glob(os.path.join(currentDir, '*.jpg')))
            self.files.extend(glob.glob(os.path.join(currentDir, '*.png')))

            # if dir contains any images then break, continue choosing dir otherwise
            if 0 < len(self.files):
                self.copy_dir = os.path.join(currentDir, 'copy')
                self.delete_dir = os.path.join(currentDir, 'delete')
                print(self.copy_dir)
                break

    def init_buttons(self):
        # buttons
        self.copy_btn = QtGui.QPushButton('Copy!', self)
        self.copy_btn.clicked.connect(lambda: self.copy_photo())
        self.copy_btn.resize(self.copy_btn.sizeHint())
        self.copy_btn.move(5, 5)

        # prevents button from getting focused, required for arrow support in windows
        self.copy_btn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.delete_btn = QtGui.QPushButton('Delete!', self)
        self.delete_btn.clicked.connect(lambda: self.delete_photo())
        self.delete_btn.resize(self.delete_btn.sizeHint())
        self.delete_btn.move(5, 30)

        # prevents button from getting focused, required for arrow support in windows
        self.delete_btn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.soft_delete_btn = QtGui.QPushButton('Delete?', self)
        self.soft_delete_btn.clicked.connect(lambda: self.soft_delete_photo())
        self.soft_delete_btn.resize(self.soft_delete_btn.sizeHint())
        self.soft_delete_btn.move(5, 55)

        # prevents button from getting focused, required for arrow support in windows
        self.soft_delete_btn.setFocusPolicy(QtCore.Qt.NoFocus)

    def reset_buttons(self):
        self.copy_btn.setText('Copy!')
        self.delete_btn.setText('Delete!')
        self.soft_delete_btn.setText('Delete?')

    def show_file(self, filename):
        self.reset_buttons()

        self.current_file = filename

        f = open(filename, 'rb')

        pixmap = QtGui.QPixmap(filename)

        try:
            tags = exifread.process_file(f)
            rotation_tag = tags['Image Orientation']

            rotation = re.search('[0-9]+', str(rotation_tag)).group(0)
            transform = QtGui.QTransform()
            transform.rotate(float(rotation))
            pixmap = pixmap.transformed(transform)
        except:
            pass

        # resize
        factor = self.get_scale_factor(pixmap.width(), pixmap.height())
        pixmap = pixmap.scaledToHeight(pixmap.height() * factor)

        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setPixmap(pixmap)

        # Show window
        # self.showMaximized()

    def get_scale_factor(self, img_width, img_height):
        factor_w, factor_h = 1.0, 1.0
        if img_width > self.app_width:
            factor_w = self.app_width / img_width
        if img_height > self.app_height:
            factor_h = self.app_height / img_height

        return min(factor_w, factor_h)

    def get_first_file(self):
        return self.files[0]

    def get_next_file(self):
        try:
            next_file = self.files[self.current_file_index + 1]
            self.current_file_index += 1

            return next_file
        except:
            return False

    def get_prev_file(self):
        if 0 > self.current_file_index - 1:
            return False

        try:
            prev_file = self.files[self.current_file_index - 1]
            self.current_file_index -= 1

            return prev_file
        except:
            return False

    def open_dir(self):
        return QtGui.QFileDialog.getExistingDirectory()

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Right or e.key() == QtCore.Qt.Key_Period:
            next_file = self.get_next_file()
            if False != next_file:
                self.show_file(next_file)
        elif e.key() == QtCore.Qt.Key_Left or e.key() == QtCore.Qt.Key_Comma:
            prev_file = self.get_prev_file()
            if False != prev_file:
                self.show_file(prev_file)
        elif e.key() == QtCore.Qt.Key_C:
            self.copy_photo()
        elif e.key() == QtCore.Qt.Key_D:
            self.soft_delete_photo()
        elif e.key() == QtCore.Qt.Key_Backspace:
            self.delete_photo()

        QtGui.QWidget.keyPressEvent(self, e)

    def copy_photo(self):
        if not os.path.exists(self.copy_dir):
            os.makedirs(self.copy_dir)

        shutil.copy2(self.current_file, self.copy_dir)

        self.copy_btn.setText('Copied')

    def soft_delete_photo(self):
        if not os.path.exists(self.delete_dir):
            os.makedirs(self.delete_dir)

        shutil.move(self.current_file, self.delete_dir)
        self.__after_delete_photo()

        self.soft_delete_btn.setText('Deleted')

    def delete_photo(self):
        os.remove(self.current_file)
        self.__after_delete_photo()

        self.delete_btn.setText('Deleted')

    def __after_delete_photo(self):
        del self.files[self.current_file_index]
        # decrement current file index, because deleting file from list moves all next files one index down
        # now getting next file would get proper next file
        self.current_file_index -= 1

        next_file = self.get_next_file()
        if False != next_file:
            self.show_file(next_file)
        else:
            # its a little tricky, but to get previous file the index must be incremented so getting prev file wold get proper previous file
            self.current_file_index += 1

            prev_file = self.get_prev_file()
            if False != prev_file:
                self.show_file(prev_file)
            else:
                QtGui.QMessageBox.information(
                    self,
                    'No files in directory',
                    'Chosen directory does not contain any images',
                    QtGui.QMessageBox.Ok
                )
                exit()

# Create an PyQT4 application object.
a = QtGui.QApplication(sys.argv)

screen_resolution = a.desktop().screenGeometry()
screen_width, screen_height = screen_resolution.width(), screen_resolution.height()

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = Photochooser(screen_width - 20, screen_height - 50)

# Set window title
w.setWindowTitle("Photo Chooser")

sys.exit(a.exec_())
<|endoftext|>


<commit_before>"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import re
import os
import sys
import string

from .lstools_base import MbedLsToolsBase

import logging

if sys.version_info[0] < 3:
    import _winreg as winreg
else:
    import winreg

logger = logging.getLogger("mbedls.lstools_win7")

class MbedLsToolsWin7(MbedLsToolsBase):
    """ mbed-enabled platform detection for Windows
    """
    def __init__(self, **kwargs):
        MbedLsToolsBase.__init__(self, **kwargs)
        self.os_supported.append('Windows7')

    def find_candidates(self):
        return [
            {
                'mount_point': mnt,
                'target_id_usb_id': id,
                'serial_port': self._com_port(id)
            }
            for mnt, id in self.get_mbeds()
        ]

    def _com_port(self, tid):
        """! Function checks mbed serial port in Windows registry entries
        @param tid TargetID
        @return Returns None if port is not found. In normal circumstances it should never return None
        @details This goes through a whole new loop, but this assures that even if serial port (COM)
                 is not detected, we still get the rest of info like mount point etc.
        """
        winreg.Enum = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     r'SYSTEM\CurrentControlSet\Enum')
        usb_devs = winreg.OpenKey(winreg.Enum, 'USB')
        logger.debug("_com_port usb_devs %r",
                     list(self.iter_keys_as_str(usb_devs)))

        logger.debug("_com_port looking up usb id in all usb devices")
        dev_keys = []
        for name, vid in zip(self.iter_keys_as_str(usb_devs),
                             self.iter_keys(usb_devs)):
            try:
                dev_keys.append(winreg.OpenKey(vid, tid))
                if logger.isEnabledFor(logging.DEBUG):
                    logger.debug(
                        "Found usb id %s in %s with subkeys %r", tid, name,
                        list(self.iter_keys_as_str(winreg.OpenKey(vid, tid))))
            except OSError:
                pass

        logger.debug("_com_port Detecting port with Device Parameter")
        for key in dev_keys:
            try:
                param = winreg.OpenKey(key, "Device Parameters")
                port, regtype = winreg.QueryValueEx(param, 'PortName')
                logger.debug('_com_port port %r regtype %r', port, regtype)
                return port
            except OSError as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        logger.debug("_com_port Detecting port by following symlinks")
        for key in dev_keys:
            try:
                ports = []
                parent_id, regtype = winreg.QueryValueEx(key, 'ParentIdPrefix')
                logger.debug("_com_port parent_id %r regtype %r")
                for VID in self.iter_keys(usb_devs):
                    candidate_keys = [k for k in self.iter_keys_as_str(VID)
                                      if parent_id in k]
                    for dev in candidate_keys:
                        logger.debug(
                            "_com_port recursive port detection with %r", dev)
                        maybe_port = self._com_port(dev)
                        if maybe_port:
                            return maybe_port
            except OSError as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        # If everything fails, return None
        return None

    def get_mbeds(self):
        """! Function filters devices' mount points for valid TargetID
        @return Returns [(<mbed_mount_point>, <mbed_id>), ..]
        @details TargetID should be a hex string with 10-48 chars
        """
        mbeds = []
        for mbed in self.get_mbed_devices():
            mountpoint = re.match('.*\\\\(.:)$', mbed[0]).group(1)
            # TargetID is a hex string with 10-48 chars
            m = re.search('[&#]([0-9A-Za-z]{10,48})[&#]', mbed[1])
            if not m:
                continue
            tid = m.group(1)
            mbeds += [(mountpoint, tid)]
            logger.debug("get_mbeds mount_point %s usb_id %s", mountpoint, tid)
        return mbeds

    # =============================== Registry ====================================

    def iter_keys_as_str(self, key):
        """! Iterate over subkeys of a key returning subkey as string
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.EnumKey(key, i)

    def iter_keys(self, key):
        """! Iterate over subkeys of a key
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.OpenKey(key, winreg.EnumKey(key, i))

    def iter_vals(self, key):
        """! Iterate over values of a key
        """
        logger.debug("iter_vals %r", key)
        for i in range(winreg.QueryInfoKey(key)[1]):
            yield winreg.EnumValue(key, i)

    def get_mbed_devices(self):
        """! Get MBED devices (connected or not)
        @return List of devices
        @details Note: We will detect also non-standard MBED devices mentioned on 'usb_vendor_list' list.
                 This will help to detect boards like EFM boards.
        """
        upper_ven = [ven.upper() for ven in self.usb_vendor_list]
        mounts_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\MountedDevices')
        for point, label, _ in self.iter_vals(mounts_key):
            printable_label = label.decode('utf-16le', 'ignore')
            if (b'DosDevices' in point and
                any(v in printable_label.upper() for v in upper_ven)):
                logger.debug("Found Mount point %s with usb ID %s",point,
                             printable_label)
                yield (point.decode('utf-8', 'ignore'), printable_label)
            else:
                logger.debug("Skipping Mount point %r label %r", point, label)
<commit_msg>Fixing disconnected devices appearing in results on Windows<commit_after>"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import re
import os
import sys
import string

from .lstools_base import MbedLsToolsBase

import logging

if sys.version_info[0] < 3:
    import _winreg as winreg
else:
    import winreg

logger = logging.getLogger("mbedls.lstools_win7")

class MbedLsToolsWin7(MbedLsToolsBase):
    """ mbed-enabled platform detection for Windows
    """
    def __init__(self, **kwargs):
        MbedLsToolsBase.__init__(self, **kwargs)
        self.os_supported.append('Windows7')

    def find_candidates(self):
        return [
            {
                'mount_point': mnt,
                'target_id_usb_id': id,
                'serial_port': self._com_port(id)
            }
            for mnt, id in self.get_mbeds()
        ]

    def _com_port(self, tid):
        """! Function checks mbed serial port in Windows registry entries
        @param tid TargetID
        @return Returns None if port is not found. In normal circumstances it should never return None
        @details This goes through a whole new loop, but this assures that even if serial port (COM)
                 is not detected, we still get the rest of info like mount point etc.
        """
        winreg.Enum = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     r'SYSTEM\CurrentControlSet\Enum')
        usb_devs = winreg.OpenKey(winreg.Enum, 'USB')
        logger.debug("_com_port usb_devs %r",
                     list(self.iter_keys_as_str(usb_devs)))

        logger.debug("_com_port looking up usb id in all usb devices")
        dev_keys = []
        for name, vid in zip(self.iter_keys_as_str(usb_devs),
                             self.iter_keys(usb_devs)):
            try:
                dev_keys.append(winreg.OpenKey(vid, tid))
                if logger.isEnabledFor(logging.DEBUG):
                    logger.debug(
                        "Found usb id %s in %s with subkeys %r", tid, name,
                        list(self.iter_keys_as_str(winreg.OpenKey(vid, tid))))
            except OSError:
                pass

        logger.debug("_com_port Detecting port with Device Parameter")
        for key in dev_keys:
            try:
                param = winreg.OpenKey(key, "Device Parameters")
                port, regtype = winreg.QueryValueEx(param, 'PortName')
                logger.debug('_com_port port %r regtype %r', port, regtype)
                return port
            except OSError as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        logger.debug("_com_port Detecting port by following symlinks")
        for key in dev_keys:
            try:
                ports = []
                parent_id, regtype = winreg.QueryValueEx(key, 'ParentIdPrefix')
                logger.debug("_com_port parent_id %r regtype %r")
                for VID in self.iter_keys(usb_devs):
                    candidate_keys = [k for k in self.iter_keys_as_str(VID)
                                      if parent_id in k]
                    for dev in candidate_keys:
                        logger.debug(
                            "_com_port recursive port detection with %r", dev)
                        maybe_port = self._com_port(dev)
                        if maybe_port:
                            return maybe_port
            except OSError as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        # If everything fails, return None
        return None

    def _drive_letters(self):
        """! Function for finding all drive letters
        @return Returns an array of all drive letters present
        """
        cmd = ['fsutil', 'fsinfo', 'drives']
        logger.debug('running command: %s' % (' '.join(cmd)))
        stdout, _, retval = self._run_cli_process(cmd)
        logger.debug('return code: %d' % retval)
        logger.debug('output: %s' % stdout)

        if not retval:
            drive_list = re.match('\s*Drives: (.*)', stdout).group(1)
            return drive_list.strip().replace('\\', '').split(' ')
        return []

    def get_mbeds(self):
        """! Function filters devices' mount points for valid TargetID
        @return Returns [(<mbed_mount_point>, <mbed_id>), ..]
        @details TargetID should be a hex string with 10-48 chars
        """
        mbeds = []
        drive_letters = set(self._drive_letters())
        logger.debug('Found drive letters: %s' % ', '.join(drive_letters))
        for mbed in self.get_mbed_devices():
            mountpoint = re.match('.*\\\\(.:)$', mbed[0]).group(1)
            if mountpoint in drive_letters:
                # TargetID is a hex string with 10-48 chars
                m = re.search('[&#]([0-9A-Za-z]{10,48})[&#]', mbed[1])
                if not m:
                    continue
                tid = m.group(1)
                mbeds += [(mountpoint, tid)]
                logger.debug("get_mbeds mount_point %s usb_id %s", mountpoint, tid)
        return mbeds

    # =============================== Registry ====================================

    def iter_keys_as_str(self, key):
        """! Iterate over subkeys of a key returning subkey as string
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.EnumKey(key, i)

    def iter_keys(self, key):
        """! Iterate over subkeys of a key
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.OpenKey(key, winreg.EnumKey(key, i))

    def iter_vals(self, key):
        """! Iterate over values of a key
        """
        logger.debug("iter_vals %r", key)
        for i in range(winreg.QueryInfoKey(key)[1]):
            yield winreg.EnumValue(key, i)

    def get_mbed_devices(self):
        """! Get MBED devices (connected or not)
        @return List of devices
        @details Note: We will detect also non-standard MBED devices mentioned on 'usb_vendor_list' list.
                 This will help to detect boards like EFM boards.
        """
        upper_ven = [ven.upper() for ven in self.usb_vendor_list]
        mounts_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\MountedDevices')
        for point, label, _ in self.iter_vals(mounts_key):
            printable_label = label.decode('utf-16le', 'ignore')
            if (b'DosDevices' in point and
                any(v in printable_label.upper() for v in upper_ven)):
                logger.debug("Found Mount point %s with usb ID %s",point,
                             printable_label)
                yield (point.decode('utf-8', 'ignore'), printable_label)
            else:
                logger.debug("Skipping Mount point %r label %r", point, label)
<|endoftext|>


<commit_before><commit_msg>right and left are hard<commit_after><|endoftext|>


<commit_before>import base64
import json
import urllib
import urllib2
import datetime
import logging
import dateutil.parser
from django.utils.timezone import now as utcnow
import pytz

log = logging.getLogger('celery.task')

try:
    from celery.task import task
except ImportError:
    from celery.decorators import task

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import IntegrityError

from app_metrics.models import Metric, MetricItem, Gauge

# For statsd support
try:
    # Not required. If we do this once at the top of the module, we save
    # ourselves the pain of importing every time the task fires.
    import statsd
except ImportError:
    statsd = None

# For redis support
try:
    import redis
except:
    redis = None

# For librato support
try:
    import librato
    from librato.metrics import Gauge as LibratoGauge
    from librato.metrics import Counter as LibratoCounter
except ImportError:
    librato = None

class MixPanelTrackError(Exception):
    pass

@task
def db_metric_task(num=1, **kwargs):
    """This is a task to add a metric item"""
    if getattr(settings, 'DEBUG'):
        log.setLevel(logging.DEBUG)
    created = kwargs.pop('created', utcnow())
    if isinstance(created, basestring):
        try:
            created = dateutil.parser.parse(created).replace(tzinfo=pytz.utc)
        except:
            log.error("Unable to parse date from {}".format(created))
            created=utcnow()
    try:
        met, _ = Metric.objects.get_or_create(**kwargs)
        MetricItem.objects.create(metric=met, num=num, created=created)
    except IntegrityError:
        met, _ = Metric.objects.get(**kwargs)
        MetricItem.objects.create(metric=met, num=num, created=created)
    except Exception as err:
        issue = "Unable to complete task!! {} - kwargs: {}".format(err, kwargs)
        log.exception(issue)
        raise

@task
def db_gauge_task(current_value, **kwargs):
    """This is a task to adjust (or create) a guage"""
    if getattr(settings, 'DEBUG'):
        log.setLevel(logging.DEBUG)

    if 'defaults' not in kwargs.keys():
        kwargs['defaults'] = {}
    kwargs['defaults']['current_value'] = current_value
    gauge, created = Gauge.objects.get_or_create(**kwargs)
    if not created:
        gauge.current_value = current_value
        gauge.save()
    log.debug("{} Gauge {} to {}".format("Created" if created else "Updated", gauge, current_value))

def _get_token():
    token = getattr(settings, 'APP_METRICS_MIXPANEL_TOKEN', None)

    if not token:
        raise ImproperlyConfigured("You must define APP_METRICS_MIXPANEL_TOKEN when using the mixpanel backend.")
    else:
        return token

# Mixpanel tasks

@task
def mixpanel_metric_task(slug, num, properties=None, **kwargs):

    token = _get_token()
    if properties is None:
        properties = dict()

    if "token" not in properties:
        properties["token"] = token

    url = getattr(settings, 'APP_METRICS_MIXPANEL_API_URL', "http://api.mixpanel.com/track/")

    params = {"event": slug, "properties": properties}
    b64_data = base64.b64encode(json.dumps(params))

    data = urllib.urlencode({"data": b64_data})
    req = urllib2.Request(url, data)
    for i in range(num):
        response = urllib2.urlopen(req)
        if response.read() == '0':
            raise MixPanelTrackError(u'MixPanel returned 0')

# Statsd tasks

def get_statsd_conn():
    if statsd is None:
        raise ImproperlyConfigured("You must install 'python-statsd' in order to use this backend.")

    conn = statsd.Connection(
        host=getattr(settings, 'APP_METRICS_STATSD_HOST', 'localhost'),
        port=int(getattr(settings, 'APP_METRICS_STATSD_PORT', 8125)),
        sample_rate=float(getattr(settings, 'APP_METRICS_STATSD_SAMPLE_RATE', 1)),
    )
    return conn

@task
def statsd_metric_task(slug, num=1, **kwargs):
    conn = get_statsd_conn()
    counter = statsd.Counter(slug, connection=conn)
    counter += num

@task
def statsd_timing_task(slug, seconds_taken=1.0, **kwargs):
    conn = get_statsd_conn()

    # You might be wondering "Why not use ``timer.start/.stop`` here?"
    # The problem is that this is a task, likely running out of process
    # & perhaps with network overhead. We'll measure the timing elsewhere,
    # in-process, to be as accurate as possible, then use the out-of-process
    # task for talking to the statsd backend.
    timer = statsd.Timer(slug, connection=conn)
    timer.send('total', seconds_taken)

@task
def statsd_gauge_task(slug, current_value, **kwargs):
    conn = get_statsd_conn()
    gauge = statsd.Gauge(slug, connection=conn)
    # We send nothing here, since we only have one name/slug to work with here.
    gauge.send('', current_value)

# Redis tasks

def get_redis_conn():
    if redis is None:
        raise ImproperlyConfigured("You must install 'redis' in order to use this backend.")
    conn = redis.StrictRedis(
        host=getattr(settings, 'APP_METRICS_REDIS_HOST', 'localhost'),
        port=getattr(settings, 'APP_METRICS_REDIS_PORT', 6379),
        db=getattr(settings, 'APP_METRICS_REDIS_DB', 0),
    )
    return conn

@task
def redis_metric_task(slug, num=1, **kwargs):
    # Record a metric in redis. We prefix our key here with 'm' for Metric
    # and build keys for each day, week, month, and year
    r = get_redis_conn()

    # Build keys
    now = datetime.datetime.now()
    day_key = "m:%s:%s" % (slug, now.strftime("%Y-%m-%d"))
    week_key = "m:%s:w:%s" % (slug, now.strftime("%U"))
    month_key = "m:%s:m:%s" % (slug, now.strftime("%Y-%m"))
    year_key = "m:%s:y:%s" % (slug, now.strftime("%Y"))

    # Increment keys
    r.incrby(day_key, num)
    r.incrby(week_key, num)
    r.incrby(month_key, num)
    r.incrby(year_key, num)

@task
def redis_gauge_task(slug, current_value, **kwargs):
    # We prefix our keys with a 'g' here for Gauge to avoid issues
    # of having a gauge and metric of the same name
    r = get_redis_conn()
    r.set("g:%s" % slug, current_value)

# Librato tasks

@task
def librato_metric_task(name, num, attributes=None, metric_type="gauge",
                        **kwargs):
    connection = librato.connect(settings.APP_METRICS_LIBRATO_USER,
                                 settings.APP_METRICS_LIBRATO_TOKEN)

    if metric_type == "counter":
        metric = LibratoCounter(connection, name, attributes=attributes)
    else:
        metric = LibratoGauge(connection, name, attributes=attributes)

    metric.add(num, source=settings.APP_METRICS_LIBRATO_SOURCE)
<commit_msg>Python 3 quick fix.  Not complete<commit_after>import base64
import json
import urllib
import datetime
import logging
import dateutil.parser
from django.utils.timezone import now as utcnow
import pytz
import six

log = logging.getLogger('celery.task')

try:
    from celery.task import task
except ImportError:
    from celery.decorators import task

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import IntegrityError

from app_metrics.models import Metric, MetricItem, Gauge

# For statsd support
try:
    # Not required. If we do this once at the top of the module, we save
    # ourselves the pain of importing every time the task fires.
    import statsd
except ImportError:
    statsd = None

# For redis support
try:
    import redis
except:
    redis = None

# For librato support
try:
    import librato
    from librato.metrics import Gauge as LibratoGauge
    from librato.metrics import Counter as LibratoCounter
except ImportError:
    librato = None

class MixPanelTrackError(Exception):
    pass

@task
def db_metric_task(num=1, **kwargs):
    """This is a task to add a metric item"""
    if getattr(settings, 'DEBUG'):
        log.setLevel(logging.DEBUG)
    created = kwargs.pop('created', utcnow())
    if isinstance(created, six.string_types):
        try:
            created = dateutil.parser.parse(created).replace(tzinfo=pytz.utc)
        except:
            log.error("Unable to parse date from {}".format(created))
            created=utcnow()
    try:
        met, _ = Metric.objects.get_or_create(**kwargs)
        MetricItem.objects.create(metric=met, num=num, created=created)
    except IntegrityError:
        met, _ = Metric.objects.get(**kwargs)
        MetricItem.objects.create(metric=met, num=num, created=created)
    except Exception as err:
        issue = "Unable to complete task!! {} - kwargs: {}".format(err, kwargs)
        log.exception(issue)
        raise

@task
def db_gauge_task(current_value, **kwargs):
    """This is a task to adjust (or create) a guage"""
    if getattr(settings, 'DEBUG'):
        log.setLevel(logging.DEBUG)

    if 'defaults' not in kwargs.keys():
        kwargs['defaults'] = {}
    kwargs['defaults']['current_value'] = current_value
    gauge, created = Gauge.objects.get_or_create(**kwargs)
    if not created:
        gauge.current_value = current_value
        gauge.save()
    log.debug("{} Gauge {} to {}".format("Created" if created else "Updated", gauge, current_value))

def _get_token():
    token = getattr(settings, 'APP_METRICS_MIXPANEL_TOKEN', None)

    if not token:
        raise ImproperlyConfigured("You must define APP_METRICS_MIXPANEL_TOKEN when using the mixpanel backend.")
    else:
        return token

# Mixpanel tasks

@task
def mixpanel_metric_task(slug, num, properties=None, **kwargs):

    import urllib2

    token = _get_token()
    if properties is None:
        properties = dict()

    if "token" not in properties:
        properties["token"] = token

    url = getattr(settings, 'APP_METRICS_MIXPANEL_API_URL', "http://api.mixpanel.com/track/")

    params = {"event": slug, "properties": properties}
    b64_data = base64.b64encode(json.dumps(params))

    data = urllib.urlencode({"data": b64_data})
    req = urllib2.Request(url, data)
    for i in range(num):
        response = urllib2.urlopen(req)
        if response.read() == '0':
            raise MixPanelTrackError(u'MixPanel returned 0')

# Statsd tasks

def get_statsd_conn():
    if statsd is None:
        raise ImproperlyConfigured("You must install 'python-statsd' in order to use this backend.")

    conn = statsd.Connection(
        host=getattr(settings, 'APP_METRICS_STATSD_HOST', 'localhost'),
        port=int(getattr(settings, 'APP_METRICS_STATSD_PORT', 8125)),
        sample_rate=float(getattr(settings, 'APP_METRICS_STATSD_SAMPLE_RATE', 1)),
    )
    return conn

@task
def statsd_metric_task(slug, num=1, **kwargs):
    conn = get_statsd_conn()
    counter = statsd.Counter(slug, connection=conn)
    counter += num

@task
def statsd_timing_task(slug, seconds_taken=1.0, **kwargs):
    conn = get_statsd_conn()

    # You might be wondering "Why not use ``timer.start/.stop`` here?"
    # The problem is that this is a task, likely running out of process
    # & perhaps with network overhead. We'll measure the timing elsewhere,
    # in-process, to be as accurate as possible, then use the out-of-process
    # task for talking to the statsd backend.
    timer = statsd.Timer(slug, connection=conn)
    timer.send('total', seconds_taken)

@task
def statsd_gauge_task(slug, current_value, **kwargs):
    conn = get_statsd_conn()
    gauge = statsd.Gauge(slug, connection=conn)
    # We send nothing here, since we only have one name/slug to work with here.
    gauge.send('', current_value)

# Redis tasks

def get_redis_conn():
    if redis is None:
        raise ImproperlyConfigured("You must install 'redis' in order to use this backend.")
    conn = redis.StrictRedis(
        host=getattr(settings, 'APP_METRICS_REDIS_HOST', 'localhost'),
        port=getattr(settings, 'APP_METRICS_REDIS_PORT', 6379),
        db=getattr(settings, 'APP_METRICS_REDIS_DB', 0),
    )
    return conn

@task
def redis_metric_task(slug, num=1, **kwargs):
    # Record a metric in redis. We prefix our key here with 'm' for Metric
    # and build keys for each day, week, month, and year
    r = get_redis_conn()

    # Build keys
    now = datetime.datetime.now()
    day_key = "m:%s:%s" % (slug, now.strftime("%Y-%m-%d"))
    week_key = "m:%s:w:%s" % (slug, now.strftime("%U"))
    month_key = "m:%s:m:%s" % (slug, now.strftime("%Y-%m"))
    year_key = "m:%s:y:%s" % (slug, now.strftime("%Y"))

    # Increment keys
    r.incrby(day_key, num)
    r.incrby(week_key, num)
    r.incrby(month_key, num)
    r.incrby(year_key, num)

@task
def redis_gauge_task(slug, current_value, **kwargs):
    # We prefix our keys with a 'g' here for Gauge to avoid issues
    # of having a gauge and metric of the same name
    r = get_redis_conn()
    r.set("g:%s" % slug, current_value)

# Librato tasks

@task
def librato_metric_task(name, num, attributes=None, metric_type="gauge",
                        **kwargs):
    connection = librato.connect(settings.APP_METRICS_LIBRATO_USER,
                                 settings.APP_METRICS_LIBRATO_TOKEN)

    if metric_type == "counter":
        metric = LibratoCounter(connection, name, attributes=attributes)
    else:
        metric = LibratoGauge(connection, name, attributes=attributes)

    metric.add(num, source=settings.APP_METRICS_LIBRATO_SOURCE)
<|endoftext|>


<commit_before>import os, sys
import pygame

class AlarmClock:
    """Alarm clock class"""

    def __init__(self, width=320, height=240):
        pygame.init()
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((self.width, self.height))

    def MainLoop(self):
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

if __name__ == "__main__":
        MainWindow = AlarmClock()
        MainWindow.MainLoop()
        <commit_msg>Full screen support<commit_after>import os, sys
import pygame

class AlarmClock:
    """Alarm clock class"""

    def __init__(self, width=320, height=240):
        pygame.init()
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((self.width, self.height),pygame.FULLSCREEN)

    def MainLoop(self):
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

if __name__ == "__main__":
        MainWindow = AlarmClock()
        MainWindow.MainLoop()
        <|endoftext|>


<commit_before>"""Convenient HTTP UserAgent class.

This is a subclass of urllib2.OpenerDirector.

Copyright 2003-2006 John J. Lee <jjl@pobox.com>

This code is free software; you can redistribute it and/or modify it under
the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt
included with the distribution).

"""

import sys, warnings, urllib2

import _opener
import _urllib2
import _auth
import _gzip
import _response

class UserAgentBase(_opener.OpenerDirector):
    """Convenient user-agent class.

    Do not use .add_handler() to add a handler for something already dealt with
    by this code.

    The only reason at present for the distinction between UserAgent and
    UserAgentBase is so that classes that depend on .seek()able responses
    (e.g. mechanize.Browser) can inherit from UserAgentBase.  The subclass
    UserAgent exposes a .set_seekable_responses() method that allows switching
    off the adding of a .seek() method to responses.

    Public attributes:

    addheaders: list of (name, value) pairs specifying headers to send with
     every request, unless they are overridden in the Request instance.

     >>> ua = UserAgentBase()
     >>> ua.addheaders = [
     ...  ("User-agent", "Mozilla/5.0 (compatible)"),
     ...  ("From", "responsible.person@example.com")]

    """

    handler_classes = {
        # scheme handlers
        "http": _urllib2.HTTPHandler,
        # CacheFTPHandler is buggy, at least in 2.3, so we don't use it
        "ftp": _urllib2.FTPHandler,
        "file": _urllib2.FileHandler,

        # other handlers
        "_unknown": _urllib2.UnknownHandler,
        # HTTP{S,}Handler depend on HTTPErrorProcessor too
        "_http_error": _urllib2.HTTPErrorProcessor,
        "_http_request_upgrade": _urllib2.HTTPRequestUpgradeProcessor,
        "_http_default_error": _urllib2.HTTPDefaultErrorHandler,

        # feature handlers
        "_basicauth": _urllib2.HTTPBasicAuthHandler,
        "_digestauth": _urllib2.HTTPDigestAuthHandler,
        "_redirect": _urllib2.HTTPRedirectHandler,
        "_cookies": _urllib2.HTTPCookieProcessor,
        "_refresh": _urllib2.HTTPRefreshProcessor,
        "_equiv": _urllib2.HTTPEquivProcessor,
        "_proxy": _urllib2.ProxyHandler,
        "_proxy_basicauth": _urllib2.ProxyBasicAuthHandler,
        "_proxy_digestauth": _urllib2.ProxyDigestAuthHandler,
        "_robots": _urllib2.HTTPRobotRulesProcessor,
        "_gzip": _gzip.HTTPGzipProcessor,  # experimental!

        # debug handlers
        "_debug_redirect": _urllib2.HTTPRedirectDebugProcessor,
        "_debug_response_body": _urllib2.HTTPResponseDebugProcessor,
        }

    default_schemes = ["http", "ftp", "file"]
    default_others = ["_unknown", "_http_error", "_http_request_upgrade",
                      "_http_default_error",
                      ]
    default_features = ["_redirect", "_cookies",
                        "_refresh", "_equiv",
                        "_basicauth", "_digestauth",
                        "_proxy", "_proxy_basicauth", "_proxy_digestauth",
                        "_robots",
                        ]
    if hasattr(_urllib2, 'HTTPSHandler'):
        handler_classes["https"] = _urllib2.HTTPSHandler
        default_schemes.append("https")

    def __init__(self):
        _opener.OpenerDirector.__init__(self)

        ua_handlers = self._ua_handlers = {}
        for scheme in (self.default_schemes+
                       self.default_others+
                       self.default_features):
            klass = self.handler_classes[scheme]
            ua_handlers[scheme] = klass()
        for handler in ua_handlers.itervalues():
            self.add_handler(handler)

        # Yuck.
        # Ensure correct default constructor args were passed to
        # HTTPRefreshProcessor and HTTPEquivProcessor.
        if "_refresh" in ua_handlers:
            self.set_handle_refresh(True)
        if "_equiv" in ua_handlers:
            self.set_handle_equiv(True)
        # Ensure default password managers are installed.
        pm = ppm = None
        if "_basicauth" in ua_handlers or "_digestauth" in ua_handlers:
            pm = _urllib2.HTTPPasswordMgrWithDefaultRealm()
        if ("_proxy_basicauth" in ua_handlers or
            "_proxy_digestauth" in ua_handlers):
            ppm = _auth.HTTPProxyPasswordMgr()
        self.set_password_manager(pm)
        self.set_proxy_password_manager(ppm)
        # set default certificate manager
        if "https" in ua_handlers:
            cm = _urllib2.HTTPSClientCertMgr()
            self.set_client_cert_manager(cm)

    def close(self):
        _opener.OpenerDirector.close(self)
        self._ua_handlers = None

    # XXX
##     def set_timeout(self, timeout):
##         self._timeout = timeout
##     def set_http_connection_cache(self, conn_cache):
##         self._http_conn_cache = conn_cache
##     def set_ftp_connection_cache(self, conn_cache):
##         # XXX ATM, FTP has cache as part of handler; should it be separate?
##         self._ftp_conn_cache = conn_cache

    def set_handled_schemes(self, schemes):
        """Set sequence of URL scheme (protocol) strings.

        For example: ua.set_handled_schemes(["http", "ftp"])

        If this fails (with ValueError) because you've passed an unknown
        scheme, the set of handled schemes will not be changed.

        """
        want = {}
        for scheme in schemes:
            if scheme.startswith("_"):
                raise ValueError("not a scheme '%s'" % scheme)
            if scheme not in self.handler_classes:
                raise ValueError("unknown scheme '%s'")
            want[scheme] = None

        # get rid of scheme handlers we don't want
        for scheme, oldhandler in self._ua_handlers.items():
            if scheme.startswith("_"): continue  # not a scheme handler
            if scheme not in want:
                self._replace_handler(scheme, None)
            else:
                del want[scheme]  # already got it
        # add the scheme handlers that are missing
        for scheme in want.keys():
            self._set_handler(scheme, True)

    def set_cookiejar(self, cookiejar):
        """Set a mechanize.CookieJar, or None."""
        self._set_handler("_cookies", obj=cookiejar)

    # XXX could use Greg Stein's httpx for some of this instead?
    # or httplib2??
    def set_proxies(self, proxies):
        """Set a dictionary mapping URL scheme to proxy specification, or None.

        e.g. {"http": "joe:password@myproxy.example.com:3128",
              "ftp": "proxy.example.com"}

        """
        self._set_handler("_proxy", obj=proxies)

    def add_password(self, url, user, password, realm=None):
        self._password_manager.add_password(realm, url, user, password)
    def add_proxy_password(self, user, password, hostport=None, realm=None):
        self._proxy_password_manager.add_password(
            realm, hostport, user, password)

    def add_client_certificate(self, url, key_file, cert_file):
        """Add an SSL client certificate, for HTTPS client auth.

        key_file and cert_file must be filenames of the key and certificate
        files, in PEM format.  You can use e.g. OpenSSL to convert a p12 (PKCS
        12) file to PEM format:

        openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem
        openssl pkcs12 -nocerts -in cert.p12 -out key.pem

        Note that client certificate password input is very inflexible ATM.  At
        the moment this seems to be console only, which is presumably the
        default behaviour of libopenssl.  In future mechanize may support
        third-party libraries that (I assume) allow more options here.

        """
        self._client_cert_manager.add_key_cert(url, key_file, cert_file)

    # the following are rarely useful -- use add_password / add_proxy_password
    # instead
    def set_password_manager(self, password_manager):
        """Set a mechanize.HTTPPasswordMgrWithDefaultRealm, or None."""
        self._password_manager = password_manager
        self._set_handler("_basicauth", obj=password_manager)
        self._set_handler("_digestauth", obj=password_manager)
    def set_proxy_password_manager(self, password_manager):
        """Set a mechanize.HTTPProxyPasswordMgr, or None."""
        self._proxy_password_manager = password_manager
        self._set_handler("_proxy_basicauth", obj=password_manager)
        self._set_handler("_proxy_digestauth", obj=password_manager)
    def set_client_cert_manager(self, cert_manager):
        """Set a mechanize.HTTPClientCertMgr, or None."""
        self._client_cert_manager = cert_manager
        handler = self._ua_handlers["https"]
        handler.client_cert_manager = cert_manager

    # these methods all take a boolean parameter
    def set_handle_robots(self, handle):
        """Set whether to observe rules from robots.txt."""
        self._set_handler("_robots", handle)
    def set_handle_redirect(self, handle):
        """Set whether to handle HTTP 30x redirections."""
        self._set_handler("_redirect", handle)
    def set_handle_refresh(self, handle, max_time=None, honor_time=True):
        """Set whether to handle HTTP Refresh headers."""
        self._set_handler("_refresh", handle, constructor_kwds=
                          {"max_time": max_time, "honor_time": honor_time})
    def set_handle_equiv(self, handle, head_parser_class=None):
        """Set whether to treat HTML http-equiv headers like HTTP headers.

        Response objects may be .seek()able if this is set (currently returned
        responses are, raised HTTPError exception responses are not).

        """
        if head_parser_class is not None:
            constructor_kwds = {"head_parser_class": head_parser_class}
        else:
            constructor_kwds={}
        self._set_handler("_equiv", handle, constructor_kwds=constructor_kwds)
    def set_handle_gzip(self, handle):
        """Handle gzip transfer encoding.

        """
        if handle:
            warnings.warn(
                "gzip transfer encoding is experimental!", stacklevel=2)
        self._set_handler("_gzip", handle)
    def set_debug_redirects(self, handle):
        """Log information about HTTP redirects (including refreshes).

        Logging is performed using module logging.  The logger name is
        "mechanize.http_redirects".  To actually print some debug output,
        eg:

        import sys, logging
        logger = logging.getLogger("mechanize.http_redirects")
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.INFO)

        Other logger names relevant to this module:

        "mechanize.http_responses"
        "mechanize.cookies" (or "cookielib" if running Python 2.4)

        To turn on everything:

        import sys, logging
        logger = logging.getLogger("mechanize")
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.INFO)

        """
        self._set_handler("_debug_redirect", handle)
    def set_debug_responses(self, handle):
        """Log HTTP response bodies.

        See docstring for .set_debug_redirects() for details of logging.

        Response objects may be .seek()able if this is set (currently returned
        responses are, raised HTTPError exception responses are not).

        """
        self._set_handler("_debug_response_body", handle)
    def set_debug_http(self, handle):
        """Print HTTP headers to sys.stdout."""
        level = int(bool(handle))
        for scheme in "http", "https":
            h = self._ua_handlers.get(scheme)
            if h is not None:
                h.set_http_debuglevel(level)

    def _set_handler(self, name, handle=None, obj=None,
                     constructor_args=(), constructor_kwds={}):
        if handle is None:
            handle = obj is not None
        if handle:
            handler_class = self.handler_classes[name]
            if obj is not None:
                newhandler = handler_class(obj)
            else:
                newhandler = handler_class(*constructor_args, **constructor_kwds)
        else:
            newhandler = None
        self._replace_handler(name, newhandler)

    def _replace_handler(self, name, newhandler=None):
        # first, if handler was previously added, remove it
        if name is not None:
            handler = self._ua_handlers.get(name)
            if handler:
                try:
                    self.handlers.remove(handler)
                except ValueError:
                    pass
        # then add the replacement, if any
        if newhandler is not None:
            self.add_handler(newhandler)
            self._ua_handlers[name] = newhandler

class UserAgent(UserAgentBase):

    def __init__(self):
        UserAgentBase.__init__(self)
        self._seekable = False

    def set_seekable_responses(self, handle):
        """Make response objects .seek()able."""
        self._seekable = bool(handle)

    def open(self, fullurl, data=None):
        if self._seekable:
            def bound_open(fullurl, data=None):
                return UserAgentBase.open(self, fullurl, data)
            response = _opener.wrapped_open(
                bound_open, _response.seek_wrapped_response, fullurl, data)
        else:
            response = UserAgentBase.open(self, fullurl, data)
        return response
<commit_msg>Change default mechanize.UserAgent (hence mechanize.Browser) Refresh behaviour:  * Don't follow Refreshes > 30 seconds  * honor_time is now False by default<commit_after>"""Convenient HTTP UserAgent class.

This is a subclass of urllib2.OpenerDirector.

Copyright 2003-2006 John J. Lee <jjl@pobox.com>

This code is free software; you can redistribute it and/or modify it under
the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt
included with the distribution).

"""

import sys, warnings, urllib2

import _opener
import _urllib2
import _auth
import _gzip
import _response

class UserAgentBase(_opener.OpenerDirector):
    """Convenient user-agent class.

    Do not use .add_handler() to add a handler for something already dealt with
    by this code.

    The only reason at present for the distinction between UserAgent and
    UserAgentBase is so that classes that depend on .seek()able responses
    (e.g. mechanize.Browser) can inherit from UserAgentBase.  The subclass
    UserAgent exposes a .set_seekable_responses() method that allows switching
    off the adding of a .seek() method to responses.

    Public attributes:

    addheaders: list of (name, value) pairs specifying headers to send with
     every request, unless they are overridden in the Request instance.

     >>> ua = UserAgentBase()
     >>> ua.addheaders = [
     ...  ("User-agent", "Mozilla/5.0 (compatible)"),
     ...  ("From", "responsible.person@example.com")]

    """

    handler_classes = {
        # scheme handlers
        "http": _urllib2.HTTPHandler,
        # CacheFTPHandler is buggy, at least in 2.3, so we don't use it
        "ftp": _urllib2.FTPHandler,
        "file": _urllib2.FileHandler,

        # other handlers
        "_unknown": _urllib2.UnknownHandler,
        # HTTP{S,}Handler depend on HTTPErrorProcessor too
        "_http_error": _urllib2.HTTPErrorProcessor,
        "_http_request_upgrade": _urllib2.HTTPRequestUpgradeProcessor,
        "_http_default_error": _urllib2.HTTPDefaultErrorHandler,

        # feature handlers
        "_basicauth": _urllib2.HTTPBasicAuthHandler,
        "_digestauth": _urllib2.HTTPDigestAuthHandler,
        "_redirect": _urllib2.HTTPRedirectHandler,
        "_cookies": _urllib2.HTTPCookieProcessor,
        "_refresh": _urllib2.HTTPRefreshProcessor,
        "_equiv": _urllib2.HTTPEquivProcessor,
        "_proxy": _urllib2.ProxyHandler,
        "_proxy_basicauth": _urllib2.ProxyBasicAuthHandler,
        "_proxy_digestauth": _urllib2.ProxyDigestAuthHandler,
        "_robots": _urllib2.HTTPRobotRulesProcessor,
        "_gzip": _gzip.HTTPGzipProcessor,  # experimental!

        # debug handlers
        "_debug_redirect": _urllib2.HTTPRedirectDebugProcessor,
        "_debug_response_body": _urllib2.HTTPResponseDebugProcessor,
        }

    default_schemes = ["http", "ftp", "file"]
    default_others = ["_unknown", "_http_error", "_http_request_upgrade",
                      "_http_default_error",
                      ]
    default_features = ["_redirect", "_cookies",
                        "_refresh", "_equiv",
                        "_basicauth", "_digestauth",
                        "_proxy", "_proxy_basicauth", "_proxy_digestauth",
                        "_robots",
                        ]
    if hasattr(_urllib2, 'HTTPSHandler'):
        handler_classes["https"] = _urllib2.HTTPSHandler
        default_schemes.append("https")

    def __init__(self):
        _opener.OpenerDirector.__init__(self)

        ua_handlers = self._ua_handlers = {}
        for scheme in (self.default_schemes+
                       self.default_others+
                       self.default_features):
            klass = self.handler_classes[scheme]
            ua_handlers[scheme] = klass()
        for handler in ua_handlers.itervalues():
            self.add_handler(handler)

        # Yuck.
        # Ensure correct default constructor args were passed to
        # HTTPRefreshProcessor and HTTPEquivProcessor.
        if "_refresh" in ua_handlers:
            self.set_handle_refresh(True)
        if "_equiv" in ua_handlers:
            self.set_handle_equiv(True)
        # Ensure default password managers are installed.
        pm = ppm = None
        if "_basicauth" in ua_handlers or "_digestauth" in ua_handlers:
            pm = _urllib2.HTTPPasswordMgrWithDefaultRealm()
        if ("_proxy_basicauth" in ua_handlers or
            "_proxy_digestauth" in ua_handlers):
            ppm = _auth.HTTPProxyPasswordMgr()
        self.set_password_manager(pm)
        self.set_proxy_password_manager(ppm)
        # set default certificate manager
        if "https" in ua_handlers:
            cm = _urllib2.HTTPSClientCertMgr()
            self.set_client_cert_manager(cm)

    def close(self):
        _opener.OpenerDirector.close(self)
        self._ua_handlers = None

    # XXX
##     def set_timeout(self, timeout):
##         self._timeout = timeout
##     def set_http_connection_cache(self, conn_cache):
##         self._http_conn_cache = conn_cache
##     def set_ftp_connection_cache(self, conn_cache):
##         # XXX ATM, FTP has cache as part of handler; should it be separate?
##         self._ftp_conn_cache = conn_cache

    def set_handled_schemes(self, schemes):
        """Set sequence of URL scheme (protocol) strings.

        For example: ua.set_handled_schemes(["http", "ftp"])

        If this fails (with ValueError) because you've passed an unknown
        scheme, the set of handled schemes will not be changed.

        """
        want = {}
        for scheme in schemes:
            if scheme.startswith("_"):
                raise ValueError("not a scheme '%s'" % scheme)
            if scheme not in self.handler_classes:
                raise ValueError("unknown scheme '%s'")
            want[scheme] = None

        # get rid of scheme handlers we don't want
        for scheme, oldhandler in self._ua_handlers.items():
            if scheme.startswith("_"): continue  # not a scheme handler
            if scheme not in want:
                self._replace_handler(scheme, None)
            else:
                del want[scheme]  # already got it
        # add the scheme handlers that are missing
        for scheme in want.keys():
            self._set_handler(scheme, True)

    def set_cookiejar(self, cookiejar):
        """Set a mechanize.CookieJar, or None."""
        self._set_handler("_cookies", obj=cookiejar)

    # XXX could use Greg Stein's httpx for some of this instead?
    # or httplib2??
    def set_proxies(self, proxies):
        """Set a dictionary mapping URL scheme to proxy specification, or None.

        e.g. {"http": "joe:password@myproxy.example.com:3128",
              "ftp": "proxy.example.com"}

        """
        self._set_handler("_proxy", obj=proxies)

    def add_password(self, url, user, password, realm=None):
        self._password_manager.add_password(realm, url, user, password)
    def add_proxy_password(self, user, password, hostport=None, realm=None):
        self._proxy_password_manager.add_password(
            realm, hostport, user, password)

    def add_client_certificate(self, url, key_file, cert_file):
        """Add an SSL client certificate, for HTTPS client auth.

        key_file and cert_file must be filenames of the key and certificate
        files, in PEM format.  You can use e.g. OpenSSL to convert a p12 (PKCS
        12) file to PEM format:

        openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem
        openssl pkcs12 -nocerts -in cert.p12 -out key.pem

        Note that client certificate password input is very inflexible ATM.  At
        the moment this seems to be console only, which is presumably the
        default behaviour of libopenssl.  In future mechanize may support
        third-party libraries that (I assume) allow more options here.

        """
        self._client_cert_manager.add_key_cert(url, key_file, cert_file)

    # the following are rarely useful -- use add_password / add_proxy_password
    # instead
    def set_password_manager(self, password_manager):
        """Set a mechanize.HTTPPasswordMgrWithDefaultRealm, or None."""
        self._password_manager = password_manager
        self._set_handler("_basicauth", obj=password_manager)
        self._set_handler("_digestauth", obj=password_manager)
    def set_proxy_password_manager(self, password_manager):
        """Set a mechanize.HTTPProxyPasswordMgr, or None."""
        self._proxy_password_manager = password_manager
        self._set_handler("_proxy_basicauth", obj=password_manager)
        self._set_handler("_proxy_digestauth", obj=password_manager)
    def set_client_cert_manager(self, cert_manager):
        """Set a mechanize.HTTPClientCertMgr, or None."""
        self._client_cert_manager = cert_manager
        handler = self._ua_handlers["https"]
        handler.client_cert_manager = cert_manager

    # these methods all take a boolean parameter
    def set_handle_robots(self, handle):
        """Set whether to observe rules from robots.txt."""
        self._set_handler("_robots", handle)
    def set_handle_redirect(self, handle):
        """Set whether to handle HTTP 30x redirections."""
        self._set_handler("_redirect", handle)
    def set_handle_refresh(self, handle, max_time=30.0, honor_time=False):
        """Set whether to handle HTTP Refresh headers."""
        self._set_handler("_refresh", handle, constructor_kwds=
                          {"max_time": max_time, "honor_time": honor_time})
    def set_handle_equiv(self, handle, head_parser_class=None):
        """Set whether to treat HTML http-equiv headers like HTTP headers.

        Response objects may be .seek()able if this is set (currently returned
        responses are, raised HTTPError exception responses are not).

        """
        if head_parser_class is not None:
            constructor_kwds = {"head_parser_class": head_parser_class}
        else:
            constructor_kwds={}
        self._set_handler("_equiv", handle, constructor_kwds=constructor_kwds)
    def set_handle_gzip(self, handle):
        """Handle gzip transfer encoding.

        """
        if handle:
            warnings.warn(
                "gzip transfer encoding is experimental!", stacklevel=2)
        self._set_handler("_gzip", handle)
    def set_debug_redirects(self, handle):
        """Log information about HTTP redirects (including refreshes).

        Logging is performed using module logging.  The logger name is
        "mechanize.http_redirects".  To actually print some debug output,
        eg:

        import sys, logging
        logger = logging.getLogger("mechanize.http_redirects")
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.INFO)

        Other logger names relevant to this module:

        "mechanize.http_responses"
        "mechanize.cookies" (or "cookielib" if running Python 2.4)

        To turn on everything:

        import sys, logging
        logger = logging.getLogger("mechanize")
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.INFO)

        """
        self._set_handler("_debug_redirect", handle)
    def set_debug_responses(self, handle):
        """Log HTTP response bodies.

        See docstring for .set_debug_redirects() for details of logging.

        Response objects may be .seek()able if this is set (currently returned
        responses are, raised HTTPError exception responses are not).

        """
        self._set_handler("_debug_response_body", handle)
    def set_debug_http(self, handle):
        """Print HTTP headers to sys.stdout."""
        level = int(bool(handle))
        for scheme in "http", "https":
            h = self._ua_handlers.get(scheme)
            if h is not None:
                h.set_http_debuglevel(level)

    def _set_handler(self, name, handle=None, obj=None,
                     constructor_args=(), constructor_kwds={}):
        if handle is None:
            handle = obj is not None
        if handle:
            handler_class = self.handler_classes[name]
            if obj is not None:
                newhandler = handler_class(obj)
            else:
                newhandler = handler_class(*constructor_args, **constructor_kwds)
        else:
            newhandler = None
        self._replace_handler(name, newhandler)

    def _replace_handler(self, name, newhandler=None):
        # first, if handler was previously added, remove it
        if name is not None:
            handler = self._ua_handlers.get(name)
            if handler:
                try:
                    self.handlers.remove(handler)
                except ValueError:
                    pass
        # then add the replacement, if any
        if newhandler is not None:
            self.add_handler(newhandler)
            self._ua_handlers[name] = newhandler

class UserAgent(UserAgentBase):

    def __init__(self):
        UserAgentBase.__init__(self)
        self._seekable = False

    def set_seekable_responses(self, handle):
        """Make response objects .seek()able."""
        self._seekable = bool(handle)

    def open(self, fullurl, data=None):
        if self._seekable:
            def bound_open(fullurl, data=None):
                return UserAgentBase.open(self, fullurl, data)
            response = _opener.wrapped_open(
                bound_open, _response.seek_wrapped_response, fullurl, data)
        else:
            response = UserAgentBase.open(self, fullurl, data)
        return response
<|endoftext|>