repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
qqqmr/digitalwurlitzer | refs/heads/master | node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py | 1835 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""New implementation of Visual Studio project generation."""
import os
import random
import gyp.common
# hashlib is supplied as of Python 2.5 as the replacement interface for md5
# and other secure hashes. In 2.6, md5 is deprecated. Import hashlib if
# available, avoiding a deprecation warning under 2.6. Import md5 otherwise,
# preserving 2.4 compatibility.
try:
import hashlib
_new_md5 = hashlib.md5
except ImportError:
import md5
_new_md5 = md5.new
# Initialize random number generator
random.seed()
# GUIDs for project types
ENTRY_TYPE_GUIDS = {
'project': '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}',
'folder': '{2150E333-8FDC-42A3-9474-1A3956D46DE8}',
}
#------------------------------------------------------------------------------
# Helper functions
def MakeGuid(name, seed='msvs_new'):
"""Returns a GUID for the specified target name.
Args:
name: Target name.
seed: Seed for MD5 hash.
Returns:
A GUID-line string calculated from the name and seed.
This generates something which looks like a GUID, but depends only on the
name and seed. This means the same name/seed will always generate the same
GUID, so that projects and solutions which refer to each other can explicitly
determine the GUID to refer to explicitly. It also means that the GUID will
not change when the project for a target is rebuilt.
"""
# Calculate a MD5 signature for the seed and name.
d = _new_md5(str(seed) + str(name)).hexdigest().upper()
# Convert most of the signature to GUID form (discard the rest)
guid = ('{' + d[:8] + '-' + d[8:12] + '-' + d[12:16] + '-' + d[16:20]
+ '-' + d[20:32] + '}')
return guid
#------------------------------------------------------------------------------
class MSVSSolutionEntry(object):
def __cmp__(self, other):
# Sort by name then guid (so things are in order on vs2008).
return cmp((self.name, self.get_guid()), (other.name, other.get_guid()))
class MSVSFolder(MSVSSolutionEntry):
"""Folder in a Visual Studio project or solution."""
def __init__(self, path, name = None, entries = None,
guid = None, items = None):
"""Initializes the folder.
Args:
path: Full path to the folder.
name: Name of the folder.
entries: List of folder entries to nest inside this folder. May contain
Folder or Project objects. May be None, if the folder is empty.
guid: GUID to use for folder, if not None.
items: List of solution items to include in the folder project. May be
None, if the folder does not directly contain items.
"""
if name:
self.name = name
else:
# Use last layer.
self.name = os.path.basename(path)
self.path = path
self.guid = guid
# Copy passed lists (or set to empty lists)
self.entries = sorted(list(entries or []))
self.items = list(items or [])
self.entry_type_guid = ENTRY_TYPE_GUIDS['folder']
def get_guid(self):
if self.guid is None:
# Use consistent guids for folders (so things don't regenerate).
self.guid = MakeGuid(self.path, seed='msvs_folder')
return self.guid
#------------------------------------------------------------------------------
class MSVSProject(MSVSSolutionEntry):
"""Visual Studio project."""
def __init__(self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None):
"""Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath
"""
self.path = path
self.guid = guid
self.spec = spec
self.build_file = build_file
# Use project filename if name not specified
self.name = name or os.path.splitext(os.path.basename(path))[0]
# Copy passed lists (or set to empty lists)
self.dependencies = list(dependencies or [])
self.entry_type_guid = ENTRY_TYPE_GUIDS['project']
if config_platform_overrides:
self.config_platform_overrides = config_platform_overrides
else:
self.config_platform_overrides = {}
self.fixpath_prefix = fixpath_prefix
self.msbuild_toolset = None
def set_dependencies(self, dependencies):
self.dependencies = list(dependencies or [])
def get_guid(self):
if self.guid is None:
# Set GUID from path
# TODO(rspangler): This is fragile.
# 1. We can't just use the project filename sans path, since there could
# be multiple projects with the same base name (for example,
# foo/unittest.vcproj and bar/unittest.vcproj).
# 2. The path needs to be relative to $SOURCE_ROOT, so that the project
# GUID is the same whether it's included from base/base.sln or
# foo/bar/baz/baz.sln.
# 3. The GUID needs to be the same each time this builder is invoked, so
# that we don't need to rebuild the solution when the project changes.
# 4. We should be able to handle pre-built project files by reading the
# GUID from the files.
self.guid = MakeGuid(self.name)
return self.guid
def set_msbuild_toolset(self, msbuild_toolset):
self.msbuild_toolset = msbuild_toolset
#------------------------------------------------------------------------------
class MSVSSolution(object):
"""Visual Studio solution."""
def __init__(self, path, version, entries=None, variants=None,
websiteProperties=True):
"""Initializes the solution.
Args:
path: Path to solution file.
version: Format version to emit.
entries: List of entries in solution. May contain Folder or Project
objects. May be None, if the folder is empty.
variants: List of build variant strings. If none, a default list will
be used.
websiteProperties: Flag to decide if the website properties section
is generated.
"""
self.path = path
self.websiteProperties = websiteProperties
self.version = version
# Copy passed lists (or set to empty lists)
self.entries = list(entries or [])
if variants:
# Copy passed list
self.variants = variants[:]
else:
# Use default
self.variants = ['Debug|Win32', 'Release|Win32']
# TODO(rspangler): Need to be able to handle a mapping of solution config
# to project config. Should we be able to handle variants being a dict,
# or add a separate variant_map variable? If it's a dict, we can't
# guarantee the order of variants since dict keys aren't ordered.
# TODO(rspangler): Automatically write to disk for now; should delay until
# node-evaluation time.
self.Write()
def Write(self, writer=gyp.common.WriteOnDiff):
"""Writes the solution file to disk.
Raises:
IndexError: An entry appears multiple times.
"""
# Walk the entry tree and collect all the folders and projects.
all_entries = set()
entries_to_check = self.entries[:]
while entries_to_check:
e = entries_to_check.pop(0)
# If this entry has been visited, nothing to do.
if e in all_entries:
continue
all_entries.add(e)
# If this is a folder, check its entries too.
if isinstance(e, MSVSFolder):
entries_to_check += e.entries
all_entries = sorted(all_entries)
# Open file and print header
f = writer(self.path)
f.write('Microsoft Visual Studio Solution File, '
'Format Version %s\r\n' % self.version.SolutionVersion())
f.write('# %s\r\n' % self.version.Description())
# Project entries
sln_root = os.path.split(self.path)[0]
for e in all_entries:
relative_path = gyp.common.RelativePath(e.path, sln_root)
# msbuild does not accept an empty folder_name.
# use '.' in case relative_path is empty.
folder_name = relative_path.replace('/', '\\') or '.'
f.write('Project("%s") = "%s", "%s", "%s"\r\n' % (
e.entry_type_guid, # Entry type GUID
e.name, # Folder name
folder_name, # Folder name (again)
e.get_guid(), # Entry GUID
))
# TODO(rspangler): Need a way to configure this stuff
if self.websiteProperties:
f.write('\tProjectSection(WebsiteProperties) = preProject\r\n'
'\t\tDebug.AspNetCompiler.Debug = "True"\r\n'
'\t\tRelease.AspNetCompiler.Debug = "False"\r\n'
'\tEndProjectSection\r\n')
if isinstance(e, MSVSFolder):
if e.items:
f.write('\tProjectSection(SolutionItems) = preProject\r\n')
for i in e.items:
f.write('\t\t%s = %s\r\n' % (i, i))
f.write('\tEndProjectSection\r\n')
if isinstance(e, MSVSProject):
if e.dependencies:
f.write('\tProjectSection(ProjectDependencies) = postProject\r\n')
for d in e.dependencies:
f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid()))
f.write('\tEndProjectSection\r\n')
f.write('EndProject\r\n')
# Global section
f.write('Global\r\n')
# Configurations (variants)
f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n')
for v in self.variants:
f.write('\t\t%s = %s\r\n' % (v, v))
f.write('\tEndGlobalSection\r\n')
# Sort config guids for easier diffing of solution changes.
config_guids = []
config_guids_overrides = {}
for e in all_entries:
if isinstance(e, MSVSProject):
config_guids.append(e.get_guid())
config_guids_overrides[e.get_guid()] = e.config_platform_overrides
config_guids.sort()
f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n')
for g in config_guids:
for v in self.variants:
nv = config_guids_overrides[g].get(v, v)
# Pick which project configuration to build for this solution
# configuration.
f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % (
g, # Project GUID
v, # Solution build configuration
nv, # Project build config for that solution config
))
# Enable project in this solution configuration.
f.write('\t\t%s.%s.Build.0 = %s\r\n' % (
g, # Project GUID
v, # Solution build configuration
nv, # Project build config for that solution config
))
f.write('\tEndGlobalSection\r\n')
# TODO(rspangler): Should be able to configure this stuff too (though I've
# never seen this be any different)
f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n')
f.write('\t\tHideSolutionNode = FALSE\r\n')
f.write('\tEndGlobalSection\r\n')
# Folder mappings
# Omit this section if there are no folders
if any([e.entries for e in all_entries if isinstance(e, MSVSFolder)]):
f.write('\tGlobalSection(NestedProjects) = preSolution\r\n')
for e in all_entries:
if not isinstance(e, MSVSFolder):
continue # Does not apply to projects, only folders
for subentry in e.entries:
f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid()))
f.write('\tEndGlobalSection\r\n')
f.write('EndGlobal\r\n')
f.close()
|
Gorgel/khd_projects | refs/heads/master | khd_projects/projects/templatetags/__init__.py | 3 | __author__ = 'gorgel'
|
murder77/electrum | refs/heads/master | plugins/exchange_rate.py | 1 | from PyQt4.QtGui import *
from PyQt4.QtCore import *
from datetime import datetime
import inspect
import requests
import sys
from threading import Thread
import time
import traceback
from decimal import Decimal
from functools import partial
from electrum.bitcoin import COIN
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
from electrum.util import PrintError, ThreadJob, timestamp_to_datetime
from electrum.util import format_satoshis
from electrum_gui.qt.util import *
from electrum_gui.qt.amountedit import AmountEdit
# See https://en.wikipedia.org/wiki/ISO_4217
CCY_PRECISIONS = {'BHD': 3, 'BIF': 0, 'BYR': 0, 'CLF': 4, 'CLP': 0,
'CVE': 0, 'DJF': 0, 'GNF': 0, 'IQD': 3, 'ISK': 0,
'JOD': 3, 'JPY': 0, 'KMF': 0, 'KRW': 0, 'KWD': 3,
'LYD': 3, 'MGA': 1, 'MRO': 1, 'OMR': 3, 'PYG': 0,
'RWF': 0, 'TND': 3, 'UGX': 0, 'UYI': 0, 'VND': 0,
'VUV': 0, 'XAF': 0, 'XAG': 2, 'XAU': 4, 'XOF': 0,
'XPF': 0}
class ExchangeBase(PrintError):
def __init__(self, sig):
self.history = {}
self.quotes = {}
self.sig = sig
def protocol(self):
return "https"
def get_json(self, site, get_string):
url = "".join([self.protocol(), '://', site, get_string])
response = requests.request('GET', url,
headers={'User-Agent' : 'Electrum'})
return response.json()
def name(self):
return self.__class__.__name__
def update_safe(self, ccy):
try:
self.print_error("getting fx quotes for", ccy)
self.quotes = self.get_rates(ccy)
self.print_error("received fx quotes")
self.sig.emit(SIGNAL('fx_quotes'))
except Exception, e:
self.print_error("failed fx quotes:", e)
def update(self, ccy):
t = Thread(target=self.update_safe, args=(ccy,))
t.setDaemon(True)
t.start()
def get_historical_rates_safe(self, ccy):
try:
self.print_error("requesting fx history for", ccy)
self.history[ccy] = self.historical_rates(ccy)
self.print_error("received fx history for", ccy)
self.sig.emit(SIGNAL("fx_history"))
except Exception, e:
self.print_error("failed fx history:", e)
def get_historical_rates(self, ccy):
result = self.history.get(ccy)
if not result and ccy in self.history_ccys():
t = Thread(target=self.get_historical_rates_safe, args=(ccy,))
t.setDaemon(True)
t.start()
return result
def history_ccys(self):
return []
def historical_rate(self, ccy, d_t):
return self.history.get(ccy, {}).get(d_t.strftime('%Y-%m-%d'))
class BitcoinAverage(ExchangeBase):
def update(self, ccy):
json = self.get_json('api.bitcoinaverage.com', '/ticker/global/all')
return dict([(r, Decimal(json[r]['last']))
for r in json if r != 'timestamp'])
class BitcoinVenezuela(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('api.bitcoinvenezuela.com', '/')
return dict([(r, Decimal(json['BTC'][r]))
for r in json['BTC']])
def protocol(self):
return "http"
def history_ccys(self):
return ['ARS', 'EUR', 'USD', 'VEF']
def historical_rates(self, ccy):
return self.get_json('api.bitcoinvenezuela.com',
"/historical/index.php?coin=BTC")[ccy +'_BTC']
class BTCParalelo(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('btcparalelo.com', '/api/price')
return {'VEF': Decimal(json['price'])}
def protocol(self):
return "http"
class Bitcurex(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('pln.bitcurex.com', '/data/ticker.json')
pln_price = json['last']
return {'PLN': Decimal(pln_price)}
class Bitmarket(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('www.bitmarket.pl', '/json/BTCPLN/ticker.json')
return {'PLN': Decimal(json['last'])}
class BitPay(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('bitpay.com', '/api/rates')
return dict([(r['code'], Decimal(r['rate'])) for r in json])
class BlockchainInfo(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('blockchain.info', '/ticker')
return dict([(r, Decimal(json[r]['15m'])) for r in json])
def name(self):
return "Blockchain"
class BTCChina(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('data.btcchina.com', '/data/ticker')
return {'CNY': Decimal(json['ticker']['last'])}
class CaVirtEx(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('www.cavirtex.com', '/api/CAD/ticker.json')
return {'CAD': Decimal(json['last'])}
class Coinbase(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('coinbase.com',
'/api/v1/currencies/exchange_rates')
return dict([(r[7:].upper(), Decimal(json[r]))
for r in json if r.startswith('btc_to_')])
class CoinDesk(ExchangeBase):
def get_rates(self, ccy):
dicts = self.get_json('api.coindesk.com',
'/v1/bpi/supported-currencies.json')
json = self.get_json('api.coindesk.com',
'/v1/bpi/currentprice/%s.json' % ccy)
ccys = [d['currency'] for d in dicts]
result = dict.fromkeys(ccys)
result[ccy] = Decimal(json['bpi'][ccy]['rate_float'])
return result
def history_starts(self):
return { 'USD': '2012-11-30' }
def history_ccys(self):
return self.history_starts().keys()
def historical_rates(self, ccy):
start = self.history_starts()[ccy]
end = datetime.today().strftime('%Y-%m-%d')
# Note ?currency and ?index don't work as documented. Sigh.
query = ('/v1/bpi/historical/close.json?start=%s&end=%s'
% (start, end))
json = self.get_json('api.coindesk.com', query)
return json['bpi']
class itBit(ExchangeBase):
def get_rates(self, ccy):
ccys = ['USD', 'EUR', 'SGD']
json = self.get_json('api.itbit.com', '/v1/markets/XBT%s/ticker' % ccy)
result = dict.fromkeys(ccys)
if ccy in ccys:
result[ccy] = Decimal(json['lastPrice'])
return result
class LocalBitcoins(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('localbitcoins.com',
'/bitcoinaverage/ticker-all-currencies/')
return dict([(r, Decimal(json[r]['rates']['last'])) for r in json])
class Winkdex(ExchangeBase):
def get_rates(self, ccy):
json = self.get_json('winkdex.com', '/api/v0/price')
return {'USD': Decimal(json['price'] / 100.0)}
def history_ccys(self):
return ['USD']
def historical_rates(self, ccy):
json = self.get_json('winkdex.com',
"/api/v0/series?start_time=1342915200")
history = json['series'][0]['results']
return dict([(h['timestamp'][:10], h['price'] / 100.0)
for h in history])
class Plugin(BasePlugin, ThreadJob):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
# Signal object first
self.sig = QObject()
self.sig.connect(self.sig, SIGNAL('fx_quotes'), self.on_fx_quotes)
self.sig.connect(self.sig, SIGNAL('fx_history'), self.on_fx_history)
self.ccy = self.config_ccy()
self.history_used_spot = False
self.ccy_combo = None
self.hist_checkbox = None
self.windows = dict()
is_exchange = lambda obj: (inspect.isclass(obj)
and issubclass(obj, ExchangeBase)
and obj != ExchangeBase)
self.exchanges = dict(inspect.getmembers(sys.modules[__name__],
is_exchange))
self.set_exchange(self.config_exchange())
def ccy_amount_str(self, amount, commas):
prec = CCY_PRECISIONS.get(self.ccy, 2)
fmt_str = "{:%s.%df}" % ("," if commas else "", max(0, prec))
return fmt_str.format(round(amount, prec))
def thread_jobs(self):
return [self]
def run(self):
# This runs from the network thread which catches exceptions
if self.windows and self.timeout <= time.time():
self.timeout = time.time() + 150
self.exchange.update(self.ccy)
def config_ccy(self):
'''Use when dynamic fetching is needed'''
return self.config.get("currency", "EUR")
def config_exchange(self):
return self.config.get('use_exchange', 'Blockchain')
def config_history(self):
return self.config.get('history_rates', 'unchecked') != 'unchecked'
def show_history(self):
return self.config_history() and self.exchange.history_ccys()
def set_exchange(self, name):
class_ = self.exchanges.get(name) or self.exchanges.values()[0]
name = class_.__name__
self.print_error("using exchange", name)
if self.config_exchange() != name:
self.config.set_key('use_exchange', name, True)
self.exchange = class_(self.sig)
# A new exchange means new fx quotes, initially empty. Force
# a quote refresh
self.timeout = 0
self.get_historical_rates()
self.on_fx_quotes()
def update_status_bars(self):
'''Update status bar fiat balance in all windows'''
for window in self.windows:
window.update_status()
def on_new_window(self, window):
# Additional send and receive edit boxes
send_e = AmountEdit(self.config_ccy)
window.send_grid.addWidget(send_e, 4, 2, Qt.AlignLeft)
window.amount_e.frozen.connect(
lambda: send_e.setFrozen(window.amount_e.isReadOnly()))
receive_e = AmountEdit(self.config_ccy)
window.receive_grid.addWidget(receive_e, 2, 2, Qt.AlignLeft)
self.windows[window] = {'edits': (send_e, receive_e),
'last_edited': {}}
self.connect_fields(window, window.amount_e, send_e, window.fee_e)
self.connect_fields(window, window.receive_amount_e, receive_e, None)
window.history_list.refresh_headers()
window.update_status()
def connect_fields(self, window, btc_e, fiat_e, fee_e):
last_edited = self.windows[window]['last_edited']
def edit_changed(edit):
edit.setStyleSheet(BLACK_FG)
last_edited[(fiat_e, btc_e)] = edit
amount = edit.get_amount()
rate = self.exchange_rate()
if rate is None or amount is None:
if edit is fiat_e:
btc_e.setText("")
if fee_e:
fee_e.setText("")
else:
fiat_e.setText("")
else:
if edit is fiat_e:
btc_e.setAmount(int(amount / Decimal(rate) * COIN))
if fee_e: window.update_fee()
btc_e.setStyleSheet(BLUE_FG)
else:
fiat_e.setText(self.ccy_amount_str(
amount * Decimal(rate) / COIN, False))
fiat_e.setStyleSheet(BLUE_FG)
fiat_e.textEdited.connect(partial(edit_changed, fiat_e))
btc_e.textEdited.connect(partial(edit_changed, btc_e))
last_edited[(fiat_e, btc_e)] = btc_e
@hook
def do_clear(self, window):
self.windows[window]['edits'][0].setText('')
def on_close_window(self, window):
self.windows.pop(window)
def close(self):
# Get rid of hooks before updating status bars.
BasePlugin.close(self)
self.update_status_bars()
self.refresh_headers()
for window, data in self.windows.items():
for edit in data['edits']:
edit.hide()
window.update_status()
def refresh_headers(self):
for window in self.windows:
window.history_list.refresh_headers()
def on_fx_history(self):
'''Called when historical fx quotes are updated'''
for window in self.windows:
window.history_list.update()
def on_fx_quotes(self):
'''Called when fresh spot fx quotes come in'''
self.update_status_bars()
self.populate_ccy_combo()
# Refresh edits with the new rate
for window, data in self.windows.items():
for edit in data['last_edited'].values():
edit.textEdited.emit(edit.text())
# History tab needs updating if it used spot
if self.history_used_spot:
self.on_fx_history()
def on_ccy_combo_change(self):
'''Called when the chosen currency changes'''
ccy = str(self.ccy_combo.currentText())
if ccy and ccy != self.ccy:
self.ccy = ccy
self.config.set_key('currency', ccy, True)
self.update_status_bars()
self.get_historical_rates() # Because self.ccy changes
self.hist_checkbox_update()
def hist_checkbox_update(self):
if self.hist_checkbox:
self.hist_checkbox.setEnabled(self.ccy in self.exchange.history_ccys())
self.hist_checkbox.setChecked(self.config_history())
def populate_ccy_combo(self):
# There should be at most one instance of the settings dialog
combo = self.ccy_combo
# NOTE: bool(combo) is False if it is empty. Nuts.
if combo is not None:
combo.blockSignals(True)
combo.clear()
combo.addItems(sorted(self.exchange.quotes.keys()))
combo.blockSignals(False)
combo.setCurrentIndex(combo.findText(self.ccy))
def exchange_rate(self):
'''Returns None, or the exchange rate as a Decimal'''
rate = self.exchange.quotes.get(self.ccy)
if rate:
return Decimal(rate)
@hook
def format_amount_and_units(self, btc_balance):
rate = self.exchange_rate()
return '' if rate is None else " (%s %s)" % (self.value_str(btc_balance, rate), self.ccy)
@hook
def get_fiat_status_text(self, btc_balance, result):
# return status as: (1.23 USD) 1 BTC~123.45 USD
rate = self.exchange_rate()
if rate is None:
text = _(" (No FX rate available)")
else:
text = "1 BTC~%s %s" % (self.value_str(COIN, rate), self.ccy)
result['text'] = text
def get_historical_rates(self):
if self.show_history():
self.exchange.get_historical_rates(self.ccy)
def requires_settings(self):
return True
def value_str(self, satoshis, rate):
if satoshis is None: # Can happen with incomplete history
return _("Unknown")
if rate:
value = Decimal(satoshis) / COIN * Decimal(rate)
return "%s" % (self.ccy_amount_str(value, True))
return _("No data")
def historical_value_str(self, satoshis, d_t):
rate = self.exchange.historical_rate(self.ccy, d_t)
# Frequently there is no rate for today, until tomorrow :)
# Use spot quotes in that case
if rate is None and (datetime.today().date() - d_t.date()).days <= 2:
rate = self.exchange.quotes.get(self.ccy)
self.history_used_spot = True
return self.value_str(satoshis, rate)
@hook
def history_tab_headers(self, headers):
if self.show_history():
headers.extend(['%s '%self.ccy + _('Amount'), '%s '%self.ccy + _('Balance')])
@hook
def history_tab_update_begin(self):
self.history_used_spot = False
@hook
def history_tab_update(self, tx, entry):
if not self.show_history():
return
tx_hash, conf, value, timestamp, balance = tx
if conf <= 0:
date = datetime.today()
else:
date = timestamp_to_datetime(timestamp)
for amount in [value, balance]:
text = self.historical_value_str(amount, date)
entry.append(text)
def settings_widget(self, window):
return EnterButton(_('Settings'), self.settings_dialog)
def settings_dialog(self):
d = QDialog()
d.setWindowTitle("Settings")
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
layout.addWidget(QLabel(_('Currency: ')), 1, 0)
layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
# Currency list
self.ccy_combo = QComboBox()
self.ccy_combo.currentIndexChanged.connect(self.on_ccy_combo_change)
self.populate_ccy_combo()
def on_change_ex(idx):
exchange = str(combo_ex.currentText())
if exchange != self.exchange.name():
self.set_exchange(exchange)
self.hist_checkbox_update()
def on_change_hist(checked):
if checked:
self.config.set_key('history_rates', 'checked')
self.get_historical_rates()
else:
self.config.set_key('history_rates', 'unchecked')
self.refresh_headers()
def ok_clicked():
self.timeout = 0
self.ccy_combo = None
d.accept()
combo_ex = QComboBox()
combo_ex.addItems(sorted(self.exchanges.keys()))
combo_ex.setCurrentIndex(combo_ex.findText(self.config_exchange()))
combo_ex.currentIndexChanged.connect(on_change_ex)
self.hist_checkbox = QCheckBox()
self.hist_checkbox.stateChanged.connect(on_change_hist)
self.hist_checkbox_update()
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(lambda: ok_clicked())
layout.addWidget(self.ccy_combo,1,1)
layout.addWidget(combo_ex,0,1)
layout.addWidget(self.hist_checkbox,2,1)
layout.addWidget(ok_button,3,1)
return d.exec_()
|
jpulec/hardt | refs/heads/master | hardt/apps/playlists/__init__.py | 12133432 | |
wdurhamh/statsmodels | refs/heads/master | statsmodels/tsa/tests/__init__.py | 12133432 | |
amaozhao/basecms | refs/heads/master | classytags/exceptions.py | 14 | from django.template import TemplateSyntaxError
__all__ = ['ArgumentRequiredError', 'InvalidFlag', 'BreakpointExpected',
'TooManyArguments']
class BaseError(TemplateSyntaxError):
template = ''
def __str__(self): # pragma: no cover
return self.template % self.__dict__
class ArgumentRequiredError(BaseError):
template = "The tag '%(tagname)s' requires the '%(argname)s' argument."
def __init__(self, argument, tagname):
self.argument = argument
self.tagname = tagname
self.argname = self.argument.name
class InvalidFlag(BaseError):
template = ("The flag '%(argname)s' for the tag '%(tagname)s' must be one "
"of %(allowed_values)s, but got '%(actual_value)s'")
def __init__(self, argname, actual_value, allowed_values, tagname):
self.argname = argname
self.tagname = tagname
self.actual_value = actual_value
self.allowed_values = allowed_values
class BreakpointExpected(BaseError):
template = ("Expected one of the following breakpoints: %(breakpoints)s "
"in %(tagname)s, got '%(got)s' instead.")
def __init__(self, tagname, breakpoints, got):
self.breakpoints = ', '.join(["'%s'" % bp for bp in breakpoints])
self.tagname = tagname
self.got = got
class TrailingBreakpoint(BaseError):
template = ("Tag %(tagname)s ends in trailing breakpoint '%(breakpoint)s' without an argument following.")
def __init__(self, tagname, breakpoint):
self.tagname = tagname
self.breakpoint = breakpoint
class TooManyArguments(BaseError):
template = "The tag '%(tagname)s' got too many arguments: %(extra)s"
def __init__(self, tagname, extra):
self.tagname = tagname
self.extra = ', '.join(["'%s'" % e for e in extra])
class TemplateSyntaxWarning(Warning):
"""
Used for variable cleaning TemplateSyntaxErrors when in non-debug-mode.
"""
|
hugs/selenium | refs/heads/master | selenium/src/py/lib/docutils/languages/it.py | 5 | # Author: Nicola Larosa
# Contact: docutils@tekNico.net
# Revision: $Revision: 2944 $
# Date: $Date: 2005-01-20 13:11:50 +0100 (Thu, 20 Jan 2005) $
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Italian-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
'author': 'Autore',
'authors': 'Autori',
'organization': 'Organizzazione',
'address': 'Indirizzo',
'contact': 'Contatti',
'version': 'Versione',
'revision': 'Revisione',
'status': 'Status',
'date': 'Data',
'copyright': 'Copyright',
'dedication': 'Dedica',
'abstract': 'Riassunto',
'attention': 'Attenzione!',
'caution': 'Cautela!',
'danger': '!PERICOLO!',
'error': 'Errore',
'hint': 'Suggerimento',
'important': 'Importante',
'note': 'Nota',
'tip': 'Consiglio',
'warning': 'Avvertenza',
'contents': 'Indice'}
"""Mapping of node class name to label text."""
bibliographic_fields = {
'autore': 'author',
'autori': 'authors',
'organizzazione': 'organization',
'indirizzo': 'address',
'contatto': 'contact',
'versione': 'version',
'revisione': 'revision',
'status': 'status',
'data': 'date',
'copyright': 'copyright',
'dedica': 'dedication',
'riassunto': 'abstract'}
"""Italian (lowcased) to canonical name mapping for bibliographic fields."""
author_separators = [';', ',']
"""List of separator strings for the 'Authors' bibliographic field. Tried in
order."""
|
indykish/servo | refs/heads/master | tests/wpt/web-platform-tests/XMLHttpRequest/resources/content.py | 227 | def main(request, response):
response_ctype = ''
if "response_charset_label" in request.GET:
response_ctype = ";charset=" + request.GET.first("response_charset_label")
headers = [("Content-type", "text/plain" + response_ctype),
("X-Request-Method", request.method),
("X-Request-Query", request.url_parts.query if request.url_parts.query else "NO"),
("X-Request-Content-Length", request.headers.get("Content-Length", "NO")),
("X-Request-Content-Type", request.headers.get("Content-Type", "NO"))]
if "content" in request.GET:
content = request.GET.first("content")
else:
content = request.body
return headers, content
|
mancoast/CPythonPyc_test | refs/heads/master | cpython/270_test_userlist.py | 137 | # Check every path through every method of UserList
from UserList import UserList
from test import test_support, list_tests
class UserListTest(list_tests.CommonTest):
type2test = UserList
def test_getslice(self):
super(UserListTest, self).test_getslice()
l = [0, 1, 2, 3, 4]
u = self.type2test(l)
for i in range(-3, 6):
self.assertEqual(u[:i], l[:i])
self.assertEqual(u[i:], l[i:])
for j in xrange(-3, 6):
self.assertEqual(u[i:j], l[i:j])
def test_add_specials(self):
u = UserList("spam")
u2 = u + "eggs"
self.assertEqual(u2, list("spameggs"))
def test_radd_specials(self):
u = UserList("eggs")
u2 = "spam" + u
self.assertEqual(u2, list("spameggs"))
u2 = u.__radd__(UserList("spam"))
self.assertEqual(u2, list("spameggs"))
def test_iadd(self):
super(UserListTest, self).test_iadd()
u = [0, 1]
u += UserList([0, 1])
self.assertEqual(u, [0, 1, 0, 1])
def test_mixedcmp(self):
u = self.type2test([0, 1])
self.assertEqual(u, [0, 1])
self.assertNotEqual(u, [0])
self.assertNotEqual(u, [0, 2])
def test_mixedadd(self):
u = self.type2test([0, 1])
self.assertEqual(u + [], u)
self.assertEqual(u + [2], [0, 1, 2])
def test_getitemoverwriteiter(self):
# Verify that __getitem__ overrides *are* recognized by __iter__
class T(self.type2test):
def __getitem__(self, key):
return str(key) + '!!!'
self.assertEqual(iter(T((1,2))).next(), "0!!!")
def test_main():
with test_support.check_py3k_warnings(
(".+__(get|set|del)slice__ has been removed", DeprecationWarning)):
test_support.run_unittest(UserListTest)
if __name__ == "__main__":
test_main()
|
mathemage/h2o-3 | refs/heads/master | h2o-py/h2o/cross_validation.py | 6 | # -*- encoding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from h2o.utils.compatibility import * # NOQA
class H2OPartitionIterator(object):
def __init__(self, n):
if abs(n - int(n)) >= 1e-15: raise ValueError("n must be an integer")
self.n = int(n)
self.masks = None
def __iter__(self):
for test_mask in self._test_masks():
yield 1 - test_mask, test_mask
def _test_masks(self):
raise NotImplementedError()
class H2OKFold(H2OPartitionIterator):
def __init__(self, fr, n_folds=3, seed=-1):
H2OPartitionIterator.__init__(self, len(fr))
self.n_folds = n_folds
self.fr = fr
self.seed = seed
self.fold_assignments = None
def __len__(self):
return self.n_folds
def _test_masks(self):
if self.fold_assignments is None:
self._assign_folds()
if self.masks is None: self.masks = [i == self.fold_assignments for i in range(self.n_folds)]
return self.masks
def _assign_folds(self):
if self.fr is None: raise ValueError("No H2OFrame available for computing folds.")
self.fold_assignments = self.fr.kfold_column(self.n_folds, self.seed)
self.fr = None
class H2OStratifiedKFold(H2OPartitionIterator):
def __init__(self, y, n_folds=3, seed=-1):
H2OPartitionIterator.__init__(self, len(y))
self.n_folds = n_folds
self.y = y
self.seed = seed
self.fold_assignments = None
def __len__(self):
return self.n_folds
def _test_masks(self):
if self.fold_assignments is None:
self._assign_folds()
if self.masks is None: self.masks = [i == self.fold_assignments for i in range(self.n_folds)]
return self.masks
def _assign_folds(self):
if self.y is None: raise ValueError("No y available for computing stratified folds.")
self.fold_assignments = self.y.stratified_kfold_column(self.n_folds, self.seed)
self.y = None
|
iver333/phantomjs | refs/heads/master | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/haslanded_unittest.py | 124 | # Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest2 as unittest
import subprocess
from webkitpy.tool.steps.haslanded import HasLanded
class HasLandedTest(unittest.TestCase):
maxDiff = None
@unittest.skipUnless(subprocess.call('which interdiff', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0, "requires interdiff")
def test_run(self):
# These patches require trailing whitespace to remain valid patches.
diff1 = """\
Index: a.py
===================================================================
--- a.py
+++ a.py
@@ -1,3 +1,5 @@
A
B
C
+D
+E
Index: b.py
===================================================================
--- b.py 2013-01-21 15:20:59.693887185 +1100
+++ b.py 2013-01-21 15:22:24.382555711 +1100
@@ -1,3 +1,5 @@
1
2
3
+4
+5
"""
diff1_add_line = """\
Index: a.py
===================================================================
--- a.py
+++ a.py
@@ -1,3 +1,6 @@
A
B
C
+D
+E
+F
Index: b.py
===================================================================
--- b.py
+++ b.py
@@ -1,3 +1,5 @@
1
2
3
+4
+5
"""
diff1_remove_line = """\
Index: a.py
===================================================================
--- a.py
+++ a.py
@@ -1,3 +1,4 @@
A
B
C
+D
Index: b.py
===================================================================
--- b.py
+++ b.py
@@ -1,3 +1,5 @@
1
2
3
+4
+5
"""
diff1_add_file = diff1 + """\
Index: c.py
===================================================================
--- c.py
+++ c.py
@@ -1,3 +1,5 @@
1
2
3
+4
+5
"""
diff1_remove_file = """\
Index: a.py
===================================================================
--- a.py
+++ a.py
@@ -1,3 +1,5 @@
A
B
C
+D
+E
"""
self.assertMultiLineEqual(
HasLanded.diff_diff(diff1, diff1_add_line, '', 'add-line'),
"""\
diff -u a.py a.py
--- a.py
+++ a.py
@@ -5,0 +6 @@
+F
""")
self.assertMultiLineEqual(
HasLanded.diff_diff(diff1, diff1_remove_line, '', 'remove-line'),
"""\
diff -u a.py a.py
--- a.py
+++ a.py
@@ -5 +4,0 @@
-E
""")
self.assertMultiLineEqual(
HasLanded.diff_diff(diff1, diff1_add_file, '', 'add-file'),
"""\
only in patch2:
unchanged:
--- c.py
+++ c.py
@@ -1,3 +1,5 @@
1
2
3
+4
+5
""")
self.assertMultiLineEqual(
HasLanded.diff_diff(diff1, diff1_remove_file, '', 'remove-file'),
"""\
reverted:
--- b.py 2013-01-21 15:22:24.382555711 +1100
+++ b.py 2013-01-21 15:20:59.693887185 +1100
@@ -1,5 +1,3 @@
1
2
3
-4
-5
""")
def test_convert_to_svn_and_strip_change_log(self):
# These patches require trailing whitespace to remain valid patches.
testbefore1 = HasLanded.convert_to_svn("""\
diff --git a/Tools/ChangeLog b/Tools/ChangeLog
index 219ba72..0390b73 100644
--- a/Tools/ChangeLog
+++ b/Tools/ChangeLog
@@ -1,3 +1,32 @@
+2013-01-17 Tim 'mithro' Ansell <mithro@mithis.com>
+
+ Adding "has-landed" command to webkit-patch which allows a person to
+ Reviewed by NOBODY (OOPS!).
+
2013-01-20 Tim 'mithro' Ansell <mithro@mithis.com>
Extend diff_parser to support the --full-index output.
diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
index 4bf8ec6..3a128cb 100644
--- a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
+++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
""")
testafter1 = HasLanded.convert_to_svn("""\
diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
index 4bf8ec6..3a128cb 100644
--- a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
+++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
diff --git a/Tools/ChangeLog b/Tools/ChangeLog
index 219ba72..0390b73 100644
--- a/Tools/ChangeLog
+++ b/Tools/ChangeLog
@@ -1,3 +1,32 @@
+2013-01-17 Tim 'mithro' Ansell <mithro@mithis.com>
+
+ Adding "has-landed" command to webkit-patch which allows a person to
+ Reviewed by NOBODY (OOPS!).
+
2013-01-20 Tim 'mithro' Ansell <mithro@mithis.com>
Extend diff_parser to support the --full-index output.
""")
testexpected1 = """\
Index: Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
===================================================================
--- Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
+++ Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
"""
testmiddle1 = HasLanded.convert_to_svn("""\
diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
index 4bf8ec6..3a128cb 100644
--- a/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
+++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
diff --git a/ChangeLog b/ChangeLog
index 219ba72..0390b73 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,32 @@
+2013-01-17 Tim 'mithro' Ansell <mithro@mithis.com>
+
+ Adding "has-landed" command to webkit-patch which allows a person to
+ Reviewed by NOBODY (OOPS!).
+
2013-01-20 Tim 'mithro' Ansell <mithro@mithis.com>
Extend diff_parser to support the --full-index output.
diff --git a/Tools/Scripts/webkitpy/common/other.py b/Tools/Scripts/webkitpy/common/other.py
index 4bf8ec6..3a128cb 100644
--- a/Tools/Scripts/webkitpy/common/other.py
+++ b/Tools/Scripts/webkitpy/common/other.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
""")
testexpected2 = """\
Index: Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
===================================================================
--- Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
+++ Tools/Scripts/webkitpy/common/net/bugzilla/bug.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
Index: Tools/Scripts/webkitpy/common/other.py
===================================================================
--- Tools/Scripts/webkitpy/common/other.py
+++ Tools/Scripts/webkitpy/common/other.py
@@ -28,6 +28,8 @@
+import re
+
from .attachment import Attachment
"""
self.assertMultiLineEqual(testexpected1, HasLanded.strip_change_log(testbefore1))
self.assertMultiLineEqual(testexpected1, HasLanded.strip_change_log(testafter1))
self.assertMultiLineEqual(testexpected2, HasLanded.strip_change_log(testmiddle1))
|
jaxkodex/odoo | refs/heads/8.0 | addons/auth_oauth/controllers/main.py | 205 | import functools
import logging
import simplejson
import urlparse
import werkzeug.utils
from werkzeug.exceptions import BadRequest
import openerp
from openerp import SUPERUSER_ID
from openerp import http
from openerp.http import request
from openerp.addons.web.controllers.main import db_monodb, ensure_db, set_cookie_and_redirect, login_and_redirect
from openerp.addons.auth_signup.controllers.main import AuthSignupHome as Home
from openerp.modules.registry import RegistryManager
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# helpers
#----------------------------------------------------------
def fragment_to_query_string(func):
@functools.wraps(func)
def wrapper(self, *a, **kw):
kw.pop('debug', False)
if not kw:
return """<html><head><script>
var l = window.location;
var q = l.hash.substring(1);
var r = l.pathname + l.search;
if(q.length !== 0) {
var s = l.search ? (l.search === '?' ? '' : '&') : '?';
r = l.pathname + l.search + s + q;
}
if (r == l.pathname) {
r = '/';
}
window.location = r;
</script></head><body></body></html>"""
return func(self, *a, **kw)
return wrapper
#----------------------------------------------------------
# Controller
#----------------------------------------------------------
class OAuthLogin(Home):
def list_providers(self):
try:
provider_obj = request.registry.get('auth.oauth.provider')
providers = provider_obj.search_read(request.cr, SUPERUSER_ID, [('enabled', '=', True), ('auth_endpoint', '!=', False), ('validation_endpoint', '!=', False)])
# TODO in forwardport: remove conditions on 'auth_endpoint' and 'validation_endpoint' when these fields will be 'required' in model
except Exception:
providers = []
for provider in providers:
return_url = request.httprequest.url_root + 'auth_oauth/signin'
state = self.get_state(provider)
params = dict(
debug=request.debug,
response_type='token',
client_id=provider['client_id'],
redirect_uri=return_url,
scope=provider['scope'],
state=simplejson.dumps(state),
)
provider['auth_link'] = provider['auth_endpoint'] + '?' + werkzeug.url_encode(params)
return providers
def get_state(self, provider):
redirect = request.params.get('redirect') or 'web'
if not redirect.startswith(('//', 'http://', 'https://')):
redirect = '%s%s' % (request.httprequest.url_root, redirect[1:] if redirect[0] == '/' else redirect)
state = dict(
d=request.session.db,
p=provider['id'],
r=werkzeug.url_quote_plus(redirect),
)
token = request.params.get('token')
if token:
state['t'] = token
return state
@http.route()
def web_login(self, *args, **kw):
ensure_db()
if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'):
# Redirect if already logged in and redirect param is present
return http.redirect_with_hash(request.params.get('redirect'))
providers = self.list_providers()
response = super(OAuthLogin, self).web_login(*args, **kw)
if response.is_qweb:
error = request.params.get('oauth_error')
if error == '1':
error = _("Sign up is not allowed on this database.")
elif error == '2':
error = _("Access Denied")
elif error == '3':
error = _("You do not have access to this database or your invitation has expired. Please ask for an invitation and be sure to follow the link in your invitation email.")
else:
error = None
response.qcontext['providers'] = providers
if error:
response.qcontext['error'] = error
return response
@http.route()
def web_auth_signup(self, *args, **kw):
providers = self.list_providers()
if len(providers) == 1:
werkzeug.exceptions.abort(werkzeug.utils.redirect(providers[0]['auth_link'], 303))
response = super(OAuthLogin, self).web_auth_signup(*args, **kw)
response.qcontext.update(providers=providers)
return response
@http.route()
def web_auth_reset_password(self, *args, **kw):
providers = self.list_providers()
if len(providers) == 1:
werkzeug.exceptions.abort(werkzeug.utils.redirect(providers[0]['auth_link'], 303))
response = super(OAuthLogin, self).web_auth_reset_password(*args, **kw)
response.qcontext.update(providers=providers)
return response
class OAuthController(http.Controller):
@http.route('/auth_oauth/signin', type='http', auth='none')
@fragment_to_query_string
def signin(self, **kw):
state = simplejson.loads(kw['state'])
dbname = state['d']
provider = state['p']
context = state.get('c', {})
registry = RegistryManager.get(dbname)
with registry.cursor() as cr:
try:
u = registry.get('res.users')
credentials = u.auth_oauth(cr, SUPERUSER_ID, provider, kw, context=context)
cr.commit()
action = state.get('a')
menu = state.get('m')
redirect = werkzeug.url_unquote_plus(state['r']) if state.get('r') else False
url = '/web'
if redirect:
url = redirect
elif action:
url = '/web#action=%s' % action
elif menu:
url = '/web#menu_id=%s' % menu
return login_and_redirect(*credentials, redirect_url=url)
except AttributeError:
# auth_signup is not installed
_logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,))
url = "/web/login?oauth_error=1"
except openerp.exceptions.AccessDenied:
# oauth credentials not valid, user could be on a temporary session
_logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
url = "/web/login?oauth_error=3"
redirect = werkzeug.utils.redirect(url, 303)
redirect.autocorrect_location_header = False
return redirect
except Exception, e:
# signup error
_logger.exception("OAuth2: %s" % str(e))
url = "/web/login?oauth_error=2"
return set_cookie_and_redirect(url)
@http.route('/auth_oauth/oea', type='http', auth='none')
def oea(self, **kw):
"""login user via Odoo Account provider"""
dbname = kw.pop('db', None)
if not dbname:
dbname = db_monodb()
if not dbname:
return BadRequest()
registry = RegistryManager.get(dbname)
with registry.cursor() as cr:
IMD = registry['ir.model.data']
try:
model, provider_id = IMD.get_object_reference(cr, SUPERUSER_ID, 'auth_oauth', 'provider_openerp')
except ValueError:
return set_cookie_and_redirect('/web?db=%s' % dbname)
assert model == 'auth.oauth.provider'
state = {
'd': dbname,
'p': provider_id,
'c': {'no_user_creation': True},
}
kw['state'] = simplejson.dumps(state)
return self.signin(**kw)
# vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4:
|
zlsun/XX-Net | refs/heads/master | code/default/python27/1.0/lib/Cookie.py | 24 | ####
# Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software
# and its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Timothy O'Malley not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
####
#
# Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp
# by Timothy O'Malley <timo@alum.mit.edu>
#
# Cookie.py is a Python module for the handling of HTTP
# cookies as a Python dictionary. See RFC 2109 for more
# information on cookies.
#
# The original idea to treat Cookies as a dictionary came from
# Dave Mitchell (davem@magnet.com) in 1995, when he released the
# first version of nscookie.py.
#
####
r"""
Here's a sample session to show how to use this module.
At the moment, this is the only documentation.
The Basics
----------
Importing is easy..
>>> import Cookie
Most of the time you start by creating a cookie. Cookies come in
three flavors, each with slightly different encoding semantics, but
more on that later.
>>> C = Cookie.SimpleCookie()
>>> C = Cookie.SerialCookie()
>>> C = Cookie.SmartCookie()
[Note: Long-time users of Cookie.py will remember using
Cookie.Cookie() to create a Cookie object. Although deprecated, it
is still supported by the code. See the Backward Compatibility notes
for more information.]
Once you've created your Cookie, you can add values just as if it were
a dictionary.
>>> C = Cookie.SmartCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> C.output()
'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'
Notice that the printable representation of a Cookie is the
appropriate format for a Set-Cookie: header. This is the
default behavior. You can change the header and printed
attributes by using the .output() function
>>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print C.output(header="Cookie:")
Cookie: rocky=road; Path=/cookie
>>> print C.output(attrs=[], header="Cookie:")
Cookie: rocky=road
The load() method of a Cookie extracts cookies from a string. In a
CGI script, you would use this method to extract the cookies from the
HTTP_COOKIE environment variable.
>>> C = Cookie.SmartCookie()
>>> C.load("chips=ahoy; vienna=finger")
>>> C.output()
'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'
The load() method is darn-tootin smart about identifying cookies
within a string. Escaped quotation marks, nested semicolons, and other
such trickeries do not confuse it.
>>> C = Cookie.SmartCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print C
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Each element of the Cookie also supports all of the RFC 2109
Cookie attributes. Here's an example which sets the Path
attribute.
>>> C = Cookie.SmartCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print C
Set-Cookie: oreo=doublestuff; Path=/
Each dictionary element has a 'value' attribute, which gives you
back the value associated with the key.
>>> C = Cookie.SmartCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
A Bit More Advanced
-------------------
As mentioned before, there are three different flavors of Cookie
objects, each with different encoding/decoding semantics. This
section briefly discusses the differences.
SimpleCookie
The SimpleCookie expects that all values should be standard strings.
Just to be sure, SimpleCookie invokes the str() builtin to convert
the value to a string, when the values are set dictionary-style.
>>> C = Cookie.SimpleCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> C.output()
'Set-Cookie: number=7\r\nSet-Cookie: string=seven'
SerialCookie
The SerialCookie expects that all values should be serialized using
cPickle (or pickle, if cPickle isn't available). As a result of
serializing, SerialCookie can save almost any Python object to a
value, and recover the exact same object when the cookie has been
returned. (SerialCookie can yield some strange-looking cookie
values, however.)
>>> C = Cookie.SerialCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
7
>>> C["string"].value
'seven'
>>> C.output()
'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string="S\'seven\'\\012p1\\012."'
Be warned, however, if SerialCookie cannot de-serialize a value (because
it isn't a valid pickle'd object), IT WILL RAISE AN EXCEPTION.
SmartCookie
The SmartCookie combines aspects of each of the other two flavors.
When setting a value in a dictionary-fashion, the SmartCookie will
serialize (ala cPickle) the value *if and only if* it isn't a
Python string. String objects are *not* serialized. Similarly,
when the load() method parses out values, it attempts to de-serialize
the value. If it fails, then it fallsback to treating the value
as a string.
>>> C = Cookie.SmartCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
7
>>> C["string"].value
'seven'
>>> C.output()
'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string=seven'
Backwards Compatibility
-----------------------
In order to keep compatibility with earlier versions of Cookie.py,
it is still possible to use Cookie.Cookie() to create a Cookie. In
fact, this simply returns a SmartCookie.
>>> C = Cookie.Cookie()
>>> print C.__class__.__name__
SmartCookie
Finis.
""" #"
# ^
# |----helps out font-lock
#
# Import our required modules
#
import string
try:
from cPickle import dumps, loads
except ImportError:
from pickle import dumps, loads
import re, warnings
__all__ = ["CookieError","BaseCookie","SimpleCookie","SerialCookie",
"SmartCookie","Cookie"]
_nulljoin = ''.join
_semispacejoin = '; '.join
_spacejoin = ' '.join
#
# Define an exception visible to External modules
#
class CookieError(Exception):
pass
# These quoting routines conform to the RFC2109 specification, which in
# turn references the character definitions from RFC2068. They provide
# a two-way quoting algorithm. Any non-text character is translated
# into a 4 character sequence: a forward-slash followed by the
# three-digit octal equivalent of the character. Any '\' or '"' is
# quoted with a preceding '\' slash.
#
# These are taken from RFC2068 and RFC2109.
# _LegalChars is the list of chars which don't require "'s
# _Translator hash-table for fast quoting
#
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~"
_Translator = {
'\000' : '\\000', '\001' : '\\001', '\002' : '\\002',
'\003' : '\\003', '\004' : '\\004', '\005' : '\\005',
'\006' : '\\006', '\007' : '\\007', '\010' : '\\010',
'\011' : '\\011', '\012' : '\\012', '\013' : '\\013',
'\014' : '\\014', '\015' : '\\015', '\016' : '\\016',
'\017' : '\\017', '\020' : '\\020', '\021' : '\\021',
'\022' : '\\022', '\023' : '\\023', '\024' : '\\024',
'\025' : '\\025', '\026' : '\\026', '\027' : '\\027',
'\030' : '\\030', '\031' : '\\031', '\032' : '\\032',
'\033' : '\\033', '\034' : '\\034', '\035' : '\\035',
'\036' : '\\036', '\037' : '\\037',
# Because of the way browsers really handle cookies (as opposed
# to what the RFC says) we also encode , and ;
',' : '\\054', ';' : '\\073',
'"' : '\\"', '\\' : '\\\\',
'\177' : '\\177', '\200' : '\\200', '\201' : '\\201',
'\202' : '\\202', '\203' : '\\203', '\204' : '\\204',
'\205' : '\\205', '\206' : '\\206', '\207' : '\\207',
'\210' : '\\210', '\211' : '\\211', '\212' : '\\212',
'\213' : '\\213', '\214' : '\\214', '\215' : '\\215',
'\216' : '\\216', '\217' : '\\217', '\220' : '\\220',
'\221' : '\\221', '\222' : '\\222', '\223' : '\\223',
'\224' : '\\224', '\225' : '\\225', '\226' : '\\226',
'\227' : '\\227', '\230' : '\\230', '\231' : '\\231',
'\232' : '\\232', '\233' : '\\233', '\234' : '\\234',
'\235' : '\\235', '\236' : '\\236', '\237' : '\\237',
'\240' : '\\240', '\241' : '\\241', '\242' : '\\242',
'\243' : '\\243', '\244' : '\\244', '\245' : '\\245',
'\246' : '\\246', '\247' : '\\247', '\250' : '\\250',
'\251' : '\\251', '\252' : '\\252', '\253' : '\\253',
'\254' : '\\254', '\255' : '\\255', '\256' : '\\256',
'\257' : '\\257', '\260' : '\\260', '\261' : '\\261',
'\262' : '\\262', '\263' : '\\263', '\264' : '\\264',
'\265' : '\\265', '\266' : '\\266', '\267' : '\\267',
'\270' : '\\270', '\271' : '\\271', '\272' : '\\272',
'\273' : '\\273', '\274' : '\\274', '\275' : '\\275',
'\276' : '\\276', '\277' : '\\277', '\300' : '\\300',
'\301' : '\\301', '\302' : '\\302', '\303' : '\\303',
'\304' : '\\304', '\305' : '\\305', '\306' : '\\306',
'\307' : '\\307', '\310' : '\\310', '\311' : '\\311',
'\312' : '\\312', '\313' : '\\313', '\314' : '\\314',
'\315' : '\\315', '\316' : '\\316', '\317' : '\\317',
'\320' : '\\320', '\321' : '\\321', '\322' : '\\322',
'\323' : '\\323', '\324' : '\\324', '\325' : '\\325',
'\326' : '\\326', '\327' : '\\327', '\330' : '\\330',
'\331' : '\\331', '\332' : '\\332', '\333' : '\\333',
'\334' : '\\334', '\335' : '\\335', '\336' : '\\336',
'\337' : '\\337', '\340' : '\\340', '\341' : '\\341',
'\342' : '\\342', '\343' : '\\343', '\344' : '\\344',
'\345' : '\\345', '\346' : '\\346', '\347' : '\\347',
'\350' : '\\350', '\351' : '\\351', '\352' : '\\352',
'\353' : '\\353', '\354' : '\\354', '\355' : '\\355',
'\356' : '\\356', '\357' : '\\357', '\360' : '\\360',
'\361' : '\\361', '\362' : '\\362', '\363' : '\\363',
'\364' : '\\364', '\365' : '\\365', '\366' : '\\366',
'\367' : '\\367', '\370' : '\\370', '\371' : '\\371',
'\372' : '\\372', '\373' : '\\373', '\374' : '\\374',
'\375' : '\\375', '\376' : '\\376', '\377' : '\\377'
}
_idmap = ''.join(chr(x) for x in xrange(256))
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
_QuotePatt = re.compile(r"[\\].")
def _unquote(str):
# If there aren't any doublequotes,
# then there can't be any special characters. See RFC 2109.
if len(str) < 2:
return str
if str[0] != '"' or str[-1] != '"':
return str
# We have to assume that we must decode this string.
# Down to work.
# Remove the "s
str = str[1:-1]
# Check for special sequences. Examples:
# \012 --> \n
# \" --> "
#
i = 0
n = len(str)
res = []
while 0 <= i < n:
Omatch = _OctalPatt.search(str, i)
Qmatch = _QuotePatt.search(str, i)
if not Omatch and not Qmatch: # Neither matched
res.append(str[i:])
break
# else:
j = k = -1
if Omatch: j = Omatch.start(0)
if Qmatch: k = Qmatch.start(0)
if Qmatch and ( not Omatch or k < j ): # QuotePatt matched
res.append(str[i:k])
res.append(str[k+1])
i = k+2
else: # OctalPatt matched
res.append(str[i:j])
res.append( chr( int(str[j+1:j+4], 8) ) )
i = j+4
return _nulljoin(res)
# end _unquote
# The _getdate() routine is used to set the expiration time in
# the cookie's HTTP header. By default, _getdate() returns the
# current time in the appropriate "expires" format for a
# Set-Cookie header. The one optional argument is an offset from
# now, in seconds. For example, an offset of -3600 means "one hour ago".
# The offset may be a floating point number.
#
_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
_monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
from time import gmtime, time
now = time()
year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \
(weekdayname[wd], day, monthname[month], year, hh, mm, ss)
#
# A class to hold ONE key,value pair.
# In a cookie, each such pair may have several attributes.
# so this class is used to keep the attributes associated
# with the appropriate key,value pair.
# This class also includes a coded_value attribute, which
# is used to hold the network representation of the
# value. This is most useful when Python objects are
# pickled for network transit.
#
class Morsel(dict):
# RFC 2109 lists these attributes as reserved:
# path comment domain
# max-age secure version
#
# For historical reasons, these attributes are also reserved:
# expires
#
# This is an extension from Microsoft:
# httponly
#
# This dictionary provides a mapping from the lowercase
# variant on the left to the appropriate traditional
# formatting on the right.
_reserved = { "expires" : "expires",
"path" : "Path",
"comment" : "Comment",
"domain" : "Domain",
"max-age" : "Max-Age",
"secure" : "secure",
"httponly" : "httponly",
"version" : "Version",
}
_flags = {'secure', 'httponly'}
def __init__(self):
# Set defaults
self.key = self.value = self.coded_value = None
# Set default attributes
for K in self._reserved:
dict.__setitem__(self, K, "")
# end __init__
def __setitem__(self, K, V):
K = K.lower()
if not K in self._reserved:
raise CookieError("Invalid Attribute %s" % K)
dict.__setitem__(self, K, V)
# end __setitem__
def isReservedKey(self, K):
return K.lower() in self._reserved
# end isReservedKey
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def output(self, attrs=None, header = "Set-Cookie:"):
return "%s %s" % ( header, self.OutputString(attrs) )
__str__ = output
def __repr__(self):
return '<%s: %s=%s>' % (self.__class__.__name__,
self.key, repr(self.value) )
def js_output(self, attrs=None):
# Print javascript
return """
<script type="text/javascript">
<!-- begin hiding
document.cookie = \"%s\";
// end hiding -->
</script>
""" % ( self.OutputString(attrs).replace('"',r'\"'), )
# end js_output()
def OutputString(self, attrs=None):
# Build up our result
#
result = []
RA = result.append
# First, the key=value pair
RA("%s=%s" % (self.key, self.coded_value))
# Now add any defined attributes
if attrs is None:
attrs = self._reserved
items = self.items()
items.sort()
for K,V in items:
if V == "": continue
if K not in attrs: continue
if K == "expires" and type(V) == type(1):
RA("%s=%s" % (self._reserved[K], _getdate(V)))
elif K == "max-age" and type(V) == type(1):
RA("%s=%d" % (self._reserved[K], V))
elif K == "secure":
RA(str(self._reserved[K]))
elif K == "httponly":
RA(str(self._reserved[K]))
else:
RA("%s=%s" % (self._reserved[K], V))
# Return the result
return _semispacejoin(result)
# end OutputString
# end Morsel class
#
# Pattern for finding cookie
#
# This used to be strict parsing based on the RFC2109 and RFC2068
# specifications. I have since discovered that MSIE 3.0x doesn't
# follow the character rules outlined in those specs. As a
# result, the parsing rules here are less strict.
#
_LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
_LegalValueChars = _LegalKeyChars + r"\[\]"
_CookiePattern = re.compile(
r"(?x)" # This is a Verbose pattern
r"\s*" # Optional whitespace at start of cookie
r"(?P<key>" # Start of group 'key'
"["+ _LegalKeyChars +"]+?" # Any word of at least one letter, nongreedy
r")" # End of group 'key'
r"(" # Optional group: there may not be a value.
r"\s*=\s*" # Equal Sign
r"(?P<val>" # Start of group 'val'
r'"(?:[^\\"]|\\.)*"' # Any doublequoted string
r"|" # or
r"\w{3},\s[\s\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr
r"|" # or
"["+ _LegalValueChars +"]*" # Any word or empty string
r")" # End of group 'val'
r")?" # End of optional value group
r"\s*" # Any number of spaces.
r"(\s+|;|$)" # Ending either at space, semicolon, or EOS.
)
# At long last, here is the cookie class.
# Using this class is almost just like using a dictionary.
# See this module's docstring for example usage.
#
class BaseCookie(dict):
# A container class for a set of Morsels
#
def value_decode(self, val):
"""real_value, coded_value = value_decode(STRING)
Called prior to setting a cookie's value from the network
representation. The VALUE is the value read from HTTP
header.
Override this function to modify the behavior of cookies.
"""
return val, val
# end value_encode
def value_encode(self, val):
"""real_value, coded_value = value_encode(VALUE)
Called prior to setting a cookie's value from the dictionary
representation. The VALUE is the value being assigned.
Override this function to modify the behavior of cookies.
"""
strval = str(val)
return strval, strval
# end value_encode
def __init__(self, input=None):
if input: self.load(input)
# end __init__
def __set(self, key, real_value, coded_value):
"""Private method for setting a cookie's value"""
M = self.get(key, Morsel())
M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M)
# end __set
def __setitem__(self, key, value):
"""Dictionary style assignment."""
if isinstance(value, Morsel):
# allow assignment of constructed Morsels (e.g. for pickling)
dict.__setitem__(self, key, value)
else:
rval, cval = self.value_encode(value)
self.__set(key, rval, cval)
# end __setitem__
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP."""
result = []
items = self.items()
items.sort()
for K,V in items:
result.append( V.output(attrs, header) )
return sep.join(result)
# end output
__str__ = output
def __repr__(self):
L = []
items = self.items()
items.sort()
for K,V in items:
L.append( '%s=%s' % (K,repr(V.value) ) )
return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
def js_output(self, attrs=None):
"""Return a string suitable for JavaScript."""
result = []
items = self.items()
items.sort()
for K,V in items:
result.append( V.js_output(attrs) )
return _nulljoin(result)
# end js_output
def load(self, rawdata):
"""Load cookies from a string (presumably HTTP_COOKIE) or
from a dictionary. Loading cookies from a dictionary 'd'
is equivalent to calling:
map(Cookie.__setitem__, d.keys(), d.values())
"""
if type(rawdata) == type(""):
self.__ParseString(rawdata)
else:
# self.update() wouldn't call our custom __setitem__
for k, v in rawdata.items():
self[k] = v
return
# end load()
def __ParseString(self, str, patt=_CookiePattern):
i = 0 # Our starting point
n = len(str) # Length of string
M = None # current morsel
while 0 <= i < n:
# Start looking for a cookie
match = patt.match(str, i)
if not match: break # No more cookies
K,V = match.group("key"), match.group("val")
i = match.end(0)
# Parse the key, value in case it's metainfo
if K[0] == "$":
# We ignore attributes which pertain to the cookie
# mechanism as a whole. See RFC 2109.
# (Does anyone care?)
if M:
M[ K[1:] ] = V
elif K.lower() in Morsel._reserved:
if M:
if V is None:
if K.lower() in Morsel._flags:
M[K] = True
else:
M[K] = _unquote(V)
elif V is not None:
rval, cval = self.value_decode(V)
self.__set(K, rval, cval)
M = self[K]
# end __ParseString
# end BaseCookie class
class SimpleCookie(BaseCookie):
"""SimpleCookie
SimpleCookie supports strings as cookie values. When setting
the value using the dictionary assignment notation, SimpleCookie
calls the builtin str() to convert the value to a string. Values
received from HTTP are kept as strings.
"""
def value_decode(self, val):
return _unquote( val ), val
def value_encode(self, val):
strval = str(val)
return strval, _quote( strval )
# end SimpleCookie
class SerialCookie(BaseCookie):
"""SerialCookie
SerialCookie supports arbitrary objects as cookie values. All
values are serialized (using cPickle) before being sent to the
client. All incoming values are assumed to be valid Pickle
representations. IF AN INCOMING VALUE IS NOT IN A VALID PICKLE
FORMAT, THEN AN EXCEPTION WILL BE RAISED.
Note: Large cookie values add overhead because they must be
retransmitted on every HTTP transaction.
Note: HTTP has a 2k limit on the size of a cookie. This class
does not check for this limit, so be careful!!!
"""
def __init__(self, input=None):
warnings.warn("SerialCookie class is insecure; do not use it",
DeprecationWarning)
BaseCookie.__init__(self, input)
# end __init__
def value_decode(self, val):
# This could raise an exception!
return loads( _unquote(val) ), val
def value_encode(self, val):
return val, _quote( dumps(val) )
# end SerialCookie
class SmartCookie(BaseCookie):
"""SmartCookie
SmartCookie supports arbitrary objects as cookie values. If the
object is a string, then it is quoted. If the object is not a
string, however, then SmartCookie will use cPickle to serialize
the object into a string representation.
Note: Large cookie values add overhead because they must be
retransmitted on every HTTP transaction.
Note: HTTP has a 2k limit on the size of a cookie. This class
does not check for this limit, so be careful!!!
"""
def __init__(self, input=None):
warnings.warn("Cookie/SmartCookie class is insecure; do not use it",
DeprecationWarning)
BaseCookie.__init__(self, input)
# end __init__
def value_decode(self, val):
strval = _unquote(val)
try:
return loads(strval), val
except:
return strval, val
def value_encode(self, val):
if type(val) == type(""):
return val, _quote(val)
else:
return val, _quote( dumps(val) )
# end SmartCookie
###########################################################
# Backwards Compatibility: Don't break any existing code!
# We provide Cookie() as an alias for SmartCookie()
Cookie = SmartCookie
#
###########################################################
def _test():
import doctest, Cookie
return doctest.testmod(Cookie)
if __name__ == "__main__":
_test()
#Local Variables:
#tab-width: 4
#end:
|
alacritythief/django-rest-framework | refs/heads/master | rest_framework/templatetags/rest_framework.py | 49 | from __future__ import absolute_import, unicode_literals
import re
from django import template
from django.core.urlresolvers import NoReverseMatch, reverse
from django.template import Context, loader
from django.utils import six
from django.utils.encoding import force_text, iri_to_uri
from django.utils.html import escape, smart_urlquote
from django.utils.safestring import SafeData, mark_safe
from rest_framework.renderers import HTMLFormRenderer
from rest_framework.utils.urls import replace_query_param
register = template.Library()
# Regex for adding classes to html snippets
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.simple_tag
def get_pagination_html(pager):
return pager.to_html()
@register.simple_tag
def render_field(field, style=None):
style = style or {}
renderer = style.get('renderer', HTMLFormRenderer())
return renderer.render_field(field, style)
@register.simple_tag
def optional_login(request):
"""
Include a login snippet if REST framework's login view is in the URLconf.
"""
try:
login_url = reverse('rest_framework:login')
except NoReverseMatch:
return ''
snippet = "<li><a href='{href}?next={next}'>Log in</a></li>".format(href=login_url, next=escape(request.path))
return snippet
@register.simple_tag
def optional_logout(request, user):
"""
Include a logout snippet if REST framework's logout view is in the URLconf.
"""
try:
logout_url = reverse('rest_framework:logout')
except NoReverseMatch:
return '<li class="navbar-text">{user}</li>'.format(user=user)
snippet = """<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
{user}
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href='{href}?next={next}'>Log out</a></li>
</ul>
</li>"""
return snippet.format(user=user, href=logout_url, next=escape(request.path))
@register.simple_tag
def add_query_param(request, key, val):
"""
Add a query parameter to the current request url, and return the new url.
"""
iri = request.get_full_path()
uri = iri_to_uri(iri)
return escape(replace_query_param(uri, key, val))
@register.filter
def add_class(value, css_class):
"""
http://stackoverflow.com/questions/4124220/django-adding-css-classes-when-rendering-form-fields-in-a-template
Inserts classes into template variables that contain HTML tags,
useful for modifying forms without needing to change the Form objects.
Usage:
{{ field.label_tag|add_class:"control-label" }}
In the case of REST Framework, the filter is used to add Bootstrap-specific
classes to the forms.
"""
html = six.text_type(value)
match = class_re.search(html)
if match:
m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class,
css_class, css_class),
match.group(1))
if not m:
return mark_safe(class_re.sub(match.group(1) + " " + css_class,
html))
else:
return mark_safe(html.replace('>', ' class="%s">' % css_class, 1))
return value
@register.filter
def format_value(value):
if getattr(value, 'is_hyperlink', False):
return mark_safe('<a href=%s>%s</a>' % (value, escape(value.name)))
if value is None or isinstance(value, bool):
return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
elif isinstance(value, list):
if any([isinstance(item, (list, dict)) for item in value]):
template = loader.get_template('rest_framework/admin/list_value.html')
else:
template = loader.get_template('rest_framework/admin/simple_list_value.html')
context = Context({'value': value})
return template.render(context)
elif isinstance(value, dict):
template = loader.get_template('rest_framework/admin/dict_value.html')
context = Context({'value': value})
return template.render(context)
elif isinstance(value, six.string_types):
if (
(value.startswith('http:') or value.startswith('https:')) and not
re.search(r'\s', value)
):
return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
elif '@' in value and not re.search(r'\s', value):
return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
elif '\n' in value:
return mark_safe('<pre>%s</pre>' % escape(value))
return six.text_type(value)
@register.filter
def add_nested_class(value):
if isinstance(value, dict):
return 'class=nested'
if isinstance(value, list) and any([isinstance(item, (list, dict)) for item in value]):
return 'class=nested'
return ''
# Bunch of stuff cloned from urlize
TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', "']", "'}", "'"]
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'),
('"', '"'), ("'", "'")]
word_split_re = re.compile(r'(\s+)')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
def smart_urlquote_wrapper(matched_url):
"""
Simple wrapper for smart_urlquote. ValueError("Invalid IPv6 URL") can
be raised here, see issue #1386
"""
try:
return smart_urlquote(matched_url)
except ValueError:
return None
@register.filter
def urlize_quoted_links(text, trim_url_limit=None, nofollow=True, autoescape=True):
"""
Converts any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing punctuation (periods, commas, close-parens) and
leading punctuation (opening parens) and it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text longer than this limit
will truncated to trim_url_limit-3 characters and appended with an elipsis.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If autoescape is True, the link text and URLs will get autoescaped.
"""
def trim_url(x, limit=trim_url_limit):
return limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word:
# Deal with punctuation.
lead, middle, trail = '', word, ''
for punctuation in TRAILING_PUNCTUATION:
if middle.endswith(punctuation):
middle = middle[:-len(punctuation)]
trail = punctuation + trail
for opening, closing in WRAPPING_PUNCTUATION:
if middle.startswith(opening):
middle = middle[len(opening):]
lead = lead + opening
# Keep parentheses at the end only if they're balanced.
if (
middle.endswith(closing) and
middle.count(closing) == middle.count(opening) + 1
):
middle = middle[:-len(closing)]
trail = closing + trail
# Make URL we want to point to.
url = None
nofollow_attr = ' rel="nofollow"' if nofollow else ''
if simple_url_re.match(middle):
url = smart_urlquote_wrapper(middle)
elif simple_url_2_re.match(middle):
url = smart_urlquote_wrapper('http://%s' % middle)
elif ':' not in middle and simple_email_re.match(middle):
local, domain = middle.rsplit('@', 1)
try:
domain = domain.encode('idna').decode('ascii')
except UnicodeError:
continue
url = 'mailto:%s@%s' % (local, domain)
nofollow_attr = ''
# Make link.
if url:
trimmed = trim_url(middle)
if autoescape and not safe_input:
lead, trail = escape(lead), escape(trail)
url, trimmed = escape(url), escape(trimmed)
middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
else:
if safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
elif safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
return ''.join(words)
@register.filter
def break_long_headers(header):
"""
Breaks headers longer than 160 characters (~page length)
when possible (are comma separated)
"""
if len(header) > 160 and ',' in header:
header = mark_safe('<br> ' + ', <br>'.join(header.split(',')))
return header
|
MrNuggles/HeyBoet-Telegram-Bot | refs/heads/master | temboo/Library/Dropbox/FileOperations/CreateFolder.py | 5 | # -*- coding: utf-8 -*-
###############################################################################
#
# CreateFolder
# Creates a Dropbox folder.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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 temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class CreateFolder(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the CreateFolder Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(CreateFolder, self).__init__(temboo_session, '/Library/Dropbox/FileOperations/CreateFolder')
def new_input_set(self):
return CreateFolderInputSet()
def _make_result_set(self, result, path):
return CreateFolderResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return CreateFolderChoreographyExecution(session, exec_id, path)
class CreateFolderInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the CreateFolder
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_AccessTokenSecret(self, value):
"""
Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
"""
super(CreateFolderInputSet, self)._set_input('AccessTokenSecret', value)
def set_AccessToken(self, value):
"""
Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
"""
super(CreateFolderInputSet, self)._set_input('AccessToken', value)
def set_AppKey(self, value):
"""
Set the value of the AppKey input for this Choreo. ((required, string) The App Key provided by Dropbox (AKA the OAuth Consumer Key).)
"""
super(CreateFolderInputSet, self)._set_input('AppKey', value)
def set_AppSecret(self, value):
"""
Set the value of the AppSecret input for this Choreo. ((required, string) The App Secret provided by Dropbox (AKA the OAuth Consumer Secret).)
"""
super(CreateFolderInputSet, self)._set_input('AppSecret', value)
def set_NewFolderName(self, value):
"""
Set the value of the NewFolderName input for this Choreo. ((required, string) The name of the new folder to create. A path with a root folder is also valid (i.e. /RootFolder/NewFolderName).)
"""
super(CreateFolderInputSet, self)._set_input('NewFolderName', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.)
"""
super(CreateFolderInputSet, self)._set_input('ResponseFormat', value)
def set_Root(self, value):
"""
Set the value of the Root input for this Choreo. ((optional, string) Defaults to "auto" which automatically determines the root folder using your app's permission level. Other options are "sandbox" (App Folder) and "dropbox" (Full Dropbox).)
"""
super(CreateFolderInputSet, self)._set_input('Root', value)
class CreateFolderResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the CreateFolder Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Dropbox. Corresponds to the ResponseFormat input. Defaults to json.)
"""
return self._output.get('Response', None)
class CreateFolderChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return CreateFolderResultSet(response, path)
|
Stanford-Online/edx-platform | refs/heads/master | openedx/core/djangoapps/api_admin/api/v1/tests/test_views.py | 18 | """
Tests for the `api_admin` api module.
"""
import json
from rest_framework.reverse import reverse
from django.contrib.auth.models import User
from django.test import TestCase
from openedx.core.djangoapps.api_admin.tests import factories
from openedx.core.djangolib.testing.utils import skip_unless_lms
from student.tests.factories import UserFactory
@skip_unless_lms
class ApiAccessRequestViewTests(TestCase):
"""
Tests for API access request api views.
"""
password = 'test'
def setUp(self):
"""
Perform operations common to all test cases.
"""
self.user = UserFactory.create(password=self.password)
self.client.login(username=self.user.username, password=self.password)
# Create APIAccessRequest records for testing.
factories.ApiAccessRequestFactory.create_batch(5)
factories.ApiAccessRequestFactory.create(user=self.user)
self.url = reverse('api_admin:api:v1:list_api_access_request')
def update_user_and_re_login(self, **kwargs):
"""
Update attributes of currently logged in user.
"""
self.client.logout()
User.objects.filter(id=self.user.id).update(**kwargs)
self.client.login(username=self.user.username, password=self.password)
def _assert_api_access_request_response(self, api_response, expected_results_count):
"""
Assert API response on `API Access Request` endpoint.
"""
json_content = json.loads(api_response.content)
self.assertEqual(api_response.status_code, 200)
self.assertEqual(json_content['count'], expected_results_count)
def test_list_view_for_not_authenticated_user(self):
"""
Make sure API end point 'api_access_request' returns access denied if user is not authenticated.
"""
self.update_user_and_re_login(is_staff=False)
response = self.client.get(self.url)
self._assert_api_access_request_response(api_response=response, expected_results_count=1)
def test_list_view_for_non_staff_user(self):
"""
Make sure API end point 'api_access_request' returns api access requests made only by the requesting user.
"""
self.client.logout()
response = self.client.get(self.url)
self.assertEqual(response.status_code, 401)
def test_list_view_for_staff_user(self):
"""
Make sure API end point 'api_access_request' returns all api access requests to staff user.
"""
self.update_user_and_re_login(is_staff=True)
response = self.client.get(self.url)
self._assert_api_access_request_response(api_response=response, expected_results_count=6)
def test_filtering_for_staff_user(self):
"""
Make sure that staff user can filter API Access Requests with username.
"""
self.update_user_and_re_login(is_staff=True)
response = self.client.get(self.url + '?user__username={}'.format(self.user.username))
self._assert_api_access_request_response(api_response=response, expected_results_count=1)
def test_filtering_for_non_existing_user(self):
"""
Make sure that 404 is returned if user does not exist against the username
used for filtering.
"""
self.update_user_and_re_login(is_staff=True)
response = self.client.get(self.url + '?user__username={}'.format('non-existing-user-name'))
self.assertEqual(response.status_code, 200)
self._assert_api_access_request_response(api_response=response, expected_results_count=0)
|
depjs/dep | refs/heads/master | node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py | 8 | # This file comes from
# https://github.com/martine/ninja/blob/master/misc/ninja_syntax.py
# Do not edit! Edit the upstream one instead.
"""Python module for generating .ninja files.
Note that this is emphatically not a required piece of Ninja; it's
just a helpful utility for build-file-generation systems that already
use Python.
"""
import textwrap
def escape_path(word):
return word.replace("$ ", "$$ ").replace(" ", "$ ").replace(":", "$:")
class Writer(object):
def __init__(self, output, width=78):
self.output = output
self.width = width
def newline(self):
self.output.write("\n")
def comment(self, text):
for line in textwrap.wrap(text, self.width - 2):
self.output.write("# " + line + "\n")
def variable(self, key, value, indent=0):
if value is None:
return
if isinstance(value, list):
value = " ".join(filter(None, value)) # Filter out empty strings.
self._line("%s = %s" % (key, value), indent)
def pool(self, name, depth):
self._line("pool %s" % name)
self.variable("depth", depth, indent=1)
def rule(
self,
name,
command,
description=None,
depfile=None,
generator=False,
pool=None,
restat=False,
rspfile=None,
rspfile_content=None,
deps=None,
):
self._line("rule %s" % name)
self.variable("command", command, indent=1)
if description:
self.variable("description", description, indent=1)
if depfile:
self.variable("depfile", depfile, indent=1)
if generator:
self.variable("generator", "1", indent=1)
if pool:
self.variable("pool", pool, indent=1)
if restat:
self.variable("restat", "1", indent=1)
if rspfile:
self.variable("rspfile", rspfile, indent=1)
if rspfile_content:
self.variable("rspfile_content", rspfile_content, indent=1)
if deps:
self.variable("deps", deps, indent=1)
def build(
self, outputs, rule, inputs=None, implicit=None, order_only=None, variables=None
):
outputs = self._as_list(outputs)
all_inputs = self._as_list(inputs)[:]
out_outputs = list(map(escape_path, outputs))
all_inputs = list(map(escape_path, all_inputs))
if implicit:
implicit = map(escape_path, self._as_list(implicit))
all_inputs.append("|")
all_inputs.extend(implicit)
if order_only:
order_only = map(escape_path, self._as_list(order_only))
all_inputs.append("||")
all_inputs.extend(order_only)
self._line(
"build %s: %s" % (" ".join(out_outputs), " ".join([rule] + all_inputs))
)
if variables:
if isinstance(variables, dict):
iterator = iter(variables.items())
else:
iterator = iter(variables)
for key, val in iterator:
self.variable(key, val, indent=1)
return outputs
def include(self, path):
self._line("include %s" % path)
def subninja(self, path):
self._line("subninja %s" % path)
def default(self, paths):
self._line("default %s" % " ".join(self._as_list(paths)))
def _count_dollars_before_index(self, s, i):
"""Returns the number of '$' characters right in front of s[i]."""
dollar_count = 0
dollar_index = i - 1
while dollar_index > 0 and s[dollar_index] == "$":
dollar_count += 1
dollar_index -= 1
return dollar_count
def _line(self, text, indent=0):
"""Write 'text' word-wrapped at self.width characters."""
leading_space = " " * indent
while len(leading_space) + len(text) > self.width:
# The text is too wide; wrap if possible.
# Find the rightmost space that would obey our width constraint and
# that's not an escaped space.
available_space = self.width - len(leading_space) - len(" $")
space = available_space
while True:
space = text.rfind(" ", 0, space)
if space < 0 or self._count_dollars_before_index(text, space) % 2 == 0:
break
if space < 0:
# No such space; just use the first unescaped space we can find.
space = available_space - 1
while True:
space = text.find(" ", space + 1)
if (
space < 0
or self._count_dollars_before_index(text, space) % 2 == 0
):
break
if space < 0:
# Give up on breaking.
break
self.output.write(leading_space + text[0:space] + " $\n")
text = text[space + 1 :]
# Subsequent lines are continuations, so indent them.
leading_space = " " * (indent + 2)
self.output.write(leading_space + text + "\n")
def _as_list(self, input):
if input is None:
return []
if isinstance(input, list):
return input
return [input]
def escape(string):
"""Escape a string such that it can be embedded into a Ninja file without
further interpretation."""
assert "\n" not in string, "Ninja syntax does not allow newlines"
# We only have one special metacharacter: '$'.
return string.replace("$", "$$")
|
TimYi/django | refs/heads/master | tests/migrations/test_deprecated_fields.py | 504 | from django.core.management import call_command
from django.test import override_settings
from .test_base import MigrationTestBase
class Tests(MigrationTestBase):
"""
Deprecated model fields should still be usable in historic migrations.
"""
@override_settings(MIGRATION_MODULES={"migrations": "migrations.deprecated_field_migrations"})
def test_migrate(self):
# Make sure no tables are created
self.assertTableNotExists("migrations_ipaddressfield")
# Run migration
call_command("migrate", verbosity=0)
# Make sure the right tables exist
self.assertTableExists("migrations_ipaddressfield")
# Unmigrate everything
call_command("migrate", "migrations", "zero", verbosity=0)
# Make sure it's all gone
self.assertTableNotExists("migrations_ipaddressfield")
|
chrisndodge/edx-platform | refs/heads/master | common/djangoapps/microsite_configuration/tests/backends/test_base.py | 38 | """
Test Microsite base backends.
"""
import logging
from mock import patch
from django.conf import settings
from django.test import TestCase
from microsite_configuration import microsite
from microsite_configuration.backends.base import (
AbstractBaseMicrositeBackend,
BaseMicrositeBackend
)
log = logging.getLogger(__name__)
class NullBackend(AbstractBaseMicrositeBackend):
"""
A class that does nothing but inherit from the base class.
We created this class to test methods of AbstractBaseMicrositeBackend class.
Since abstract class cannot be instantiated we created this wrapper class.
"""
def set_config_by_domain(self, domain):
"""
For a given request domain, find a match in our microsite configuration
and make it available to the complete django request process
"""
return super(NullBackend, self).set_config_by_domain(domain)
def get_template_path(self, relative_path, **kwargs):
"""
Returns a path (string) to a Mako template, which can either be in
an override or will just return what is passed in which is expected to be a string
"""
return super(NullBackend, self).get_template_path(relative_path, **kwargs)
def get_value(self, val_name, default=None, **kwargs):
"""
Returns a value associated with the request's microsite, if present
"""
return super(NullBackend, self).get_value(val_name, default, **kwargs)
def get_dict(self, dict_name, default=None, **kwargs):
"""
Returns a dictionary product of merging the request's microsite and
the default value.
This can be used, for example, to return a merged dictonary from the
settings.FEATURES dict, including values defined at the microsite
"""
return super(NullBackend, self).get_dict(dict_name, default, **kwargs)
def is_request_in_microsite(self):
"""
This will return True/False if the current request is a request within a microsite
"""
return super(NullBackend, self).is_request_in_microsite()
def has_override_value(self, val_name):
"""
Returns True/False whether a Microsite has a definition for the
specified named value
"""
return super(NullBackend, self).has_override_value(val_name)
def get_all_config(self):
"""
This returns a set of orgs that are considered within all microsites.
This can be used, for example, to do filtering
"""
return super(NullBackend, self).get_all_config()
def get_value_for_org(self, org, val_name, default=None):
"""
This returns a configuration value for a microsite which has an org_filter that matches
what is passed in
"""
return super(NullBackend, self).get_value_for_org(org, val_name, default)
def get_all_orgs(self):
"""
This returns a set of orgs that are considered within a microsite. This can be used,
for example, to do filtering
"""
return super(NullBackend, self).get_all_orgs()
def clear(self):
"""
Clears out any microsite configuration from the current request/thread
"""
return super(NullBackend, self).clear()
class AbstractBaseMicrositeBackendTests(TestCase):
"""
Go through and test the base abstract class
"""
def test_cant_create_instance(self):
"""
We shouldn't be able to create an instance of the base abstract class
"""
with self.assertRaises(TypeError):
AbstractBaseMicrositeBackend() # pylint: disable=abstract-class-instantiated
def test_not_yet_implemented(self):
"""
Make sure all base methods raise a NotImplementedError exception
"""
backend = NullBackend()
with self.assertRaises(NotImplementedError):
backend.set_config_by_domain(None)
with self.assertRaises(NotImplementedError):
backend.get_value(None, None)
with self.assertRaises(NotImplementedError):
backend.get_dict(None, None)
with self.assertRaises(NotImplementedError):
backend.is_request_in_microsite()
with self.assertRaises(NotImplementedError):
backend.has_override_value(None)
with self.assertRaises(NotImplementedError):
backend.get_all_config()
with self.assertRaises(NotImplementedError):
backend.clear()
with self.assertRaises(NotImplementedError):
backend.get_value_for_org(None, None, None)
with self.assertRaises(NotImplementedError):
backend.get_all_orgs()
@patch(
'microsite_configuration.microsite.BACKEND',
microsite.get_backend(
'microsite_configuration.backends.base.BaseMicrositeBackend', BaseMicrositeBackend
)
)
class BaseMicrositeBackendTests(TestCase):
"""
Go through and test the BaseMicrositeBackend class for behavior which is not
overriden in subclasses
"""
def test_enable_microsites_pre_startup(self):
"""
Tests microsite.test_enable_microsites_pre_startup works as expected.
"""
# remove microsite root directory paths first
settings.DEFAULT_TEMPLATE_ENGINE['DIRS'] = [
path for path in settings.DEFAULT_TEMPLATE_ENGINE['DIRS']
if path != settings.MICROSITE_ROOT_DIR
]
with patch('microsite_configuration.backends.base.BaseMicrositeBackend.has_configuration_set',
return_value=False):
microsite.enable_microsites_pre_startup(log)
self.assertNotIn(settings.MICROSITE_ROOT_DIR,
settings.DEFAULT_TEMPLATE_ENGINE['DIRS'])
with patch('microsite_configuration.backends.base.BaseMicrositeBackend.has_configuration_set',
return_value=True):
microsite.enable_microsites_pre_startup(log)
self.assertIn(settings.MICROSITE_ROOT_DIR,
settings.DEFAULT_TEMPLATE_ENGINE['DIRS'])
|
Moriadry/tensorflow | refs/heads/master | tensorflow/contrib/specs/python/summaries_test.py | 112 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for specs-related summarization functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.specs.python import specs
from tensorflow.contrib.specs.python import summaries
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
def _rand(*size):
return np.random.uniform(size=size).astype("f")
class SummariesTest(test.TestCase):
def testStructure(self):
with self.test_session():
inputs_shape = (1, 18, 19, 5)
inputs = constant_op.constant(_rand(*inputs_shape))
spec = "net = Cr(64, [5, 5])"
outputs = specs.create_net(spec, inputs)
variables.global_variables_initializer().run()
result = outputs.eval()
self.assertEqual(tuple(result.shape), (1, 18, 19, 64))
self.assertEqual(
summaries.tf_spec_structure(
spec, input_shape=inputs_shape),
"_ variablev2 conv variablev2 biasadd relu")
def testStructureFromTensor(self):
with self.test_session():
inputs = constant_op.constant(_rand(1, 18, 19, 5))
spec = "net = Cr(64, [5, 5])"
outputs = specs.create_net(spec, inputs)
variables.global_variables_initializer().run()
result = outputs.eval()
self.assertEqual(tuple(result.shape), (1, 18, 19, 64))
self.assertEqual(
summaries.tf_spec_structure(spec, inputs),
"_ variablev2 conv variablev2 biasadd relu")
def testPrint(self):
with self.test_session():
inputs = constant_op.constant(_rand(1, 18, 19, 5))
spec = "net = Cr(64, [5, 5])"
outputs = specs.create_net(spec, inputs)
variables.global_variables_initializer().run()
result = outputs.eval()
self.assertEqual(tuple(result.shape), (1, 18, 19, 64))
summaries.tf_spec_print(spec, inputs)
def testSummary(self):
with self.test_session():
inputs = constant_op.constant(_rand(1, 18, 19, 5))
spec = "net = Cr(64, [5, 5])"
outputs = specs.create_net(spec, inputs)
variables.global_variables_initializer().run()
result = outputs.eval()
self.assertEqual(tuple(result.shape), (1, 18, 19, 64))
summaries.tf_spec_summary(spec, inputs)
if __name__ == "__main__":
test.main()
|
Rheinhart/Firefly | refs/heads/master | firefly/distributed/child.py | 8 | #coding:utf8
'''
Created on 2013-8-14
@author: lan (www.9miao.com)
'''
class Child(object):
'''子节点对象'''
def __init__(self,cid,name):
'''初始化子节点对象
'''
self._id = cid
self._name = name
self._transport = None
def getName(self):
'''获取子节点的名称'''
return self._name
def setTransport(self,transport):
'''设置子节点的通道'''
self._transport = transport
def callbackChild(self,*args,**kw):
'''回调子节点的接口
return a Defered Object (recvdata)
'''
recvdata = self._transport.callRemote('callChild',*args,**kw)
return recvdata
|
sailingchannels/crawler | refs/heads/master | crawler.py | 1 | import requests
import json
import config
import calendar
import sys
import time
import math
import xmltodict
import logging
import arrow
import os
from pymongo import MongoClient, DESCENDING
from datetime import datetime, date, timedelta
import detectlanguage
from Queue import Queue
from twython import Twython
from apikeyprovider import APIKeyProvider
from cmreslogging.handlers import CMRESHandler
apiKeyProvider = APIKeyProvider(config.apiKey())
videoKeyProvider = APIKeyProvider(config.apiVideoKeys())
# logging
logger = logging.getLogger("sailing-channels-crawler")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
print "environment", os.getenv("ENVIRONMENT")
if os.getenv("ENVIRONMENT") == "production":
elasticHandler = CMRESHandler(hosts=[{"host": "elasticsearch", "port": 9200}],
auth_type=CMRESHandler.AuthType.NO_AUTH,
es_index_name="sailing-channels-crawler")
logger.addHandler(elasticHandler)
# social networks
twitter = Twython(config.twitter()["consumerKey"], config.twitter()[
"consumerSecret"], config.twitter()["accessToken"], config.twitter()["accessSecret"])
# config
sailingTerms = []
blacklist = []
THREE_HOURS_IN_SECONDS = 10800
ONE_HOUR_IN_SECONDS = 3600
ONE_DAY_IN_SECONDS = 86400
ONE_WEEK_IN_SECONDS = 604800
# open mongodb connection
client = MongoClient(config.mongoDB())
db_name = "sailing-channels"
devMode = False
if len(sys.argv) != 2:
db_name += "-dev"
devMode = True
logger.info("*** DEVELOPER MODE ***")
db = client[db_name]
# add sailing terms
for tt in db.sailingterms.find({}):
sailingTerms.append(tt["_id"])
# fill blacklist
for bb in db.blacklist.find({}):
blacklist.append(bb["_id"])
logger.info(sailingTerms)
# members
channels = {}
def deleteChannel(channelId):
db.channels.delete_one({"_id": channelId})
db.videos.delete_many({"channel": channelId})
db.views.delete_many({"_id.channel": channelId})
db.visits.delete_many({"channel": channelId})
db.subscribers.delete_many({"_id.channel": channelId})
def storeVideoWithStats(channelId, vid):
existingVideo = db.videos.find_one({"_id": vid["id"]}, projection=[
"_id", "updatedAt", "publishedAt"])
shouldUpdateVideo = True
if existingVideo is not None and "updatedAt" in existingVideo:
if not ("publishedAt" in existingVideo):
existingVideo["publishedAt"] = arrow.utcnow().timestamp
logger.warning(
"video %s did not have a publishedAt date, tmp set to current timestamp", vid["id"])
uploadedLaterThanThreshold = ONE_HOUR_IN_SECONDS * 3
publishedSinceSeconds = math.fabs(
int(existingVideo["publishedAt"]) - arrow.utcnow().timestamp)
if publishedSinceSeconds >= ONE_WEEK_IN_SECONDS:
uploadedLaterThanThreshold = ONE_DAY_IN_SECONDS
if publishedSinceSeconds >= 4 * ONE_WEEK_IN_SECONDS:
uploadedLaterThanThreshold = ONE_WEEK_IN_SECONDS
if publishedSinceSeconds >= 6 * 4 * ONE_WEEK_IN_SECONDS:
uploadedLaterThanThreshold = 4 * ONE_WEEK_IN_SECONDS
updatedTimeDiff = math.fabs(int(
existingVideo["updatedAt"]) - arrow.utcnow().timestamp)
shouldUpdateVideo = updatedTimeDiff >= uploadedLaterThanThreshold
if shouldUpdateVideo:
# fetch video statistics
key = videoKeyProvider.apiKey()
rd = requests.get(
"https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,status&id=" + vid["id"] + "&key=" + key)
videoStat = rd.json()
statistics = None
if videoStat is None or "items" not in videoStat:
logger.warning("could not retrieve statistic for channel %s, apikey %s, statuscode %d, content: %s",
channelId, key, rd.status_code, rd.content)
return
if len(videoStat["items"]) > 0:
statistics = videoStat["items"][0]["statistics"]
# store video tags
try:
vid["tags"] = [x.lower()
for x in videoStat["items"][0]["snippet"]["tags"]]
except:
pass
if statistics:
if statistics.has_key("viewCount"):
vid["views"] = int(statistics["viewCount"])
if statistics.has_key("likeCount"):
vid["likes"] = int(statistics["likeCount"])
if statistics.has_key("dislikeCount"):
vid["dislikes"] = int(statistics["dislikeCount"])
if statistics.has_key("commentCount"):
vid["comments"] = int(statistics["commentCount"])
# status of video
status = videoStat["items"][0]["status"]
if status["privacyStatus"] == "public":
# prepare video for inserting into database
dbVid = vid
dbVid["_id"] = dbVid["id"]
dbVid["channel"] = channelId
dbVid["updatedAt"] = arrow.utcnow().timestamp
del dbVid["id"]
try:
vidDoesNotExists = existingVideo is None
# reasonable fresh video, post to twitter and facebook
if vidDoesNotExists and math.fabs(int(dbVid["publishedAt"]) - time.mktime(datetime.utcnow().timetuple())) <= 15000:
ch = db.channels.find_one(
{"_id": channelId}, projection=["title"])
# twitter
try:
msg = "New: " + ch["title"] + " \"" + dbVid["title"] + \
"\" https://sailing-channels.com/#/channel/" + channelId
if devMode <> True:
twitter.update_status(status=msg)
else:
logger.warning(msg)
except Exception, e:
logger.exception(e)
# update information in database
db.videos.update_one({
"_id": dbVid["_id"]
}, {
"$set": dbVid
}, True)
logger.info("upserted video %s for channel %s",
dbVid["_id"], channelId)
except:
pass
else:
# remove non public videos
db.videos.delete_one({
"_id": dbVid["id"]
})
logger.info("deleted video %s for channel %s",
dbVid["_id"], channelId)
def readStatistics(channelId):
r = requests.get("https://www.googleapis.com/youtube/v3/channels?part=statistics,snippet,brandingSettings&id=" +
channelId + "&key=" + apiKeyProvider.apiKey())
stats = r.json()
if stats is None or "items" not in stats:
return None, None, None
return stats["items"][0]["statistics"], stats["items"][0]["snippet"], stats["items"][0]["brandingSettings"]
def linreg(X, Y):
"""
return a,b in solution to y = ax + b such that root mean square distance between trend line and original points is minimized
"""
N = len(X)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for x, y in zip(X, Y):
Sx = Sx + x
Sy = Sy + y
Sxx = Sxx + x*x
Syy = Syy + y*y
Sxy = Sxy + x*y
det = Sxx * N - Sx * Sx
return (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
def getChannelPopularityIndex(channelId):
# fetch views from 7 days ago
daysViewsCursor = db.views.find({
"_id.channel": channelId
}, limit=3, projection=["views"], sort=[("date", DESCENDING)])
# calculate view gain
if daysViewsCursor is not None:
viewsOverTime = [view["views"] for view in daysViewsCursor]
viewsOverTime.reverse()
if len(viewsOverTime) <= 0:
return 0
a, b = linreg(range(len(viewsOverTime)), viewsOverTime)
return a
return 0
def upsertChannel(subChannelId, ignoreSailingTerm=False):
try:
last_crawled = db.channels.find_one(
{"_id": subChannelId}, projection=["lastCrawl"])
if last_crawled:
if (datetime.now() - last_crawled["lastCrawl"]).total_seconds() < ONE_DAY_IN_SECONDS:
logger.info("skip %s last crawl less than %d secs ago",
subChannelId, ONE_HOUR_IN_SECONDS)
return
logger.info("Update channel %s with new data", subChannelId)
stats, channel_detail, branding_settings = readStatistics(
subChannelId)
hasSailingTerm = False
if stats is None:
logger.warning(
"could not read stats for channel %s", subChannelId)
return
# check if one of the sailing terms is available
for term in sailingTerms:
if (term in channel_detail["title"].lower() or term in channel_detail["description"].lower()):
hasSailingTerm = True
break
# log what happened to the channel
logger.info("%s %s %d", subChannelId,
hasSailingTerm, int(stats["videoCount"]))
# this is not a sailing channel, so we will keep track of that id
if ignoreSailingTerm == False and hasSailingTerm == False:
db.nonsailingchannels.update_one(
{"_id": subChannelId}, {
"$set": {
"_id": subChannelId,
"decisionMadeAt": arrow.utcnow().timestamp
}
}, True)
if ignoreSailingTerm == True:
hasSailingTerm = True
# blacklisted channel
if subChannelId in blacklist:
hasSailingTerm = False
deleteChannel(subChannelId)
if int(stats["videoCount"]) > 0 and hasSailingTerm:
pd = datetime.strptime(
channel_detail["publishedAt"], "%Y-%m-%dT%H:%M:%SZ")
subscriberCount = 0
if "subscriberCount" in stats:
subscriberCount = int(stats["subscriberCount"])
channels[subChannelId] = {
"id": subChannelId,
"title": channel_detail["title"],
"description": channel_detail["description"],
"publishedAt": calendar.timegm(pd.utctimetuple()),
"thumbnail": channel_detail["thumbnails"]["default"]["url"],
"subscribers": subscriberCount,
"views": int(stats["viewCount"]),
"subscribersHidden": bool(stats["hiddenSubscriberCount"]),
"lastCrawl": datetime.now()
}
# add keywords if available
try:
if branding_settings is not None and "channel" in branding_settings and "keywords" in branding_settings["channel"]:
channels[subChannelId]["keywords"] = branding_settings["channel"]["keywords"].split(
" ")
except Exception, e:
logger.exception(e)
# get popularity
popView = getChannelPopularityIndex(subChannelId)
sys.exit(0)
channels[subChannelId]["popularity"] = {
"subscribers": 0,
"views": popView,
"total": popView
}
lotsOfText = channels[subChannelId]["description"] + " "
# add country info if available
if channel_detail.has_key("country"):
channels[subChannelId]["country"] = channel_detail["country"].lower()
hasLanguage = False
ch_lang = db.channels.find_one(
{"_id": subChannelId}, projection=["detectedLanguage"])
if ch_lang:
if ch_lang.has_key("detectedLanguage"):
hasLanguage = True
try:
useDetectLangKey = 0
detectlanguage.configuration.api_key = config.detectLanguage()[
useDetectLangKey]
# detect the language of the channel
if not hasLanguage and devMode == False:
channels[subChannelId]["language"] = "en"
runLoop = True
while runLoop:
try:
detectedLang = detectlanguage.detect(
lotsOfText)
runLoop = False
except:
useDetectLangKey = useDetectLangKey + 1
if useDetectLangKey > len(config.detectLanguage()):
runLoop = False
else:
detectlanguage.configuration.api_key = config.detectLanguage()[
useDetectLangKey]
# did we find a language in the text body?
if len(detectedLang) > 0:
# is the detection reliable?
if detectedLang[0]["isReliable"]:
channels[subChannelId]["language"] = detectedLang[0]["language"]
channels[subChannelId]["detectedLanguage"] = True
except Exception, e:
logger.exception(e)
# insert subscriber counts
try:
db.subscribers.update_one({
"_id": {
"channel": subChannelId,
"date": int(date.today().strftime("%Y%m%d"))
}
}, {
"$set": {
"year": date.today().year,
"month": date.today().month,
"day": date.today().day,
"date": datetime.utcnow(),
"subscribers": channels[subChannelId]["subscribers"]
}
}, True)
except Exception, e:
logger.exception(e)
# insert view counts
try:
db.views.update_one({
"_id": {
"channel": subChannelId,
"date": int(date.today().strftime("%Y%m%d"))
}
}, {
"$set": {
"year": date.today().year,
"month": date.today().month,
"day": date.today().day,
"date": datetime.utcnow(),
"views": channels[subChannelId]["views"]
}
}, True)
except Exception, e:
logger.exception(e)
# upsert data in mongodb
try:
db.channels.update_one({
"_id": subChannelId
}, {
"$set": channels[subChannelId]
}, True)
logger.info("updated %s", subChannelId)
except Exception, e:
logger.exception(e)
except Exception, e:
logger.exception(e)
def addAdditionalChannels():
adds = []
for cc in db.additional.find({}, limit=100):
adds.append(cc["_id"])
for a in adds:
try:
logger.info("Additional channel %s will be added", a)
# add this channel
upsertChannel(a, a["ignoreSailingTerm"])
# check if channel is now available
check_channel = db.channels.find_one({"_id": a})
if check_channel != None:
logger.info(
"Additional channel %s will be deleted now, it's added to the channels list", a)
db.additional.delete_one({"_id": a})
except Exception, e:
logger.exception(e)
def checkAllChannelsForNewVideos():
for channel in db.channels.find({}, projection=["_id"]):
try:
logger.info("Store videos via RSS feed for channel %s",
channel["_id"])
maxPublishedAt = storeVideosFromRSSFeed(channel["_id"])
# update videoCount and lastUploadAt on channel document
db.channels.update_one({
"_id": channel["_id"]
}, {
"$set": {
"videoCount": db.videos.count({"channel": channel["_id"]}),
"lastUploadAt": maxPublishedAt
}
})
except Exception, e:
logger.exception(e)
def storeVideosFromRSSFeed(channelId):
headers = {
"User-Agent": "Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.18"}
url = "https://www.youtube.com/feeds/videos.xml?channel_id=" + channelId
r = requests.get(url, headers=headers)
if r.status_code != 200:
logger.warning("request to %s failed with status code %d, body: %s",
url, r.status_code, r.content)
return
videoFeed = xmltodict.parse(r.content)
if videoFeed is None or "feed" not in videoFeed:
logger.warning("xml for url %s does not contain valid feed", url)
return
if "entry" not in videoFeed["feed"]:
logger.warning(
"xml for url %s does not contain any video entries", url)
return
maxPublishedAt = 0
for feedItem in videoFeed["feed"]["entry"]:
try:
storedVideo = db.videos.find_one(
{"_id": feedItem["yt:videoId"]}, projection=["_id", "updatedAt"])
publishedAt = storeVideo(feedItem)
if publishedAt > maxPublishedAt:
maxPublishedAt = publishedAt
except Exception, e:
logger.exception(e)
return maxPublishedAt
def storeVideo(feedItem):
publishedAt = arrow.get(feedItem["published"]).timestamp
updatedAt = arrow.get(feedItem["updated"]).timestamp
vid = {
"id": feedItem["yt:videoId"],
"title": feedItem["title"],
"description": feedItem["media:group"]["media:description"],
"publishedAt": publishedAt,
"updatedAt": updatedAt,
"views": int(feedItem["media:group"]["media:community"]["media:statistics"]["@views"]),
"channel": feedItem["yt:channelId"],
"geoChecked": False,
"tags": []
}
storeVideoWithStats(vid["channel"], vid)
return publishedAt
def updateCurrentChannels():
for cc in db.channels.find({}, projection=["_id"]):
try:
upsertChannel(cc["_id"], True)
except Exception, e:
logger.exception(e)
def updatePopularity():
for cc in db.channels.find({}, projection=["_id", "views"]):
popViews = getChannelPopularityIndex(cc["_id"])
print("set popularity for channel", cc["_id"], popViews)
db.channels.update_one({
"_id": cc["_id"]
}, {
"$set": {
"popularity": {
"subscribers": 0,
"views": popViews,
"total": popViews
}
}
})
while True:
logger.info("*** CYCLE STARTED ***")
updatePopularity()
addAdditionalChannels()
updateCurrentChannels()
checkAllChannelsForNewVideos()
logger.info("*** CYCLE COMPLETED ***")
time.sleep(ONE_HOUR_IN_SECONDS / 4)
|
naousse/odoo | refs/heads/8.0 | addons/survey_crm/__openerp__.py | 312 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Survey CRM',
'version': '2.0',
'category': 'Marketing',
'complexity': 'easy',
'website': 'https://www.odoo.com/page/survey',
'description': """
Survey - CRM (bridge module)
=================================================================================
This module adds a Survey mass mailing button inside the more option of lead/customers views
""",
'author': 'OpenERP SA',
'depends': ['crm', 'survey'],
'data': [
'crm_view.xml',
],
'installable': True,
'auto_install': True
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
jeezybrick/django | refs/heads/master | django/db/models/fields/files.py | 96 | import datetime
import os
import warnings
from django import forms
from django.core import checks
from django.core.files.base import File
from django.core.files.images import ImageFile
from django.core.files.storage import default_storage
from django.db.models import signals
from django.db.models.fields import Field
from django.utils import six
from django.utils.deprecation import RemovedInDjango110Warning
from django.utils.encoding import force_str, force_text
from django.utils.inspect import func_supports_parameter
from django.utils.translation import ugettext_lazy as _
class FieldFile(File):
def __init__(self, instance, field, name):
super(FieldFile, self).__init__(None, name)
self.instance = instance
self.field = field
self.storage = field.storage
self._committed = True
def __eq__(self, other):
# Older code may be expecting FileField values to be simple strings.
# By overriding the == operator, it can remain backwards compatibility.
if hasattr(other, 'name'):
return self.name == other.name
return self.name == other
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.name)
# The standard File contains most of the necessary properties, but
# FieldFiles can be instantiated without a name, so that needs to
# be checked for here.
def _require_file(self):
if not self:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
def _get_file(self):
self._require_file()
if not hasattr(self, '_file') or self._file is None:
self._file = self.storage.open(self.name, 'rb')
return self._file
def _set_file(self, file):
self._file = file
def _del_file(self):
del self._file
file = property(_get_file, _set_file, _del_file)
def _get_path(self):
self._require_file()
return self.storage.path(self.name)
path = property(_get_path)
def _get_url(self):
self._require_file()
return self.storage.url(self.name)
url = property(_get_url)
def _get_size(self):
self._require_file()
if not self._committed:
return self.file.size
return self.storage.size(self.name)
size = property(_get_size)
def open(self, mode='rb'):
self._require_file()
self.file.open(mode)
# open() doesn't alter the file's contents, but it does reset the pointer
open.alters_data = True
# In addition to the standard File API, FieldFiles have extra methods
# to further manipulate the underlying file, as well as update the
# associated model instance.
def save(self, name, content, save=True):
name = self.field.generate_filename(self.instance, name)
if func_supports_parameter(self.storage.save, 'max_length'):
self.name = self.storage.save(name, content, max_length=self.field.max_length)
else:
warnings.warn(
'Backwards compatibility for storage backends without '
'support for the `max_length` argument in '
'Storage.save() will be removed in Django 1.10.',
RemovedInDjango110Warning, stacklevel=2
)
self.name = self.storage.save(name, content)
setattr(self.instance, self.field.name, self.name)
# Update the filesize cache
self._size = content.size
self._committed = True
# Save the object because it has changed, unless save is False
if save:
self.instance.save()
save.alters_data = True
def delete(self, save=True):
if not self:
return
# Only close the file if it's already open, which we know by the
# presence of self._file
if hasattr(self, '_file'):
self.close()
del self.file
self.storage.delete(self.name)
self.name = None
setattr(self.instance, self.field.name, self.name)
# Delete the filesize cache
if hasattr(self, '_size'):
del self._size
self._committed = False
if save:
self.instance.save()
delete.alters_data = True
def _get_closed(self):
file = getattr(self, '_file', None)
return file is None or file.closed
closed = property(_get_closed)
def close(self):
file = getattr(self, '_file', None)
if file is not None:
file.close()
def __getstate__(self):
# FieldFile needs access to its associated model field and an instance
# it's attached to in order to work properly, but the only necessary
# data to be pickled is the file's name itself. Everything else will
# be restored later, by FileDescriptor below.
return {'name': self.name, 'closed': False, '_committed': True, '_file': None}
class FileDescriptor(object):
"""
The descriptor for the file attribute on the model instance. Returns a
FieldFile when accessed so you can do stuff like::
>>> from myapp.models import MyModel
>>> instance = MyModel.objects.get(pk=1)
>>> instance.file.size
Assigns a file object on assignment so you can do::
>>> with open('/tmp/hello.world', 'r') as f:
... instance.file = File(f)
"""
def __init__(self, field):
self.field = field
def __get__(self, instance=None, owner=None):
if instance is None:
raise AttributeError(
"The '%s' attribute can only be accessed from %s instances."
% (self.field.name, owner.__name__))
# This is slightly complicated, so worth an explanation.
# instance.file`needs to ultimately return some instance of `File`,
# probably a subclass. Additionally, this returned object needs to have
# the FieldFile API so that users can easily do things like
# instance.file.path and have that delegated to the file storage engine.
# Easy enough if we're strict about assignment in __set__, but if you
# peek below you can see that we're not. So depending on the current
# value of the field we have to dynamically construct some sort of
# "thing" to return.
# The instance dict contains whatever was originally assigned
# in __set__.
file = instance.__dict__[self.field.name]
# If this value is a string (instance.file = "path/to/file") or None
# then we simply wrap it with the appropriate attribute class according
# to the file field. [This is FieldFile for FileFields and
# ImageFieldFile for ImageFields; it's also conceivable that user
# subclasses might also want to subclass the attribute class]. This
# object understands how to convert a path to a file, and also how to
# handle None.
if isinstance(file, six.string_types) or file is None:
attr = self.field.attr_class(instance, self.field, file)
instance.__dict__[self.field.name] = attr
# Other types of files may be assigned as well, but they need to have
# the FieldFile interface added to them. Thus, we wrap any other type of
# File inside a FieldFile (well, the field's attr_class, which is
# usually FieldFile).
elif isinstance(file, File) and not isinstance(file, FieldFile):
file_copy = self.field.attr_class(instance, self.field, file.name)
file_copy.file = file
file_copy._committed = False
instance.__dict__[self.field.name] = file_copy
# Finally, because of the (some would say boneheaded) way pickle works,
# the underlying FieldFile might not actually itself have an associated
# file. So we need to reset the details of the FieldFile in those cases.
elif isinstance(file, FieldFile) and not hasattr(file, 'field'):
file.instance = instance
file.field = self.field
file.storage = self.field.storage
# That was fun, wasn't it?
return instance.__dict__[self.field.name]
def __set__(self, instance, value):
instance.__dict__[self.field.name] = value
class FileField(Field):
# The class to wrap instance attributes in. Accessing the file object off
# the instance will always return an instance of attr_class.
attr_class = FieldFile
# The descriptor to use for accessing the attribute off of the class.
descriptor_class = FileDescriptor
description = _("File")
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
self._primary_key_set_explicitly = 'primary_key' in kwargs
self._unique_set_explicitly = 'unique' in kwargs
self.storage = storage or default_storage
self.upload_to = upload_to
kwargs['max_length'] = kwargs.get('max_length', 100)
super(FileField, self).__init__(verbose_name, name, **kwargs)
def check(self, **kwargs):
errors = super(FileField, self).check(**kwargs)
errors.extend(self._check_unique())
errors.extend(self._check_primary_key())
return errors
def _check_unique(self):
if self._unique_set_explicitly:
return [
checks.Error(
"'unique' is not a valid argument for a %s." % self.__class__.__name__,
hint=None,
obj=self,
id='fields.E200',
)
]
else:
return []
def _check_primary_key(self):
if self._primary_key_set_explicitly:
return [
checks.Error(
"'primary_key' is not a valid argument for a %s." % self.__class__.__name__,
hint=None,
obj=self,
id='fields.E201',
)
]
else:
return []
def deconstruct(self):
name, path, args, kwargs = super(FileField, self).deconstruct()
if kwargs.get("max_length") == 100:
del kwargs["max_length"]
kwargs['upload_to'] = self.upload_to
if self.storage is not default_storage:
kwargs['storage'] = self.storage
return name, path, args, kwargs
def get_internal_type(self):
return "FileField"
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, 'name'):
value = value.name
return super(FileField, self).get_prep_lookup(lookup_type, value)
def get_prep_value(self, value):
"Returns field's value prepared for saving into a database."
value = super(FileField, self).get_prep_value(value)
# Need to convert File objects provided via a form to unicode for database insertion
if value is None:
return None
return six.text_type(value)
def pre_save(self, model_instance, add):
"Returns field's value just before saving."
file = super(FileField, self).pre_save(model_instance, add)
if file and not file._committed:
# Commit the file to storage prior to saving the model
file.save(file.name, file, save=False)
return file
def contribute_to_class(self, cls, name, **kwargs):
super(FileField, self).contribute_to_class(cls, name, **kwargs)
setattr(cls, self.name, self.descriptor_class(self))
def get_directory_name(self):
return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
def get_filename(self, filename):
return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
def generate_filename(self, instance, filename):
# If upload_to is a callable, make sure that the path it returns is
# passed through get_valid_name() of the underlying storage.
if callable(self.upload_to):
directory_name, filename = os.path.split(self.upload_to(instance, filename))
filename = self.storage.get_valid_name(filename)
return os.path.normpath(os.path.join(directory_name, filename))
return os.path.join(self.get_directory_name(), self.get_filename(filename))
def save_form_data(self, instance, data):
# Important: None means "no change", other false value means "clear"
# This subtle distinction (rather than a more explicit marker) is
# needed because we need to consume values that are also sane for a
# regular (non Model-) Form to find in its cleaned_data dictionary.
if data is not None:
# This value will be converted to unicode and stored in the
# database, so leaving False as-is is not acceptable.
if not data:
data = ''
setattr(instance, self.name, data)
def formfield(self, **kwargs):
defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
# If a file has been provided previously, then the form doesn't require
# that a new file is provided this time.
# The code to mark the form field as not required is used by
# form_for_instance, but can probably be removed once form_for_instance
# is gone. ModelForm uses a different method to check for an existing file.
if 'initial' in kwargs:
defaults['required'] = False
defaults.update(kwargs)
return super(FileField, self).formfield(**defaults)
class ImageFileDescriptor(FileDescriptor):
"""
Just like the FileDescriptor, but for ImageFields. The only difference is
assigning the width/height to the width_field/height_field, if appropriate.
"""
def __set__(self, instance, value):
previous_file = instance.__dict__.get(self.field.name)
super(ImageFileDescriptor, self).__set__(instance, value)
# To prevent recalculating image dimensions when we are instantiating
# an object from the database (bug #11084), only update dimensions if
# the field had a value before this assignment. Since the default
# value for FileField subclasses is an instance of field.attr_class,
# previous_file will only be None when we are called from
# Model.__init__(). The ImageField.update_dimension_fields method
# hooked up to the post_init signal handles the Model.__init__() cases.
# Assignment happening outside of Model.__init__() will trigger the
# update right here.
if previous_file is not None:
self.field.update_dimension_fields(instance, force=True)
class ImageFieldFile(ImageFile, FieldFile):
def delete(self, save=True):
# Clear the image dimensions cache
if hasattr(self, '_dimensions_cache'):
del self._dimensions_cache
super(ImageFieldFile, self).delete(save)
class ImageField(FileField):
attr_class = ImageFieldFile
descriptor_class = ImageFileDescriptor
description = _("Image")
def __init__(self, verbose_name=None, name=None, width_field=None,
height_field=None, **kwargs):
self.width_field, self.height_field = width_field, height_field
super(ImageField, self).__init__(verbose_name, name, **kwargs)
def check(self, **kwargs):
errors = super(ImageField, self).check(**kwargs)
errors.extend(self._check_image_library_installed())
return errors
def _check_image_library_installed(self):
try:
from PIL import Image # NOQA
except ImportError:
return [
checks.Error(
'Cannot use ImageField because Pillow is not installed.',
hint=('Get Pillow at https://pypi.python.org/pypi/Pillow '
'or run command "pip install Pillow".'),
obj=self,
id='fields.E210',
)
]
else:
return []
def deconstruct(self):
name, path, args, kwargs = super(ImageField, self).deconstruct()
if self.width_field:
kwargs['width_field'] = self.width_field
if self.height_field:
kwargs['height_field'] = self.height_field
return name, path, args, kwargs
def contribute_to_class(self, cls, name, **kwargs):
super(ImageField, self).contribute_to_class(cls, name, **kwargs)
# Attach update_dimension_fields so that dimension fields declared
# after their corresponding image field don't stay cleared by
# Model.__init__, see bug #11196.
# Only run post-initialization dimension update on non-abstract models
if not cls._meta.abstract:
signals.post_init.connect(self.update_dimension_fields, sender=cls)
def update_dimension_fields(self, instance, force=False, *args, **kwargs):
"""
Updates field's width and height fields, if defined.
This method is hooked up to model's post_init signal to update
dimensions after instantiating a model instance. However, dimensions
won't be updated if the dimensions fields are already populated. This
avoids unnecessary recalculation when loading an object from the
database.
Dimensions can be forced to update with force=True, which is how
ImageFileDescriptor.__set__ calls this method.
"""
# Nothing to update if the field doesn't have dimension fields.
has_dimension_fields = self.width_field or self.height_field
if not has_dimension_fields:
return
# getattr will call the ImageFileDescriptor's __get__ method, which
# coerces the assigned value into an instance of self.attr_class
# (ImageFieldFile in this case).
file = getattr(instance, self.attname)
# Nothing to update if we have no file and not being forced to update.
if not file and not force:
return
dimension_fields_filled = not(
(self.width_field and not getattr(instance, self.width_field))
or (self.height_field and not getattr(instance, self.height_field))
)
# When both dimension fields have values, we are most likely loading
# data from the database or updating an image field that already had
# an image stored. In the first case, we don't want to update the
# dimension fields because we are already getting their values from the
# database. In the second case, we do want to update the dimensions
# fields and will skip this return because force will be True since we
# were called from ImageFileDescriptor.__set__.
if dimension_fields_filled and not force:
return
# file should be an instance of ImageFieldFile or should be None.
if file:
width = file.width
height = file.height
else:
# No file, so clear dimensions fields.
width = None
height = None
# Update the width and height fields.
if self.width_field:
setattr(instance, self.width_field, width)
if self.height_field:
setattr(instance, self.height_field, height)
def formfield(self, **kwargs):
defaults = {'form_class': forms.ImageField}
defaults.update(kwargs)
return super(ImageField, self).formfield(**defaults)
|
beagles/neutron_hacking | refs/heads/neutron_oslo_messaging | neutron/plugins/vmware/nsxlib/lsn.py | 7 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 VMware, Inc.
# All Rights Reserved
#
# 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 json
from neutron.common import exceptions as exception
from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path
from neutron.plugins.vmware.nsxlib import do_request
HTTP_GET = "GET"
HTTP_POST = "POST"
HTTP_DELETE = "DELETE"
HTTP_PUT = "PUT"
SERVICECLUSTER_RESOURCE = "service-cluster"
LSERVICESNODE_RESOURCE = "lservices-node"
LSERVICESNODEPORT_RESOURCE = "lport/%s" % LSERVICESNODE_RESOURCE
SUPPORTED_METADATA_OPTIONS = ['metadata_proxy_shared_secret']
LOG = log.getLogger(__name__)
def service_cluster_exists(cluster, svc_cluster_id):
exists = False
try:
exists = (
svc_cluster_id and
do_request(HTTP_GET,
_build_uri_path(SERVICECLUSTER_RESOURCE,
resource_id=svc_cluster_id),
cluster=cluster) is not None)
except exception.NotFound:
pass
return exists
def lsn_for_network_create(cluster, network_id):
lsn_obj = {
"service_cluster_uuid": cluster.default_service_cluster_uuid,
"tags": utils.get_tags(n_network_id=network_id)
}
return do_request(HTTP_POST,
_build_uri_path(LSERVICESNODE_RESOURCE),
json.dumps(lsn_obj),
cluster=cluster)["uuid"]
def lsn_for_network_get(cluster, network_id):
filters = {"tag": network_id, "tag_scope": "n_network_id"}
results = do_request(HTTP_GET,
_build_uri_path(LSERVICESNODE_RESOURCE,
fields="uuid",
filters=filters),
cluster=cluster)['results']
if not results:
raise exception.NotFound()
elif len(results) == 1:
return results[0]['uuid']
def lsn_delete(cluster, lsn_id):
do_request(HTTP_DELETE,
_build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id),
cluster=cluster)
def lsn_port_host_entries_update(
cluster, lsn_id, lsn_port_id, conf, hosts_data):
hosts_obj = {'hosts': hosts_data}
do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id,
extra_action=conf),
json.dumps(hosts_obj),
cluster=cluster)
def lsn_port_create(cluster, lsn_id, port_data):
port_obj = {
"ip_address": port_data["ip_address"],
"mac_address": port_data["mac_address"],
"tags": utils.get_tags(n_mac_address=port_data["mac_address"],
n_subnet_id=port_data["subnet_id"]),
"type": "LogicalServicesNodePortConfig",
}
return do_request(HTTP_POST,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id),
json.dumps(port_obj),
cluster=cluster)["uuid"]
def lsn_port_delete(cluster, lsn_id, lsn_port_id):
return do_request(HTTP_DELETE,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id),
cluster=cluster)
def _lsn_port_get(cluster, lsn_id, filters):
results = do_request(HTTP_GET,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
fields="uuid",
filters=filters),
cluster=cluster)['results']
if not results:
raise exception.NotFound()
elif len(results) == 1:
return results[0]['uuid']
def lsn_port_by_mac_get(cluster, lsn_id, mac_address):
filters = {"tag": mac_address, "tag_scope": "n_mac_address"}
return _lsn_port_get(cluster, lsn_id, filters)
def lsn_port_by_subnet_get(cluster, lsn_id, subnet_id):
filters = {"tag": subnet_id, "tag_scope": "n_subnet_id"}
return _lsn_port_get(cluster, lsn_id, filters)
def lsn_port_info_get(cluster, lsn_id, lsn_port_id):
result = do_request(HTTP_GET,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id),
cluster=cluster)
for tag in result['tags']:
if tag['scope'] == 'n_subnet_id':
result['subnet_id'] = tag['tag']
break
return result
def lsn_port_plug_network(cluster, lsn_id, lsn_port_id, lswitch_port_id):
patch_obj = {
"type": "PatchAttachment",
"peer_port_uuid": lswitch_port_id
}
try:
do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id,
is_attachment=True),
json.dumps(patch_obj),
cluster=cluster)
except api_exc.Conflict:
# This restriction might be lifted at some point
msg = (_("Attempt to plug Logical Services Node %(lsn)s into "
"network with port %(port)s failed. PatchAttachment "
"already exists with another port") %
{'lsn': lsn_id, 'port': lswitch_port_id})
LOG.exception(msg)
raise nsx_exc.LsnConfigurationConflict(lsn_id=lsn_id)
def _lsn_configure_action(
cluster, lsn_id, action, is_enabled, obj):
lsn_obj = {"enabled": is_enabled}
lsn_obj.update(obj)
do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id,
extra_action=action),
json.dumps(lsn_obj),
cluster=cluster)
def _lsn_port_configure_action(
cluster, lsn_id, lsn_port_id, action, is_enabled, obj):
do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id,
extra_action=action),
json.dumps({"enabled": is_enabled}),
cluster=cluster)
do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id,
extra_action=action),
json.dumps(obj),
cluster=cluster)
def lsn_port_dhcp_configure(
cluster, lsn_id, lsn_port_id, is_enabled=True, dhcp_options=None):
dhcp_options = dhcp_options or {}
opts = ["%s=%s" % (key, val) for key, val in dhcp_options.iteritems()]
dhcp_obj = {
'options': {'options': opts}
}
_lsn_port_configure_action(
cluster, lsn_id, lsn_port_id, 'dhcp', is_enabled, dhcp_obj)
def lsn_metadata_configure(
cluster, lsn_id, is_enabled=True, metadata_info=None):
opts = [
"%s=%s" % (opt, metadata_info[opt])
for opt in SUPPORTED_METADATA_OPTIONS
if metadata_info.get(opt)
]
meta_obj = {
'metadata_server_ip': metadata_info['metadata_server_ip'],
'metadata_server_port': metadata_info['metadata_server_port'],
'misc_options': opts
}
_lsn_configure_action(
cluster, lsn_id, 'metadata-proxy', is_enabled, meta_obj)
def _lsn_port_host_action(
cluster, lsn_id, lsn_port_id, host_obj, extra_action, action):
do_request(HTTP_POST,
_build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id,
resource_id=lsn_port_id,
extra_action=extra_action,
filters={"action": action}),
json.dumps(host_obj),
cluster=cluster)
def lsn_port_dhcp_host_add(cluster, lsn_id, lsn_port_id, host_data):
_lsn_port_host_action(
cluster, lsn_id, lsn_port_id, host_data, 'dhcp', 'add_host')
def lsn_port_dhcp_host_remove(cluster, lsn_id, lsn_port_id, host_data):
_lsn_port_host_action(
cluster, lsn_id, lsn_port_id, host_data, 'dhcp', 'remove_host')
def lsn_port_metadata_host_add(cluster, lsn_id, lsn_port_id, host_data):
_lsn_port_host_action(
cluster, lsn_id, lsn_port_id, host_data, 'metadata-proxy', 'add_host')
def lsn_port_metadata_host_remove(cluster, lsn_id, lsn_port_id, host_data):
_lsn_port_host_action(cluster, lsn_id, lsn_port_id,
host_data, 'metadata-proxy', 'remove_host')
|
thaumos/ansible | refs/heads/devel | lib/ansible/module_utils/database.py | 50 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c) 2014, Toshio Kuratomi <tkuratomi@ansible.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SQLParseError(Exception):
pass
class UnclosedQuoteError(SQLParseError):
pass
# maps a type of identifier to the maximum number of dot levels that are
# allowed to specify that identifier. For example, a database column can be
# specified by up to 4 levels: database.schema.table.column
_PG_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, schema=2, table=3, column=4, role=1)
_MYSQL_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, table=2, column=3, role=1, vars=1)
def _find_end_quote(identifier, quote_char):
accumulate = 0
while True:
try:
quote = identifier.index(quote_char)
except ValueError:
raise UnclosedQuoteError
accumulate = accumulate + quote
try:
next_char = identifier[quote + 1]
except IndexError:
return accumulate
if next_char == quote_char:
try:
identifier = identifier[quote + 2:]
accumulate = accumulate + 2
except IndexError:
raise UnclosedQuoteError
else:
return accumulate
def _identifier_parse(identifier, quote_char):
if not identifier:
raise SQLParseError('Identifier name unspecified or unquoted trailing dot')
already_quoted = False
if identifier.startswith(quote_char):
already_quoted = True
try:
end_quote = _find_end_quote(identifier[1:], quote_char=quote_char) + 1
except UnclosedQuoteError:
already_quoted = False
else:
if end_quote < len(identifier) - 1:
if identifier[end_quote + 1] == '.':
dot = end_quote + 1
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
further_identifiers.insert(0, first_identifier)
else:
raise SQLParseError('User escaped identifiers must escape extra quotes')
else:
further_identifiers = [identifier]
if not already_quoted:
try:
dot = identifier.index('.')
except ValueError:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
if dot == 0 or dot >= len(identifier) - 1:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
first_identifier = first_identifier.replace(quote_char, quote_char * 2)
first_identifier = ''.join((quote_char, first_identifier, quote_char))
further_identifiers.insert(0, first_identifier)
return further_identifiers
def pg_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='"')
if len(identifier_fragments) > _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('PostgreSQL does not support %s with more than %i dots' % (id_type, _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]))
return '.'.join(identifier_fragments)
def mysql_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='`')
if len(identifier_fragments) > _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('MySQL does not support %s with more than %i dots' % (id_type, _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]))
special_cased_fragments = []
for fragment in identifier_fragments:
if fragment == '`*`':
special_cased_fragments.append('*')
else:
special_cased_fragments.append(fragment)
return '.'.join(special_cased_fragments)
|
AwesomeTurtle/personfinder | refs/heads/master | tools/merge_messages.py | 17 | #!/usr/bin/env python
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Merge translations from a set of .po or XMB files into a set of .po files.
Usage:
../tools/merge_messages <source-dir> <template-file>
../tools/merge_messages <source-dir> <template-file> <target-dir>
../tools/merge_messages <source-po-file> <template-file> <target-po-file>
<source-dir> should be a directory containing a subdirectories named with
locale codes (e.g. pt_BR). For each locale, this script looks for the first
.po or .xml file it finds anywhere under <source-dir>/<locale-code>/ and
adds all its messages and translations to the corresponding django.po file
in the target directory, at <target-dir>/<locale-code>/LC_MESSAGES/django.po.
<template-file> is the output file from running:
'find_missing_translations --format=po'
With the name that corresponds to the --format=xmb output.
Make sure to run this in a tree that corresponds to the version used for
generating the xmb file or the resulting merge will be wrong. See
validate_merge for directions on verifying the merge was correct.
If <target-dir> is unspecified, it defaults to the app/locale directory of
the current app. Alternatively, you can specify a single source file and
a single target file to update.
When merging messages from a source file into a target file:
- Empty messages and messages marked "fuzzy" in the source file are ignored.
- Translations in the source file will replace any existing translations
for the same messages in the target file.
- Other translations in the source file will be added to the target file.
- If the target file doesn't exist, it will be created.
- To minimize unnecessary changes from version to version, the target file
has no "#: filename:line" comments and the messages are sorted by msgid.
"""
import babel.messages
from babel.messages import pofile
import codecs
import os
import sys
import xml.sax
class XmbCatalogReader(xml.sax.handler.ContentHandler):
"""A SAX handler that populates a babel.messages.Catalog with messages
read from an XMB file."""
def __init__(self, template):
"""template should be a Catalog containing the untranslated messages
in the same order as the corresponding messages in the XMB file."""
self.tags = []
self.catalog = babel.messages.Catalog()
self.iter = iter(template)
assert self.iter.next().id == '' # skip the blank metadata message
def startElement(self, tag, attrs):
self.tags.append(tag)
if tag == 'msg':
self.string = ''
self.message = babel.messages.Message(self.iter.next().id)
if tag == 'ph':
self.string += '%(' + attrs['name'] + ')s'
self.message.flags.add('python-format')
def endElement(self, tag):
assert self.tags.pop() == tag
if tag == 'msg':
self.message.string = self.string
self.catalog[self.message.id] = self.message
def characters(self, content):
if self.tags[-1] == 'msg':
self.string += content
def log(text):
"""Prints out Unicode text."""
print text.encode('utf-8')
def log_change(old_message, new_message):
"""Describes an update to a message."""
if not old_message:
if new_message.id:
log('+ msgid "%s"' % str(new_message.id))
else:
print >>sys.stderr, 'no message id: %s' % new_message
log('+ msgstr "%s"' % str(new_message.string.encode('ascii', 'ignore')))
if new_message.flags:
log('+ #, %s' % ', '.join(sorted(new_message.flags)))
else:
if (new_message.string != old_message.string or
new_message.flags != old_message.flags):
log(' msgid "%s"' % old_message.id)
log('- msgstr "%s"' % old_message.string)
if old_message.flags:
log('- #, %s' % ', '.join(sorted(old_message.flags)))
log('+ msgstr "%s"' % new_message.string)
if new_message.flags:
log('+ #, %s' % ', '.join(sorted(new_message.flags)))
def create_file(filename):
"""Opens a file for writing, creating any necessary parent directories."""
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
return open(filename, 'w')
def merge(source, target_filename):
"""Merges the messages from the source Catalog into a .po file at
target_filename. Creates the target file if it doesn't exist."""
if os.path.exists(target_filename):
target = pofile.read_po(open(target_filename))
for message in source:
if message.id and message.string and not message.fuzzy:
log_change(message.id in target and target[message.id], message)
# This doesn't actually replace the message! It just updates
# the fields other than the string. See Catalog.__setitem__.
target[message.id] = message
# We have to mutate the message to update the string and flags.
target[message.id].string = message.string
target[message.id].flags = message.flags
else:
for message in source:
log_change(None, message)
target = source
target_file = create_file(target_filename)
pofile.write_po(target_file, target,
no_location=True, sort_output=True, ignore_obsolete=True)
target_file.close()
def merge_file(source_filename, target_filename, template_filename):
if source_filename.endswith('.po'):
merge(pofile.read_po(open(source_filename)), target_filename)
elif source_filename.endswith('.xml'):
handler = XmbCatalogReader(pofile.read_po(open(template_filename)))
xml.sax.parse(open(source_filename), handler)
merge(handler.catalog, target_filename)
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) not in [1, 2, 3]:
print __doc__
sys.exit(1)
args = (args + [None, None])[:3]
source_path = args[0]
template_path = args[1]
target_path = args[2] or os.path.join(os.environ['APP_DIR'], 'locale')
# If a single file is specified, merge it.
if ((source_path.endswith('.po') or source_path.endswith('.xml')) and
target_path.endswith('.po')):
print target_path
merge_file(source_path, target_path, template_path)
sys.exit(0)
# Otherwise, we expect two directories.
if not os.path.isdir(source_path) or not os.path.isdir(target_path):
print __doc__
sys.exit(1)
# Find all the source files.
source_filenames = {} # {locale: po_filename}
def find_po_file(key, dir, filenames):
"""Looks for a .po file and records it in source_filenames."""
for filename in filenames:
if filename.endswith('.po') or filename.endswith('.xml'):
source_filenames[key] = os.path.join(dir, filename)
for locale in os.listdir(source_path):
os.path.walk(os.path.join(source_path, locale), find_po_file,
locale.replace('-', '_'))
# Merge them into the target files.
for locale in sorted(source_filenames.keys()):
target = os.path.join(target_path, locale, 'LC_MESSAGES', 'django.po')
print target
merge_file(source_filenames[locale], target, template_path)
|
tectronics/lastfmtagextractor | refs/heads/master | lastfmtagextractor/__init__.py | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
lastfmtagextractor/__init__.py
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
@author: Aaron McKee (ucbmckee)
v0.61 : May. 2012
'''
from .config import LastFM_Config
from .medialibrary import MediaLibrary
import common
|
PLNech/thefuck | refs/heads/master | thefuck/rules/git_push_pull.py | 3 | from thefuck.shells import shell
from thefuck.utils import replace_argument
from thefuck.specific.git import git_support
@git_support
def match(command):
return ('push' in command.script
and '! [rejected]' in command.stderr
and 'failed to push some refs to' in command.stderr
and 'Updates were rejected because the tip of your current branch is behind' in command.stderr)
@git_support
def get_new_command(command):
return shell.and_(replace_argument(command.script, 'push', 'pull'),
command.script)
|
ChatAI/dumbots | refs/heads/master | bots/TriviaBot/lib/file_parser.py | 1 | import numpy as np
import hickle as hkl
from os import walk
def file2list ( category ) :
prefix = "data/"
category = prefix + category
file = open( category )
listofcontents = []
choicelist = []
contents ={}
linenumber=0
for line in file:
if line.startswith('#'):
contents['ques'] = line[2:]
linenumber += 1
elif line.startswith('^'):
contents['ans']= line[2:]
linenumber += 1
elif line[0] in ['A','B','C','D']:
choicelist.append(line[2:])
linenumber += 1
if line.startswith('D'):
choicelist.sort()
contents['ansnum'] = choicelist.index(contents['ans'])
choicestring = ""
for i in range(len(choicelist)):
choicestring += "[" + str(i) + "] " + choicelist[i] + " "
contents["choices"] = choicestring
listofcontents.append(contents)
#print "Line :",linenumber,"question : ",contents["ques"],"answer :",contents['ansnum'],contents["ans"],"choice :",contents["choices"]
choicelist = []
contents = {}
return listofcontents
# pick a category
mypath = "../data"
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
files.extend(filenames)
break
for file in files:
print "converting the category",file
l = file2list(file)
# hickle name
hkl_name = "../data/hkldata/"+file+'.hkl'
# save as hickle
hkl.dump(l,hkl_name)
|
ravindrasingh22/ansible | refs/heads/devel | test/units/parsing/yaml/__init__.py | 12133432 | |
marratj/ansible | refs/heads/devel | test/units/modules/cloud/amazon/__init__.py | 12133432 | |
jeffjose/whartonapi | refs/heads/master | gsr.py | 1 | #!/usr/bin/python
#
# Jeffrey Jose | November 16, 2015
#
# Wharton Group Study Rooms (GSR) API
import sys, os
import requests
import getpass
import simplejson as json
import datetime
import auth
API = 'https://webapps.wharton.upenn.edu/whartonm/index.cfm/api/v1/'
# Wrapper around request.<httpmethod>
def req(method, url, *args, **kwargs):
response = getattr(requests, method)(url, *args, **kwargs)
text = json.loads(response.text)
if 'error' in text:
# Looks like there was an error
raise ValueError('Error communicating with the API')
return text, response
def api_get(endpoint, token, *args, **kwargs):
'''
Wrapper for request.get
'''
return req('get', "%s/%s?token=%s" % (API, endpoint, token), *args, **kwargs)
def api_post(endpoint, token, *args, **kwargs):
'''
Wrapper for request.post
'''
return req('post', "%s/%s?token=%s" % (API, endpoint, token), *args, **kwargs)
def api_put(endpoint, token, *args, **kwargs):
'''
Wrapper for request.put
'''
return req('put', "%s/%s?token=%s" % (API, endpoint, token), *args, **kwargs)
def api_delete(endpoint, token, *args, **kwargs):
'''
Wrapper for request.delete
'''
return req('delete', "%s/%s?token=%s" % (API, endpoint, token), *args, **kwargs)
def _parse_reservations(details):
'''
Massage the incoming reservation data packet
'''
for x in details:
x['startTime'] = datetime.datetime.fromtimestamp(float(x['startTime']))
return details
def get_locations(token):
'''
Get all the locations at Wharton. JMHH F/G/2/3 and 2401, almost always.
'''
locations, _ = api_get('gsr/locations', token)
return locations
def get_reservations(token):
'''
Get all reservation associated with the user identified by the `token`
'''
details, _ = api_get('gsr/reservations', token)
reservations = _parse_reservations(details)
return reservations
def create_reservations(token, data):
'''
Create GSR Reservation for this particular user identified by the `token`
`data` is a list of dicts of the format
{
'startTime' : <timestamp>,
'subjectLine': <str>,
'duration' : (30|60|90),
'roomId' : <str:room_id>
}
'''
# Since we're gonna modify `startTime` parameter, make a copy
data = copy.copy(data)
for d in data:
d['startTime'] = time.mktime(d['startTime'].timetuple())
text, response = api_post('gsr/reservations', token, data = d)
def delete_reservations(token, ids):
'''
Delete GSR Reservations with `ids` of the user (`token`)
Takes a list of `reservationId`s
'''
for _id in ids:
d = {'reservationId': _id}
text, response = api_delete('gsr/reservations', token, data = d)
if __name__ == '__main__':
username = raw_input('Enter your UPenn login: ')
password = getpass.getpass('Password for %s: ' % username)
token = auth.get_token(username, password)
locations = get_locations(token)
reservations = get_reservations(token)
delete_reservations(token, [x['reservationId'] for x in reservations])
|
Charleo85/SIS-Rebuild | refs/heads/master | webv2/web/urls.py | 1 | """web URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from . import views
statics = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
webv2 = [
url(r'^$', views.home_page, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^department/(?P<specific_department>[a-zA-Z-]{0,30})/$', views.department_view),
url(r'^course/(?P<mnemonic>[a-zA-Z]{1,4})(?P<number>[0-9]{4})/', views.course_detail),
# Need section detail!
]
# ###############################
# misc = [
# url(r'^admin/', include(admin.site.urls)),
# # url(r'^$', views.home_page, name='home'),
# # url(r'^about/$', views.about, name='about'),
# url(r'^search/$', views.search_page, name='search_page'),
# ]
#
# course = [
# url(
# r'^course/$', views.list_item,
# { 'modelname' : 'course' }, name='course_list',
# ),
# url(
# r'^course/detail/(?P<itemid>[0-9]{5})/$',
# views.item_detail, { 'modelname' : 'course' }, name='course_detail',
# ),
# url(
# r'^course/create/$', views.create_course_listing,
# { 'modelname' : 'course' }, name='course_create',
# ),
# ]
#
# ins = [
# url(
# r'^instructor/$', views.list_item,
# { 'modelname' : 'instructor' }, name='instructor_list'
# ),
# url(
# r'^instructor/detail/(?P<itemid>[a-zA-Z0-9]+)/$',
# views.item_detail, { 'modelname' : 'instructor' },
# name='instructor_detail',
# ),
# url(
# r'^instructor/login/$',
# views.login, { 'modelname' : 'instructor' },
# name='instructor_login',
# ),
# url(
# r'^instructor/profile/$',
# views.instructor_profile, name='instructor_profile',
# ),
# url(
# r'^instructor/logout/$',
# views.logout, { 'modelname' : 'instructor' },
# name='instructor_logout',
# ),
# url(
# r'^instructor/signup/$',
# views.signup, { 'modelname' : 'instructor' },
# name='instructor_signup',
# ),
# ]
#
# stud = [
# url(
# r'^student/login/$',
# views.login, { 'modelname' : 'student' },
# name='student_login',
# ),
# url(
# r'^student/profile/$',
# views.student_profile, name='student_profile',
# ),
# url(
# r'^student/logout/$',
# views.logout, { 'modelname' : 'student' },
# name='student_logout',
# ),
# url(
# r'^student/signup/$',
# views.signup, { 'modelname' : 'student' },
# name='student_signup',
# ),
# ]
urlpatterns = webv2 + statics # + misc + course + ins + stud
|
ghandiosm/Test | refs/heads/master | addons/website_mail_channel/models/mail_mail.py | 46 | # -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp import tools
from openerp.tools.translate import _
from openerp.addons.website.models.website import slug
class MailMail(osv.Model):
_inherit = 'mail.mail'
def send_get_mail_body(self, cr, uid, ids, partner=None, context=None):
""" Short-circuit parent method for mail groups, replace the default
footer with one appropriate for mailing-lists."""
# TDE: temporary addition (mail was parameter) due to semi-new-API
mail = self.browse(cr, uid, ids[0], context=context)
if mail.model == 'mail.channel' and mail.res_id:
# no super() call on purpose, no private links that could be quoted!
channel = self.pool['mail.channel'].browse(cr, uid, mail.res_id, context=context)
base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
vals = {
'maillist': _('Mailing-List'),
'post_to': _('Post to'),
'unsub': _('Unsubscribe'),
'mailto': 'mailto:%s@%s' % (channel.alias_name, channel.alias_domain),
'group_url': '%s/groups/%s' % (base_url, slug(channel)),
'unsub_url': '%s/groups?unsubscribe' % (base_url,),
}
footer = """_______________________________________________
%(maillist)s: %(group_url)s
%(post_to)s: %(mailto)s
%(unsub)s: %(unsub_url)s
""" % vals
body = tools.append_content_to_html(mail.body, footer, container_tag='div')
return body
else:
return super(MailMail, self).send_get_mail_body(cr, uid, ids, partner=partner, context=context)
|
epam-mooc/edx-platform | refs/heads/master | common/test/acceptance/tests/helpers.py | 9 | """
Test helper functions and base classes.
"""
import json
import unittest
import functools
import requests
from path import path
from bok_choy.web_app_test import WebAppTest
def skip_if_browser(browser):
"""
Method decorator that skips a test if browser is `browser`
Args:
browser (str): name of internet browser
Returns:
Decorated function
"""
def decorator(test_function):
@functools.wraps(test_function)
def wrapper(self, *args, **kwargs):
if self.browser.name == browser:
raise unittest.SkipTest('Skipping as this test will not work with {}'.format(browser))
test_function(self, *args, **kwargs)
return wrapper
return decorator
def is_youtube_available():
"""
Check if the required youtube urls are available.
If a URL in `youtube_api_urls` is not reachable then subsequent URLs will not be checked.
Returns:
bool:
"""
youtube_api_urls = {
'main': 'https://www.youtube.com/',
'player': 'http://www.youtube.com/iframe_api',
'metadata': 'http://gdata.youtube.com/feeds/api/videos/',
# For transcripts, you need to check an actual video, so we will
# just specify our default video and see if that one is available.
'transcript': 'http://video.google.com/timedtext?lang=en&v=OEoXaMPEzfM',
}
for url in youtube_api_urls.itervalues():
try:
response = requests.get(url, allow_redirects=False)
except requests.exceptions.ConnectionError:
return False
if response.status_code >= 300:
return False
return True
def load_data_str(rel_path):
"""
Load a file from the "data" directory as a string.
`rel_path` is the path relative to the data directory.
"""
full_path = path(__file__).abspath().dirname() / "data" / rel_path # pylint: disable=E1120
with open(full_path) as data_file:
return data_file.read()
def disable_animations(page):
"""
Disable jQuery and CSS3 animations.
"""
disable_jquery_animations(page)
disable_css_animations(page)
def enable_animations(page):
"""
Enable jQuery and CSS3 animations.
"""
enable_jquery_animations(page)
enable_css_animations(page)
def disable_jquery_animations(page):
"""
Disable jQuery animations.
"""
page.browser.execute_script("jQuery.fx.off = true;")
def enable_jquery_animations(page):
"""
Enable jQuery animations.
"""
page.browser.execute_script("jQuery.fx.off = false;")
def disable_css_animations(page):
"""
Disable CSS3 animations, transitions, transforms.
"""
page.browser.execute_script("""
var id = 'no-transitions';
// if styles were already added, just do nothing.
if (document.getElementById(id)) {
return;
}
var css = [
'* {',
'-webkit-transition: none !important;',
'-moz-transition: none !important;',
'-o-transition: none !important;',
'-ms-transition: none !important;',
'transition: none !important;',
'-webkit-transition-property: none !important;',
'-moz-transition-property: none !important;',
'-o-transition-property: none !important;',
'-ms-transition-property: none !important;',
'transition-property: none !important;',
'-webkit-transform: none !important;',
'-moz-transform: none !important;',
'-o-transform: none !important;',
'-ms-transform: none !important;',
'transform: none !important;',
'-webkit-animation: none !important;',
'-moz-animation: none !important;',
'-o-animation: none !important;',
'-ms-animation: none !important;',
'animation: none !important;',
'}'
].join(''),
head = document.head || document.getElementsByTagName('head')[0],
styles = document.createElement('style');
styles.id = id;
styles.type = 'text/css';
if (styles.styleSheet){
styles.styleSheet.cssText = css;
} else {
styles.appendChild(document.createTextNode(css));
}
head.appendChild(styles);
""")
def enable_css_animations(page):
"""
Enable CSS3 animations, transitions, transforms.
"""
page.browser.execute_script("""
var styles = document.getElementById('no-transitions'),
head = document.head || document.getElementsByTagName('head')[0];
head.removeChild(styles)
""")
class UniqueCourseTest(WebAppTest):
"""
Test that provides a unique course ID.
"""
COURSE_ID_SEPARATOR = "/"
def __init__(self, *args, **kwargs):
"""
Create a unique course ID.
"""
super(UniqueCourseTest, self).__init__(*args, **kwargs)
def setUp(self):
super(UniqueCourseTest, self).setUp()
self.course_info = {
'org': 'test_org',
'number': self.unique_id,
'run': 'test_run',
'display_name': 'Test Course' + self.unique_id
}
@property
def course_id(self):
return self.COURSE_ID_SEPARATOR.join([
self.course_info['org'],
self.course_info['number'],
self.course_info['run']
])
class YouTubeConfigError(Exception):
"""
Error occurred while configuring YouTube Stub Server.
"""
pass
class YouTubeStubConfig(object):
"""
Configure YouTube Stub Server.
"""
PORT = 9080
URL = 'http://127.0.0.1:{}/'.format(PORT)
@classmethod
def configure(cls, config):
"""
Allow callers to configure the stub server using the /set_config URL.
Arguments:
config (dict): Configuration dictionary.
Raises:
YouTubeConfigError
"""
youtube_stub_config_url = cls.URL + 'set_config'
config_data = {param: json.dumps(value) for param, value in config.items()}
response = requests.put(youtube_stub_config_url, data=config_data)
if not response.ok:
raise YouTubeConfigError(
'YouTube Server Configuration Failed. URL {0}, Configuration Data: {1}, Status was {2}'.format(
youtube_stub_config_url, config, response.status_code))
@classmethod
def reset(cls):
"""
Reset YouTube Stub Server Configurations using the /del_config URL.
Raises:
YouTubeConfigError
"""
youtube_stub_config_url = cls.URL + 'del_config'
response = requests.delete(youtube_stub_config_url)
if not response.ok:
raise YouTubeConfigError(
'YouTube Server Configuration Failed. URL: {0} Status was {1}'.format(
youtube_stub_config_url, response.status_code))
@classmethod
def get_configuration(cls):
"""
Allow callers to get current stub server configuration.
Returns:
dict
"""
youtube_stub_config_url = cls.URL + 'get_config'
response = requests.get(youtube_stub_config_url)
if response.ok:
return json.loads(response.content)
else:
return {}
|
abide/django-windows-tools | refs/heads/master | django_windows_tools/management/commands/winservice_install.py | 1 | # encoding: utf-8
# Django command installing a Windows Service that runs Django commands
#
# Copyright (c) 2012 Openance
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
from __future__ import print_function
__author__ = 'Antoine Martin <antoine@openance.com>'
import os
import os.path
import logging
import sys
import re
import stat
import platform
from optparse import OptionParser
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import get_template
from django.template import Context
from django.conf import settings
from optparse import make_option
import subprocess
def set_file_readable(filename):
import win32api
import win32security
import ntsecuritycon as con
users = win32security.ConvertStringSidToSid("S-1-5-32-545")
admins = win32security.ConvertStringSidToSid("S-1-5-32-544")
user, domain, type = win32security.LookupAccountName ("", win32api.GetUserName ())
sd = win32security.GetFileSecurity (filename, win32security.DACL_SECURITY_INFORMATION)
dacl = win32security.ACL ()
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, users)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins)
sd.SetSecurityDescriptorDacl (1, dacl, 0)
win32security.SetFileSecurity (filename, win32security.DACL_SECURITY_INFORMATION, sd)
class Command(BaseCommand):
args = ''
help = '''Creates a NT Service that runs Django commands.
This command creates a service.py script and a service.ini
configuration file at the same level that the manage.py command.
The django commands configured in the service.ini file can
then be run as a Windows NT service by installing the service with
the command:
C:\project> python service.py --startup=auto install
It can be started with the command:
C:\project> python service.py start
It can be stopped and removed with one of the commands:
C:\project> python service.py stop
C:\project> python service.py remove
'''
option_list = BaseCommand.option_list + (
make_option('--service-name',
dest='service_name',
default='django-%s-service',
help='Name of the service (takes the name of the project by default'),
make_option('--display-name',
dest='display_name',
default='Django %s backround service',
help='Display name of the service'),
make_option('--service-script-name',
dest='service_script_name',
default='service.py',
help='Name of the service script (defaults to service.py)'),
make_option('--config-file-name',
dest='config_file_name',
default='service.ini',
help='Name of the service configuration file (defaults to service.ini)'),
make_option('--log-directory',
dest='log_directory',
default='d:\logs',
help='Location for log files (d:\logs by default)'),
make_option('--beat-machine',
dest='beat_machine',
default='BEATSERVER',
help='Name of the machine that will run the Beat scheduler'),
make_option('--beat',
action='store_true',
dest='is_beat',
default=False,
help='Use this machine as host for the beat scheduler'),
make_option('--overwrite',
action='store_true',
dest='overwrite',
default=False,
help='Overwrite existing files'),
)
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.current_script = os.path.abspath(sys.argv[0])
self.project_dir, self.script_name = os.path.split(self.current_script)
self.project_name = os.path.split(self.project_dir)[1]
def install_template(self, template, filename, overwrite=False, **kwargs):
full_path = os.path.join(self.project_dir, filename)
if os.path.exists(full_path) and not overwrite:
raise CommandError('The file %s already exists !' % full_path)
print("Creating %s " % full_path)
template = get_template(template)
file = open(full_path, 'w')
file.write(template.render(Context(kwargs)))
file.close()
set_file_readable(full_path)
def handle(self, *args, **options):
if self.script_name == 'django-admin.py':
raise CommandError("""\
This command does not work when used with django-admin.py.
Please run it with the manage.py of the root directory of your project.
""")
if "%s" in options['service_name']:
options['service_name'] = options['service_name'] % self.project_name
if "%s" in options['display_name']:
options['display_name'] = options['display_name'] % self.project_name
self.install_template(
'windows_tools/service/service.py',
options['service_script_name'],
options['overwrite'],
service_name = options['service_name'],
display_name = options['display_name'],
config_file_name = options['config_file_name'],
settings_module = os.environ['DJANGO_SETTINGS_MODULE'],
)
if options['is_beat']:
options['beat_machine'] = platform.node()
if options['log_directory'][-1:] == '\\':
options['log_directory'] = options['log_directory'][0:-1]
self.install_template(
'windows_tools/service/service.ini',
options['config_file_name'],
options['overwrite'],
log_directory = options['log_directory'],
beat_machine = options['beat_machine'],
config_file_name = options['config_file_name'],
settings_module = os.environ['DJANGO_SETTINGS_MODULE'],
)
if __name__ == '__main__':
print('This is supposed to be run as a django management command')
|
dimid/ansible-modules-extras | refs/heads/devel | cloud/amazon/ec2_snapshot_facts.py | 15 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: ec2_snapshot_facts
short_description: Gather facts about ec2 volume snapshots in AWS
description:
- Gather facts about ec2 volume snapshots in AWS
version_added: "2.1"
author: "Rob White (@wimnat)"
options:
snapshot_ids:
description:
- If you specify one or more snapshot IDs, only snapshots that have the specified IDs are returned.
required: false
default: []
owner_ids:
description:
- If you specify one or more snapshot owners, only snapshots from the specified owners and for which you have \
access are returned.
required: false
default: []
restorable_by_user_ids:
description:
- If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are \
returned.
required: false
default: []
filters:
description:
- A dict of filters to apply. Each dict item consists of a filter key and a filter value. See \
U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSnapshots.html) for possible filters. Filter \
names and values are case sensitive.
required: false
default: {}
notes:
- By default, the module will return all snapshots, including public ones. To limit results to snapshots owned by \
the account use the filter 'owner-id'.
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Gather facts about all snapshots, including public ones
- ec2_snapshot_facts:
# Gather facts about all snapshots owned by the account 0123456789
- ec2_snapshot_facts:
filters:
owner-id: 0123456789
# Or alternatively...
- ec2_snapshot_facts:
owner_ids:
- 0123456789
# Gather facts about a particular snapshot using ID
- ec2_snapshot_facts:
filters:
snapshot-id: snap-00112233
# Or alternatively...
- ec2_snapshot_facts:
snapshot_ids:
- snap-00112233
# Gather facts about any snapshot with a tag key Name and value Example
- ec2_snapshot_facts:
filters:
"tag:Name": Example
# Gather facts about any snapshot with an error status
- ec2_snapshot_facts:
filters:
status: error
'''
RETURN = '''
snapshot_id:
description: The ID of the snapshot. Each snapshot receives a unique identifier when it is created.
type: string
sample: snap-01234567
volume_id:
description: The ID of the volume that was used to create the snapshot.
type: string
sample: vol-01234567
state:
description: The snapshot state (completed, pending or error).
type: string
sample: completed
state_message:
description: Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred.
type: string
sample:
start_time:
description: The time stamp when the snapshot was initiated.
type: datetime
sample: 2015-02-12T02:14:02+00:00
progress:
description: The progress of the snapshot, as a percentage.
type: string
sample: 100%
owner_id:
description: The AWS account ID of the EBS snapshot owner.
type: string
sample: 099720109477
description:
description: The description for the snapshot.
type: string
sample: My important backup
volume_size:
description: The size of the volume, in GiB.
type: integer
sample: 8
owner_alias:
description: The AWS account alias (for example, amazon, self) or AWS account ID that owns the snapshot.
type: string
sample: 033440102211
tags:
description: Any tags assigned to the snapshot.
type: list
sample: "{ 'my_tag_key': 'my_tag_value' }"
encrypted:
description: Indicates whether the snapshot is encrypted.
type: boolean
sample: True
kms_key_id:
description: The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to \
protect the volume encryption key for the parent volume.
type: string
sample: 74c9742a-a1b2-45cb-b3fe-abcdef123456
data_encryption_key_id:
description: The data encryption key identifier for the snapshot. This value is a unique identifier that \
corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy.
type: string
sample: "arn:aws:kms:ap-southeast-2:012345678900:key/74c9742a-a1b2-45cb-b3fe-abcdef123456"
'''
try:
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (ansible_dict_to_boto3_filter_list,
boto3_conn, boto3_tag_list_to_ansible_dict, camel_dict_to_snake_dict,
ec2_argument_spec, get_aws_connection_info)
def list_ec2_snapshots(connection, module):
snapshot_ids = module.params.get("snapshot_ids")
owner_ids = module.params.get("owner_ids")
restorable_by_user_ids = module.params.get("restorable_by_user_ids")
filters = ansible_dict_to_boto3_filter_list(module.params.get("filters"))
try:
snapshots = connection.describe_snapshots(SnapshotIds=snapshot_ids, OwnerIds=owner_ids, RestorableByUserIds=restorable_by_user_ids, Filters=filters)
except ClientError as e:
module.fail_json(msg=e.message)
# Turn the boto3 result in to ansible_friendly_snaked_names
snaked_snapshots = []
for snapshot in snapshots['Snapshots']:
snaked_snapshots.append(camel_dict_to_snake_dict(snapshot))
# Turn the boto3 result in to ansible friendly tag dictionary
for snapshot in snaked_snapshots:
if 'tags' in snapshot:
snapshot['tags'] = boto3_tag_list_to_ansible_dict(snapshot['tags'])
module.exit_json(snapshots=snaked_snapshots)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
snapshot_ids=dict(default=[], type='list'),
owner_ids=dict(default=[], type='list'),
restorable_by_user_ids=dict(default=[], type='list'),
filters=dict(default={}, type='dict')
)
)
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=[
['snapshot_ids', 'owner_ids', 'restorable_by_user_ids', 'filters']
]
)
if not HAS_BOTO3:
module.fail_json(msg='boto3 required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
if region:
connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)
else:
module.fail_json(msg="region must be specified")
list_ec2_snapshots(connection, module)
if __name__ == '__main__':
main()
|
samuroi/SamuROI | refs/heads/develop | samuroi/util/mask_generator/manual_correction.py | 1 | __author__ = 'stephenlenzi'
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from . import create_masks
class ComCorrector(object):
def __init__(self, mask_generator, raw_image, image_2=None, image_3=None):
"""
:param mask_generator: uses mask_generator instance to plot graphs and allow user interaction/detection correction
:return:
example usage:
>>> mask_gen = create_masks.DonutCells(raw_image, blob_image, somata_image)
>>> ComCorrector(mask_gen)
To remove cells, click the plotted dots
To add cells, shift + click the desired cell location
When you are happy with your changes update the mask_generator object by pressing the 'u' key
"""
self.shift_is_held = False
self.mask_generator = mask_generator
self.fig = plt.figure(facecolor='w', figsize=(20, 20))
self.cmap = matplotlib.cm.jet_r
self.ax1 = self.fig.add_subplot(221)
self.image = self.ax1.imshow(raw_image, cmap='gray')
self.vmin = self.image.get_clim()[0]
self.vmax = self.image.get_clim()[1]
self.centers_of_mass_plot, = self.ax1.plot(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0], 'o', color='r', picker=5)
if image_2 is not None:
self.ax2 = self.fig.add_subplot(222, sharex=self.ax1, sharey=self.ax1)
self.ax2.imshow(image_2)
self.centers_of_mass_plot2, = self.ax2.plot(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0], 'o', color='r')
self.plot_masks(self.ax2)
if image_3 is not None:
self.ax3 = self.fig.add_subplot(223, sharex=self.ax1, sharey=self.ax1)
self.centers_of_mass_plot3, = self.ax3.plot(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0], 'o', color='r')
self.ax3.imshow(image_3)
self.ax4 = self.fig.add_subplot(224, sharex=self.ax1, sharey=self.ax1)
self.ax4.imshow(self.mask_generator.segmentation_labels)
self.fig.canvas.mpl_connect('pick_event', self.onpick)
self.fig.canvas.mpl_connect('key_press_event', self.on_key_press)
self.fig.canvas.mpl_connect('key_release_event', self.on_key_release)
self.fig.canvas.mpl_connect('button_press_event', self.onclick)
def plot_masks(self, axis, alpha=1):
color_index = np.arange(0, len(self.mask_generator.roi_masks), 1)
shuffled_color_index = np.random.choice(color_index, size=len(color_index), replace=False)
for m, color in zip(self.mask_generator.roi_masks, shuffled_color_index):
axis.scatter(m[:, 1], m[:, 0], s=5, color=self.cmap(color/float(len(self.mask_generator.roi_masks))),
alpha=alpha)
def onclick(self, event):
if self.shift_is_held:
try:
self.mask_generator.append_center_of_mass([event.ydata, event.xdata])
self.update_graph()
except Exception as e:
print(e)
def onpick(self, event):
try:
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
self.mask_generator.remove_center_of_mass([ydata[event.ind], xdata[event.ind]])
self.update_graph()
except Exception as e:
print(e)
def update_graph(self):
try:
self.centers_of_mass_plot.set_data(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0])
self.centers_of_mass_plot2.set_data(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0])
self.centers_of_mass_plot3.set_data(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.cocenters_of_mass[:, 0])
self.fig.canvas.draw()
except Exception as e:
print(e)
def on_key_press(self, event):
if event.key == 'shift':
self.shift_is_held = True
if event.key == 'u':
try:
self.mask_generator.update()
self.ax2.cla()
self.ax2.imshow(self.mask_generator.segmentation_labels*self.mask_generator.putative_somata_image)
self.ax2.plot(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0], 'o', color='r')
self.centers_of_mass_plot.set_data(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0])
self.centers_of_mass_plot.set_data(self.mask_generator.centers_of_mass[:, 1],
self.mask_generator.centers_of_mass[:, 0])
self.plot_masks(self.ax2)
self.fig.canvas.draw()
except Exception as e:
print(e)
if event.key == "t":
self.vmin += 2000
self.image.set_clim(vmin=self.vmin)
self.fig.canvas.draw()
if event.key == "y":
self.vmin -= 2000
self.image.set_clim(vmin=self.vmin)
self.fig.canvas.draw()
if event.key == "g":
self.vmax += 2000
self.image.set_clim(vmax=self.vmax)
self.fig.canvas.draw()
if event.key == "j":
self.vmax += -2000
self.image.set_clim(vmax=self.vmax)
self.fig.canvas.draw()
def on_key_release(self, event):
if event.key == 'shift':
self.shift_is_held = False
|
foss-transportationmodeling/rettina-server | refs/heads/master | .env/local/lib/python2.7/site-packages/wtforms/ext/django/templatetags/__init__.py | 12133432 | |
openhatch/oh-missions-oppia-beta | refs/heads/master | core/controllers/pages_test.py | 2 | # Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# 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.
__author__ = 'Sean Lip'
import test_utils
class SplashPageTest(test_utils.GenericTestBase):
def test_splash_page(self):
"""Test the main splash page."""
response = self.testapp.get('/')
self.assertEqual(response.status_int, 200)
response.mustcontain(
'Bite-sized learning journeys',
'Browse the explorations gallery', '100% free!',
'Learn', 'About', 'Contact',
# No navbar tabs should be highlighted.
no=['class="active"'])
def test_login_and_logout_on_splash_page(self):
"""Test that the correct buttons/navbar show on login and logout."""
response = self.testapp.get('/')
self.assertEqual(response.status_int, 200)
response.mustcontain(
'Login', 'Create an Oppia account', 'Contribute',
self.get_expected_login_url('/'),
no=['Profile', 'Logout', 'Create an exploration',
self.get_expected_logout_url('/')])
self.login('reader@example.com')
response = self.testapp.get('/')
self.assertEqual(response.status_int, 200)
response.mustcontain(
'Contribute', 'Profile', 'Logout', 'Create an exploration',
self.get_expected_logout_url('/'),
no=['Login', 'Create an Oppia account',
self.get_expected_login_url('/')])
self.logout()
class NoninteractivePagesTest(test_utils.GenericTestBase):
def test_about_page(self):
"""Test the About page."""
response = self.testapp.get('/about')
self.assertEqual(response.status_int, 200)
self.assertEqual(response.content_type, 'text/html')
response.mustcontain('What is Oppia?', 'About this website', 'License')
|
SerCeMan/intellij-community | refs/heads/master | python/lib/Lib/email/mime/image.py | 573 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Class representing image/* type MIME documents."""
__all__ = ['MIMEImage']
import imghdr
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
class MIMEImage(MIMENonMultipart):
"""Class for generating image/* type MIME documents."""
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
|
scemama/Bench_MRCC | refs/heads/master | bin/plot.py | 1 | #!/usr/bin/env python
import os, sys
if len(sys.argv) > 1:
column= int(sys.argv[1])
else:
column=1
datafiles = filter(lambda x: x.startswith('data_'), os.listdir(os.getcwd()))
# Read data files
data = {}
for file in datafiles:
try:
_, method, basis = file.split('_')
except:
pass
else:
with open(file,'r') as f:
values_text = f.readlines()
try:
values = dict(map(lambda x: (float(x.split()[0]), float(x.split()[column])), values_text))
except:
print file
raise
if basis not in data:
data[basis] = {}
data[basis][method] = values
# Create data files
for basis in data:
file = "NPE_%s"%basis
try:
keys = sorted(data[basis]['FCI'].keys())
except:
continue
methods = sorted(filter(lambda x: x != "FCI", data[basis].keys()))
with open(file,'w') as f:
sum_ = {}
minmax = {}
for m in methods:
sum_[m] = 0.
minmax[m] = (1.e30,-1.e30)
line = "#%-7s "%"R"
for m in methods:
line += " %16s"%m
print >>f, line
for x in keys:
cycle = False
for m in methods:
try:
data[basis][m][x]
except:
cycle=True
break
if not cycle:
line = "%-8f "%x
EFCI = data[basis]['FCI'][x]
for m in methods:
delta_E = data[basis][m][x]-EFCI
line += " %16f"%delta_E
sum_[m] += delta_E
minold, maxold = minmax[m]
minmax[m] = (min(minold,delta_E), max(maxold,delta_E))
print >>f, line
line = "#Average "
for m in methods:
line += " %16f"%(sum_[m]/len(keys))
print >>f, line
line = "#NPE "
for m in methods:
line += " %16f"%(minmax[m][1]-minmax[m][0])
print >>f, line
for basis in data:
methods = sorted(filter(lambda x: x != "FCI", data[basis].keys()))
plots = []
i=1
for m in methods:
i+=1
plots.append("'NPE_%s' u 1:%d w lp title '%s'"%(basis,i,m))
gnuplot_command = "plot "+", ".join(plots)
print gnuplot_command
|
conlini/django_dynamic_formset | refs/heads/master | dynamic_formset/__init__.py | 1 | from widget import *
from fields import *
from formsets import * |
evanma92/routeh | refs/heads/master | flask/lib/python2.7/site-packages/flask/testsuite/ext.py | 563 | # -*- coding: utf-8 -*-
"""
flask.testsuite.ext
~~~~~~~~~~~~~~~~~~~
Tests the extension import thing.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
import unittest
try:
from imp import reload as reload_module
except ImportError:
reload_module = reload
from flask.testsuite import FlaskTestCase
from flask._compat import PY2
class ExtImportHookTestCase(FlaskTestCase):
def setup(self):
# we clear this out for various reasons. The most important one is
# that a real flaskext could be in there which would disable our
# fake package. Secondly we want to make sure that the flaskext
# import hook does not break on reloading.
for entry, value in list(sys.modules.items()):
if (entry.startswith('flask.ext.') or
entry.startswith('flask_') or
entry.startswith('flaskext.') or
entry == 'flaskext') and value is not None:
sys.modules.pop(entry, None)
from flask import ext
reload_module(ext)
# reloading must not add more hooks
import_hooks = 0
for item in sys.meta_path:
cls = type(item)
if cls.__module__ == 'flask.exthook' and \
cls.__name__ == 'ExtensionImporter':
import_hooks += 1
self.assert_equal(import_hooks, 1)
def teardown(self):
from flask import ext
for key in ext.__dict__:
self.assert_not_in('.', key)
def test_flaskext_new_simple_import_normal(self):
from flask.ext.newext_simple import ext_id
self.assert_equal(ext_id, 'newext_simple')
def test_flaskext_new_simple_import_module(self):
from flask.ext import newext_simple
self.assert_equal(newext_simple.ext_id, 'newext_simple')
self.assert_equal(newext_simple.__name__, 'flask_newext_simple')
def test_flaskext_new_package_import_normal(self):
from flask.ext.newext_package import ext_id
self.assert_equal(ext_id, 'newext_package')
def test_flaskext_new_package_import_module(self):
from flask.ext import newext_package
self.assert_equal(newext_package.ext_id, 'newext_package')
self.assert_equal(newext_package.__name__, 'flask_newext_package')
def test_flaskext_new_package_import_submodule_function(self):
from flask.ext.newext_package.submodule import test_function
self.assert_equal(test_function(), 42)
def test_flaskext_new_package_import_submodule(self):
from flask.ext.newext_package import submodule
self.assert_equal(submodule.__name__, 'flask_newext_package.submodule')
self.assert_equal(submodule.test_function(), 42)
def test_flaskext_old_simple_import_normal(self):
from flask.ext.oldext_simple import ext_id
self.assert_equal(ext_id, 'oldext_simple')
def test_flaskext_old_simple_import_module(self):
from flask.ext import oldext_simple
self.assert_equal(oldext_simple.ext_id, 'oldext_simple')
self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple')
def test_flaskext_old_package_import_normal(self):
from flask.ext.oldext_package import ext_id
self.assert_equal(ext_id, 'oldext_package')
def test_flaskext_old_package_import_module(self):
from flask.ext import oldext_package
self.assert_equal(oldext_package.ext_id, 'oldext_package')
self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package')
def test_flaskext_old_package_import_submodule(self):
from flask.ext.oldext_package import submodule
self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule')
self.assert_equal(submodule.test_function(), 42)
def test_flaskext_old_package_import_submodule_function(self):
from flask.ext.oldext_package.submodule import test_function
self.assert_equal(test_function(), 42)
def test_flaskext_broken_package_no_module_caching(self):
for x in range(2):
with self.assert_raises(ImportError):
import flask.ext.broken
def test_no_error_swallowing(self):
try:
import flask.ext.broken
except ImportError:
exc_type, exc_value, tb = sys.exc_info()
self.assert_true(exc_type is ImportError)
if PY2:
message = 'No module named missing_module'
else:
message = 'No module named \'missing_module\''
self.assert_equal(str(exc_value), message)
self.assert_true(tb.tb_frame.f_globals is globals())
# reraise() adds a second frame so we need to skip that one too.
# On PY3 we even have another one :(
next = tb.tb_next.tb_next
if not PY2:
next = next.tb_next
self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename)
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ExtImportHookTestCase))
return suite
|
alex4108/scLikesDownloader | refs/heads/master | fudge/tests/support/_for_patch.py | 6 | class some_object:
class inner:
pass
|
redshodan/cairn | refs/heads/master | src/python/cairn/sysdefs/templates/unix/archive/readmeta/__init__.py | 1 | """templates.unix.archive.readmeta Module"""
import cairn
from cairn import Options
def getSubModuleString(sysdef):
str = "ExtractMeta; ReadMeta; VerifyMeta; VerifyArchive; "
return str
|
fredcollet/Sylius | refs/heads/master | docs/_themes/sylius_rtd_theme/__init__.py | 1504 | """Sphinx ReadTheDocs theme.
From https://github.com/ryan-roemer/sphinx-bootstrap-theme.
"""
import os
VERSION = (0, 1, 5)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version__
def get_html_theme_path():
"""Return list of HTML theme paths."""
cur_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
return cur_dir
|
zhuango/python | refs/heads/master | pytorchLearning/pytroch-with-deep-learning/chapter2_startup/run_a_cv_model.py | 1 | from torchvision import models
print(dir(models))
alexnet = models.AlexNet()
renet = models.resnet101(pretrained=True)
from PIL import Image
img = Image.open("./dog.PNG")
print(img)
img.show()
img_t = preprocess(img)
import torch
# add batch dimension.
batch_t = torch.unsequence(img_t, 0)
resnet.eval()
out = resnet(batch_t)
print(out) |
alexandrucoman/vbox-neutron-agent | refs/heads/master | neutron/extensions/portsecurity.py | 22 | # Copyright 2013 VMware, Inc. All rights reserved.
#
# 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 neutron.api.v2 import attributes
from neutron.common import exceptions as nexception
class PortSecurityPortHasSecurityGroup(nexception.InUse):
message = _("Port has security group associated. Cannot disable port "
"security or ip address until security group is removed")
class PortSecurityAndIPRequiredForSecurityGroups(nexception.InvalidInput):
message = _("Port security must be enabled and port must have an IP"
" address in order to use security groups.")
class PortSecurityBindingNotFound(nexception.InvalidExtensionEnv):
message = _("Port does not have port security binding.")
PORTSECURITY = 'port_security_enabled'
EXTENDED_ATTRIBUTES_2_0 = {
'networks': {
PORTSECURITY: {'allow_post': True, 'allow_put': True,
'convert_to': attributes.convert_to_boolean,
'enforce_policy': True,
'default': True,
'is_visible': True},
},
'ports': {
PORTSECURITY: {'allow_post': True, 'allow_put': True,
'convert_to': attributes.convert_to_boolean,
'default': attributes.ATTR_NOT_SPECIFIED,
'enforce_policy': True,
'is_visible': True},
}
}
class Portsecurity(object):
"""Extension class supporting port security."""
@classmethod
def get_name(cls):
return "Port Security"
@classmethod
def get_alias(cls):
return "port-security"
@classmethod
def get_description(cls):
return "Provides port security"
@classmethod
def get_namespace(cls):
return "http://docs.openstack.org/ext/portsecurity/api/v1.0"
@classmethod
def get_updated(cls):
return "2012-07-23T10:00:00-00:00"
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
|
kirbyfan64/hy | refs/heads/master | tests/importer/test_importer.py | 15 | from hy.importer import import_file_to_module, import_buffer_to_ast, MetaLoader
from hy.errors import HyTypeError
import os
import ast
def test_basics():
"Make sure the basics of the importer work"
import_file_to_module("basic",
"tests/resources/importer/basic.hy")
def test_stringer():
"Make sure the basics of the importer work"
_ast = import_buffer_to_ast("(defn square [x] (* x x))", '')
assert type(_ast.body[0]) == ast.FunctionDef
def test_imports():
path = os.getcwd() + "/tests/resources/importer/a.hy"
testLoader = MetaLoader(path)
def _import_test():
try:
return testLoader.load_module("tests.resources.importer.a")
except:
return "Error"
assert _import_test() == "Error"
assert _import_test() is not None
def test_import_error_reporting():
"Make sure that (import) reports errors correctly."
def _import_error_test():
try:
import_buffer_to_ast("(import \"sys\")", '')
except HyTypeError:
return "Error reported"
assert _import_error_test() == "Error reported"
assert _import_error_test() is not None
|
grahamhayes/designate | refs/heads/master | designate/api/admin/controllers/extensions/__init__.py | 12133432 | |
d6e/coala | refs/heads/master | coalib/processes/communication/__init__.py | 12133432 | |
google-research/google-research | refs/heads/master | constrained_language_typology/compute_associations_main.py | 1 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Computation of feature associations.
Computes:
1) Most likely value for a given feature given the clade (genetic
preference) for genera and families.
2) Most likely value2 for a given feature2 given feature1, value1
(implicational feature preference).
Usage, e.g.:
First run:
python3 sigtyp_reader_main.py \
--sigtyp_dir ~/ST2020-master/data \
--output_dir=/var/tmp/sigtyp
Then, using the defaults:
python3 compute_associations_main.py \
--training_data=/var/tmp/sigtyp/train.csv \
--dev_data=/var/tmp/sigtyp/dev.csv
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import os
from absl import app
from absl import flags
import compute_associations # pylint: disable=[unused-import]
import constants as const
import pandas as pd
import utils
# pylint: disable=g-long-lambda
flags.DEFINE_string(
"training_data", "",
"Training data in CSV file format with the `|` column separator. "
"This format is produced by `sigtyp_reader_main.py`.")
flags.DEFINE_string(
"dev_data", None,
"Development data in CSV file format with the `|` column separator. "
"This format is produced by `sigtyp_reader_main.py`.")
flags.DEFINE_float(
"close_enough", 2500,
"Distance in kilometers between two languages to count as 'close enough' "
"to be in the same neighborhood")
FLAGS = flags.FLAGS
def write_neighborhoods(path, neighborhoods):
"""Writes neighbourhood associations to a file."""
with open(path, "w") as stream:
# Write out for max value
#
# Lat,Lng for language
# Feature
# Value
# Probability of value given feature and neighborhood
# Total counts for feature+value+neighborhood
stream.write("{}|{}|{}|{}|{}\n".format(
"lat,lng", "f", "v", '"p(v|f, c)"', "n(f, c)"))
for latlng in neighborhoods:
for f in neighborhoods[latlng]:
tot = 0
max_c = 0
for v in neighborhoods[latlng][f]:
if neighborhoods[latlng][f][v] > max_c:
max_c = neighborhoods[latlng][f][v]
max_v = v
tot += neighborhoods[latlng][f][v]
stream.write("{},{}|{}|{}|{:0.3f}|{}\n".format(
latlng[0], latlng[1], f, max_v, max_c / tot, tot))
def write_implicational(path, implicational, implicational_prior):
"""Writes implicational associations to a file."""
with open(path, "w") as stream:
# Write out for max value
#
# Feature1
# Value1
# Feature2
# Value2
# Probabilty of Value2 given Feature1, Value1 and Feature2
# Total counts for Feature1, Value1 and Feature2
# Probability of Value2 given Feature2
# Total counts for Value2, Feature2
stream.write("{}|{}|{}|{}|{}|{}|{}|{}\n".format(
"f1", "v1", "f2", "v2", '"p(v2|f1, v1, f2)"', "n(f1, v1, f2)",
'"p(v2|f2)"', "n(f2, v2)"))
for (f1, v1) in implicational:
for f2 in implicational[f1, v1]:
tot = 0
max_c = 0
for v2 in implicational[f1, v1][f2]:
if implicational[f1, v1][f2][v2] > max_c:
max_c = implicational[f1, v1][f2][v2]
max_v2 = v2
tot += implicational[f1, v1][f2][v2]
tot_f2 = 0
for v2 in implicational_prior[f2]:
tot_f2 += implicational_prior[f2][v2]
prior_v2_prob = implicational_prior[f2][max_v2] / tot_f2
stream.write("{}|{}|{}|{}|{:0.3f}|{}|{:0.3f}|{}\n".format(
f1, v1, f2, max_v2, max_c / tot, tot, prior_v2_prob, tot_f2))
def write_clades(path, clades):
"""Writes glade information to a file."""
with open(path, "w") as stream:
# Write out for max value
#
# Clade
# Feature
# Value
# Probability of value given feature and clade
# Total counts for feature+clade
stream.write("{}|{}|{}|{}|{}\n".format(
"clade", "f", "v", '"p(v|f, c)"', "n(f, c)"))
for clade in clades:
for f in clades[clade]:
tot = 0
max_c = 0
for v in clades[clade][f]:
if clades[clade][f][v] > max_c:
max_c = clades[clade][f][v]
max_v = v
tot += clades[clade][f][v]
stream.write("{}|{}|{}|{:0.3f}|{}\n".format(
clade, f, max_v, max_c / tot, tot))
def find_close_languages(lat1, lng1, languages, distance_cache):
"""Given latitude/longitude coordinates finds the nearest language."""
close_language_indices = []
for i, language in enumerate(languages):
lat2 = language["latitude"]
lng2 = language["longitude"]
loc1 = (float(lat1), float(lng1))
loc2 = (float(lat2), float(lng2))
if (loc1, loc2) not in distance_cache:
dist = utils.haversine_distance((float(lat1), float(lng1)),
(float(lat2), float(lng2)))
distance_cache[(loc1, loc2)] = dist
distance_cache[(loc2, loc1)] = dist
else:
dist = distance_cache[(loc1, loc2)]
if dist < FLAGS.close_enough:
close_language_indices.append(i)
return close_language_indices
def correlate_features_for_training():
"""Computes all the feature associations required for training a model."""
training = pd.read_csv(FLAGS.training_data, delimiter="|",
encoding=const.ENCODING)
features = training.columns[7:]
clades = collections.defaultdict(
lambda:
collections.defaultdict(
lambda:
collections.defaultdict(
lambda:
collections.defaultdict(int))))
implicational = collections.defaultdict(
lambda:
collections.defaultdict(
lambda:
collections.defaultdict(int)))
# Whereas the implicationals collect the conditional probability of v2, given
# f1,v1 and f2, this just collects the conditional probability of v2 given
# v1. If the latter is also high, then the fact that the former is high is
# probably of less interest.
implicational_prior = collections.defaultdict(
lambda:
collections.defaultdict(int))
neighborhoods = collections.defaultdict(
lambda:
collections.defaultdict(
lambda:
collections.defaultdict(int)))
feature_frequency = collections.defaultdict(int)
distance_cache = {}
training_list = training.to_dict(orient="row")
for language_df in training_list:
genus = language_df["genus"]
family = language_df["family"]
for f1 in features:
v1 = language_df[f1]
if pd.isnull(v1):
continue
clades["genus"][genus][f1][v1] += 1
clades["family"][family][f1][v1] += 1
feature_frequency[f1, v1] += 1
for f2 in features:
if f1 == f2:
continue
v2 = language_df[f2]
if pd.isnull(v2):
continue
implicational[f1, v1][f2][v2] += 1
for f2 in features:
v2 = language_df[f2]
if pd.isnull(v2):
continue
implicational_prior[f2][v2] += 1
# Find nearby languages
lat1 = language_df["latitude"]
lng1 = language_df["longitude"]
close_language_indices = find_close_languages(
lat1, lng1, training_list, distance_cache)
if len(close_language_indices) == 1:
continue
for f1 in features:
for k in close_language_indices:
v1 = training_list[k][f1]
if pd.isnull(v1):
continue
neighborhoods[lat1, lng1][f1][v1] += 1
if FLAGS.dev_data:
# If we are also processing the development data, make sure that we also
# provide neighborhoods for the lat,lng for each language in the development
# data --- of course only actually using data from training.
development = pd.read_csv(FLAGS.dev_data, delimiter="|",
encoding=const.ENCODING)
development_list = development.to_dict(orient="row")
for language_df in development_list:
lat1 = language_df["latitude"]
lng1 = language_df["longitude"]
close_language_indices = find_close_languages(
lat1, lng1, training_list, distance_cache)
if len(close_language_indices) == 1:
continue
for f1 in features:
for k in close_language_indices:
v1 = training_list[k][f1]
if pd.isnull(v1):
continue
neighborhoods[lat1, lng1][f1][v1] += 1
clade_types = [("genus", FLAGS.genus_filename),
("family", FLAGS.family_filename)]
for clade_type, clade_filename in clade_types:
write_clades(os.path.join(FLAGS.association_dir, clade_filename),
clades[clade_type])
write_neighborhoods(os.path.join(
FLAGS.association_dir, FLAGS.neighborhood_filename), neighborhoods)
write_implicational(os.path.join(
FLAGS.association_dir, FLAGS.implicational_filename),
implicational, implicational_prior)
def main(unused_argv):
correlate_features_for_training()
if __name__ == "__main__":
app.run(main)
|
bluewitch/Code-Blue-Python | refs/heads/master | fizzbuzz_aking.py | 1 | class fizzbuzzPlayer():
def __init__(self, playernum):
self.playernum = playernum
def think(self, input):
if not divmod(input,3)[1] and not divmod(input,5)[1]: return 'fizzbuzz'
elif not divmod(input,3): return 'fizz'
elif not divmod(input,5): return 'buzz'
else: return str(input)
def play(self, input):
return('Player ' + str(self.playernum) + ' says: ' + self.think(input))
player_one = fizzbuzzPlayer(1)
player_two = fizzbuzzPlayer(2)
i=0
while(i<=42):
i+=1
if not divmod(i, 2)[1]: print(player_one.play(i))
else: print(player_two.play(i))
|
michaeljohn32/odoomrp-wip | refs/heads/8.0 | machine_manager_preventive/__openerp__.py | 12 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
{
"name": "Machine manager preventive",
"version": "1.0",
"depends": ["machine_manager", "mrp_repair"],
"author": "OdooMRP team",
"website": "http://www.odoomrp.com",
"contributors": ["Daniel Campos <danielcampos@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <ajuaristio@gmail.com>"],
"category": "Manufacturing",
"data": ["security/preventive_manager_security.xml",
"security/ir.model.access.csv",
"wizard/create_preventive_wizard_view.xml",
"wizard/create_repair_order_wizard_view.xml",
"views/preventive_mrp_data.xml",
"views/preventive_sequence.xml",
"views/machine_view.xml",
"views/preventive_master_view.xml",
"views/preventive_operation_view.xml",
"views/preventive_machine_operation_view.xml",
"views/mrp_repair_view.xml"],
"installable": True
}
|
loco-odoo/localizacion_co | refs/heads/master | openerp/addons-extra/report_move_voucher/report/__init__.py | 7 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits######################################################
# Coded by: María Gabriela Quilarque <gabrielaquilarque97@gmail.com>
# Luis Escobar <luis@vauxoo.com>
# Planified by: Nhomar Hernandez
# Finance by: Vauxoo, C.A. http://vauxoo.com
# Audited by: Humberto Arocha humberto@openerp.com.ve
#############################################################################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
##############################################################################
import account
|
anksp21/Community-Zenpacks | refs/heads/master | ZenPacks.AndreaConsadori.Alvarion/ZenPacks/AndreaConsadori/Alvarion/modeler/plugins/AlvarionDeviceMap.py | 2 | #
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2007, Zenoss Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# For complete information please visit: http://www.zenoss.com/oss/
#
###########################################################################
from Products.DataCollector.plugins.CollectorPlugin import SnmpPlugin, GetMap
class AlvarionDeviceMap(SnmpPlugin):
"""Map mib elements from Alvarion mib to get hw and os products.
"""
maptype = "AlvarionDeviceMap"
snmpGetMap = GetMap({
'.1.3.6.1.4.1.12394.3.2.1.13.0' : 'setHWSerialNumber',
# '.1.3.6.1.4.1.12394.3.2.9.16.1.0' : 'manufacturer',
'.1.3.6.1.4.1.12394.3.2.1.2.0' : 'setHWProductKey',
'.1.3.6.1.4.1.12394.3.2.1.5.0': 'setOSProductKey',
})
def process(self, device, results, log):
"""collect snmp information from this device"""
log.info('processing %s for device %s', self.name(), device.id)
getdata, tabledata = results
if getdata['setHWProductKey'] is None: return None
om = self.objectMap(getdata)
return om
|
JDShu/SCOPE | refs/heads/master | askbot/migrations/0025_transfer_flagged_items_to_activity.py | 2 | # encoding: utf-8
#from south.db import db
from south.v2 import DataMigration
from askbot.migrations_api.version1 import API
from askbot import const
OFFENSIVE = const.TYPE_ACTIVITY_MARK_OFFENSIVE
class Migration(DataMigration):
def forwards(self, orm):
"""find all FlaggedItems and the corresponding Activity
transfer content object to Activity
add moderators and admins to the activity recipients
and set the denormalized value of exercise to the origin post
of the flagged item
"""
api = API(orm)
moderators = api.get_moderators_and_admins()
for flag in orm.FlaggedItem.objects.all():
activity_items = api.get_activity_items_for_object(flag)
if len(activity_items) == 0:#fix a glitch
activity = orm.Activity()
elif len(activity_items) == 1:
activity = activity_items[0]
else:
raise ValueError('cannot have >1 flagged items per activity')
activity.user = flag.user
activity.active_at = flag.flagged_at
activity.activity_type = OFFENSIVE
activity.content_type = flag.content_type
activity.object_id = flag.object_id
activity.exercise = api.get_origin_post_from_content_object(flag)
activity.save()
api.add_recipients_to_activity(moderators, activity)
flag.delete()
def backwards(self, orm):
"""there is a side-effect that activity recipients are not removed
exercise reference is not deleted either
"""
activity_items = orm.Activity.objects.filter(activity_type=OFFENSIVE)
for activity in activity_items:
flag = orm.FlaggedItem(
user = activity.user,
flagged_at = activity.active_at,
object_id = activity.object_id,
content_type = activity.content_type
)
flag.save()
models = {
'askbot.activity': {
'Meta': {'object_name': 'Activity', 'db_table': "u'activity'"},
'active_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'activity_type': ('django.db.models.fields.SmallIntegerField', [], {}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_auditted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Exercise']", 'null': 'True'}),
'receiving_users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'received_activity'", 'to': "orm['auth.User']"}),
'recipients': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'incoming_activity'", 'through': "'ActivityAuditStatus'", 'to': "orm['auth.User']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.activityauditstatus': {
'Meta': {'unique_together': "(('user', 'activity'),)", 'object_name': 'ActivityAuditStatus'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Activity']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.anonymousproblem': {
'Meta': {'object_name': 'AnonymousProblem'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'anonymous_problems'", 'to': "orm['askbot.Exercise']"}),
'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'text': ('django.db.models.fields.TextField', [], {}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'})
},
'askbot.anonymousexercise': {
'Meta': {'object_name': 'AnonymousExercise'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}),
'text': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'})
},
'askbot.problem': {
'Meta': {'object_name': 'Problem', 'db_table': "u'problem'"},
'accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'accepted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'problems'", 'to': "orm['auth.User']"}),
'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_problems'", 'null': 'True', 'to': "orm['auth.User']"}),
'html': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_edited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_edited_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'last_edited_problems'", 'null': 'True', 'to': "orm['auth.User']"}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_problems'", 'null': 'True', 'to': "orm['auth.User']"}),
'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'problems'", 'to': "orm['askbot.Exercise']"}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'vote_up_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'wikified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'askbot.problemrevision': {
'Meta': {'object_name': 'ProblemRevision', 'db_table': "u'problem_revision'"},
'problem': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['askbot.Problem']"}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'problemrevisions'", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'revised_at': ('django.db.models.fields.DateTimeField', [], {}),
'revision': ('django.db.models.fields.PositiveIntegerField', [], {}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'text': ('django.db.models.fields.TextField', [], {})
},
'askbot.award': {
'Meta': {'object_name': 'Award', 'db_table': "u'award'"},
'awarded_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'badge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_badge'", 'to': "orm['askbot.Badge']"}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_user'", 'to': "orm['auth.User']"})
},
'askbot.badge': {
'Meta': {'unique_together': "(('name', 'type'),)", 'object_name': 'Badge', 'db_table': "u'badge'"},
'awarded_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'awarded_to': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'badges'", 'through': "'Award'", 'to': "orm['auth.User']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'multiple': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '50', 'blank': 'True'}),
'type': ('django.db.models.fields.SmallIntegerField', [], {})
},
'askbot.comment': {
'Meta': {'object_name': 'Comment', 'db_table': "u'comment'"},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'comment': ('django.db.models.fields.CharField', [], {'max_length': '2048'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'html': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '2048'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comments'", 'to': "orm['auth.User']"})
},
'askbot.emailfeedsetting': {
'Meta': {'object_name': 'EmailFeedSetting'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'feed_type': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'frequency': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '8'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reported_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'subscriber': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notification_subscriptions'", 'to': "orm['auth.User']"})
},
'askbot.favoriteexercise': {
'Meta': {'object_name': 'FavoriteExercise', 'db_table': "u'favorite_exercise'"},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Exercise']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_favorite_exercises'", 'to': "orm['auth.User']"})
},
'askbot.flaggeditem': {
'Meta': {'unique_together': "(('content_type', 'object_id', 'user'),)", 'object_name': 'FlaggedItem', 'db_table': "u'flagged_item'"},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'flagged_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flaggeditems'", 'to': "orm['auth.User']"})
},
'askbot.markedtag': {
'Meta': {'object_name': 'MarkedTag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reason': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_selections'", 'to': "orm['askbot.Tag']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tag_selections'", 'to': "orm['auth.User']"})
},
'askbot.exercise': {
'Meta': {'object_name': 'Exercise', 'db_table': "u'exercise'"},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'problem_accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'problem_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exercises'", 'to': "orm['auth.User']"}),
'close_reason': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'closed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'closed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'closed_exercises'", 'null': 'True', 'to': "orm['auth.User']"}),
'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_exercises'", 'null': 'True', 'to': "orm['auth.User']"}),
'favorited_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'favorite_exercises'", 'through': "'FavoriteExercise'", 'to': "orm['auth.User']"}),
'favourite_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'followed_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'followed_exercises'", 'to': "orm['auth.User']"}),
'html': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_activity_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_activity_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_active_in_exercises'", 'to': "orm['auth.User']"}),
'last_edited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_edited_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'last_edited_exercises'", 'null': 'True', 'to': "orm['auth.User']"}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_exercises'", 'null': 'True', 'to': "orm['auth.User']"}),
'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'exercises'", 'to': "orm['askbot.Tag']"}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'view_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'vote_up_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'wikified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'askbot.exerciserevision': {
'Meta': {'object_name': 'ExerciseRevision', 'db_table': "u'exercise_revision'"},
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exerciserevisions'", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['askbot.Exercise']"}),
'revised_at': ('django.db.models.fields.DateTimeField', [], {}),
'revision': ('django.db.models.fields.PositiveIntegerField', [], {}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}),
'text': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'})
},
'askbot.exerciseview': {
'Meta': {'object_name': 'ExerciseView'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'viewed'", 'to': "orm['askbot.Exercise']"}),
'when': ('django.db.models.fields.DateTimeField', [], {}),
'who': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exercise_views'", 'to': "orm['auth.User']"})
},
'askbot.repute': {
'Meta': {'object_name': 'Repute', 'db_table': "u'repute'"},
'comment': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'negative': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'positive': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Exercise']", 'null': 'True', 'blank': 'True'}),
'reputation': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'reputation_type': ('django.db.models.fields.SmallIntegerField', [], {}),
'reputed_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.tag': {
'Meta': {'object_name': 'Tag', 'db_table': "u'tag'"},
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_tags'", 'to': "orm['auth.User']"}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_tags'", 'null': 'True', 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'used_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'askbot.vote': {
'Meta': {'unique_together': "(('content_type', 'object_id', 'user'),)", 'object_name': 'Vote', 'db_table': "u'vote'"},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['auth.User']"}),
'vote': ('django.db.models.fields.SmallIntegerField', [], {}),
'voted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
'hide_ignored_exercises': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'exercises_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}),
'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}),
'tag_filter_setting': ('django.db.models.fields.CharField', [], {'default': "'ignored'", 'max_length': '16'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['askbot']
|
mikesname/ehri-collections | refs/heads/master | ehriportal/suggestions/models.py | 1 | """Suggestions model."""
import datetime
from django.db import models
import jsonfield
GRAB_META = [
"HTTP_USER_AGENT",
"HTTP_HOST",
"REMOTE_HOST",
"HTTP_ACCEPT",
"HTTP_REFERER",
"REMOTE_ADDR",
"CONTEXT_TYPE",
"HTTP_ACCEPT_LANGUAGE",
"QUERY_STRING",
]
def get_suggestion_meta(request):
"""Return a dictionary of interesting things about
a request that we want to store with the suggestion,
since it might give some useful extra context."""
return dict([(k, v) for k, v in request.META.iteritems() \
if k in GRAB_META])
class Suggestion(models.Model):
"""Suggestion class."""
name = models.CharField(max_length=255)
email = models.EmailField(null=True, blank=True)
text = models.TextField()
meta = jsonfield.JSONField(null=True)
created_on = models.DateTimeField(editable=False)
updated_on = models.DateTimeField(editable=False, null=True, blank=True)
def save(self, *args, **kwargs):
if not self.id:
self.created_on = datetime.datetime.now()
else:
self.updated_on = datetime.datetime.now()
super(Suggestion, self).save(*args, **kwargs)
def __unicode__(self):
text = self.text[:17]
if len(text) != self.text:
text += "..."
return "%s: '%s'" % (self.name, text)
@models.permalink
def get_absolute_url(self):
return ('suggestion_detail', [self.id])
|
2014cdag10/2014cdaGG | refs/heads/master | wsgi/programs/cdag14/__init__.py | 9 | import cherrypy
# 這是 CDAG14 類別的定義
class CDAG14(object):
# 各組利用 index 引導隨後的程式執行
@cherrypy.expose
def index(self, *args, **kwargs):
outstring = '''
這是 2014CDA 協同專案下的 cdag14 分組程式開發網頁, 以下為 W12 的任務執行內容.<br />
<!-- 這裡採用相對連結, 而非網址的絕對連結 (這一段為 html 註解) -->
<a href="cube1">cdag14 正方體參數繪圖</a>(尺寸變數 a, b, c)<br /><br />
<a href="fourbar1">四連桿組立</a><br /><br />
請確定下列連桿位於 V:/home/fourbar 目錄中, 且開啟空白 Creo 組立檔案.<br />
<a href="/static/fourbar.7z">fourbar.7z</a>(滑鼠右鍵存成 .7z 檔案)<br />
'''
return outstring
'''
假如採用下列規畫
import programs.cdag14 as cdag14
root.cdag14 = cdag14.CDAG14()
則程式啟動後, 可以利用 /cdag14/cube1 呼叫函式執行
'''
@cherrypy.expose
def cube1(self, *args, **kwargs):
'''
// 假如要自行打開特定零件檔案
// 若第三輸入為 false, 表示僅載入 session, 但是不顯示
// ret 為 model open return
var ret = document.pwl.pwlMdlOpen("axle_5.prt", "v:/tmp", false);
if (!ret.Status) {
alert("pwlMdlOpen failed (" + ret.ErrorCode + ")");
}
//將 ProE 執行階段設為變數 session
var session = pfcGetProESession();
// 在視窗中打開零件檔案, 並且顯示出來
var window = session.OpenFile(pfcCreate("pfcModelDescriptor").CreateFromFileName("axle_5.prt"));
var solid = session.GetModel("axle_5.prt",pfcCreate("pfcModelType").MDL_PART);
'''
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/weblink/examples/jscript/pfcUtils.js"></script>
<script type="text/javascript" src="/static/weblink/examples/jscript/pfcParameterExamples.js"></script>
<script type="text/javascript" src="/static/weblink/examples/jscript/pfcComponentFeatExamples.js"></script>
</head>
<body>
<script type="text/javascript">
var session = pfcGetProESession ();
// 以目前所開啟的檔案為 solid model
// for volume
var solid = session.CurrentModel;
var a, b, c, i, j, aValue, bValue, cValue, volume, count;
// 將模型檔中的 a 變數設為 javascript 中的 a 變數
a = solid.GetParam("a");
b = solid.GetParam("b");
c = solid.GetParam("c");
volume=0;
count=0;
try
{
for(i=0;i<5;i++)
{
myf = 100;
myn = myf + i*10;
// 設定變數值, 利用 ModelItem 中的 CreateDoubleParamValue 轉換成 Pro/Web.Link 所需要的浮點數值
aValue = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myn);
bValue = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myn);
// 將處理好的變數值, 指定給對應的零件變數
a.Value = aValue;
b.Value = bValue;
//零件尺寸重新設定後, 呼叫 Regenerate 更新模型
solid.Regenerate(void null);
//利用 GetMassProperty 取得模型的質量相關物件
properties = solid.GetMassProperty(void null);
volume = properties.Volume;
count = count + 1;
alert("執行第"+count+"次,零件總體積:"+volume);
// 將零件存為新檔案
//var newfile = document.pwl.pwlMdlSaveAs("filename.prt", "v:/tmp", "filename_5_"+count+".prt");
// 測試 stl 轉檔
//var stl_csys = "PRT_CSYS_DEF";
//var stl_instrs = new pfcCreate ("pfcSTLASCIIExportInstructions").Create(stl_csys);
//stl_instrs.SetQuality(10);
//solid.Export("v:/tmp/filename_5_"+count+".stl", stl_instrs);
// 結束測試轉檔
//if (!newfile.Status) {
//alert("pwlMdlSaveAs failed (" + newfile.ErrorCode + ")");
//}
} // for loop
}
catch (err)
{
alert ("Exception occurred: "+pfcGetExceptionType (err));
}
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def fourbar1(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/weblink/examples/jscript/pfcUtils.js"></script>
</head>
<body>
<script type="text/javascript">
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var session = pfcGetProESession();
// 設定 config option
session.SetConfigOption("comp_placement_assumptions","no");
// 建立擺放零件的位置矩陣
var identityMatrix = pfcCreate ("pfcMatrix3D");
for (var x = 0; x < 4; x++)
for (var y = 0; y < 4; y++)
{
if (x == y)
identityMatrix.Set (x, y, 1.0);
else
identityMatrix.Set (x, y, 0.0);
}
var transf = pfcCreate ("pfcTransform3D").Create (identityMatrix);
// 取得目前的工作目錄
var currentDir = session.getCurrentDirectory();
// 以目前已開檔, 作為 model
var model = session.CurrentModel;
// 查驗有無 model, 或 model 類別是否為組立件
if (model == void null || model.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly.");
var assembly = model;
/**----------------------------------------------- link0 -------------------------------------------------------------**/
//檔案目錄,建議將圖檔放置工作目錄下較方便使用
var descr = pfcCreate ("pfcModelDescriptor").CreateFromFileName ("v:/home/fourbar/link0.prt");
// 若 link1.prt 在 session 則直接取用
var componentModel = session.GetModelFromDescr (descr);
//若 link1.prt 不在 session 則從工作目錄中載入 session
var componentModel = session.RetrieveModel(descr);
//若 link1.prt 已經在 session 則放入組立檔中
if (componentModel != void null)
{
//注意這個 asmcomp 即為設定約束條件的本體
//asmcomp 為特徵物件,直接將零件, 以 transf 座標轉換放入組立檔案中
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
// 建立約束條件變數
var constrs = pfcCreate ("pfcComponentConstraints");
//設定組立檔中的三個定位面, 注意內定名稱與 Pro/E WF 中的 ASM_D_FRONT 不同, 而是 ASM_FRONT
var asmDatums = new Array ("ASM_FRONT", "ASM_TOP", "ASM_RIGHT");
//設定零件檔中的三個定位面, 名稱與 Pro/E WF 中相同
var compDatums = new Array ("FRONT", "TOP", "RIGHT");
//建立 ids 變數, intseq 為 sequence of integers 為資料類別, 使用者可以經由整數索引擷取此資料類別的元件, 第一個索引為 0
var ids = pfcCreate ("intseq");
//建立路徑變數
var path = pfcCreate ("MpfcAssembly").CreateComponentPath (assembly, ids);
//採用互動式設定相關的變數
var MpfcSelect = pfcCreate ("MpfcSelect");
//利用迴圈分別約束組立與零件檔中的三個定位平面
for (var i = 0; i < 3; i++)
{
//設定組立參考面
var asmItem = assembly.GetItemByName (pfcCreate ("pfcModelItemType").ITEM_SURFACE, asmDatums [i]);
//若無對應的組立參考面, 則啟用互動式平面選擇表單 flag
if (asmItem == void null)
{
interactFlag = true;
continue;
}
//設定零件參考面
var compItem = componentModel.GetItemByName (pfcCreate ("pfcModelItemType").ITEM_SURFACE, compDatums [i]);
//若無對應的零件參考面, 則啟用互動式平面選擇表單 flag
if (compItem == void null)
{
interactFlag = true;
continue;
}
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, path);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate ("pfcComponentConstraint").Create (pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate ("pfcConstraintAttributes").Create (false, false);
//將互動選擇相關資料, 附加在程式約束變數之後
constrs.Append (constr);
}
//設定組立約束條件
asmcomp.SetConstraints (constrs, void null);
/**-------------------------------------------------------------------------------------------------------------------**/
/**----------------------------------------------- link1 -------------------------------------------------------------**/
var descr = pfcCreate ("pfcModelDescriptor").CreateFromFileName ("v:/home/fourbar/link1.prt");
var componentModel = session.GetModelFromDescr (descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var components = assembly.ListFeaturesByType(true, pfcCreate ("pfcFeatureType").FEATTYPE_COMPONENT);
var featID = components.Item(0).Id;
ids.Append(featID);
var subPath = pfcCreate ("MpfcAssembly").CreateComponentPath( assembly, ids );
subassembly = subPath.Leaf;
var asmDatums = new Array ("A_1", "TOP", "ASM_TOP");
var compDatums = new Array ("A_1", "TOP", "TOP");
var relation = new Array (pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN, pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_MATE);
var relationItem = new Array(pfcCreate("pfcModelItemType").ITEM_AXIS,pfcCreate("pfcModelItemType").ITEM_SURFACE);
var constrs = pfcCreate ("pfcComponentConstraints");
for (var i = 0; i < 2; i++)
{
var asmItem = subassembly.GetItemByName (relationItem[i], asmDatums [i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName (relationItem[i], compDatums [i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var MpfcSelect = pfcCreate ("MpfcSelect");
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate ("pfcComponentConstraint").Create (relation[i]);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate ("pfcConstraintAttributes").Create (true, false);
constrs.Append (constr);
}
asmcomp.SetConstraints (constrs, void null);
/**-------------------------------------------------------------------------------------------------------------------**/
/**----------------------------------------------- link2 -------------------------------------------------------------**/
var descr = pfcCreate ("pfcModelDescriptor").CreateFromFileName ("v:/home/fourbar/link2.prt");
var componentModel = session.GetModelFromDescr (descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var ids = pfcCreate ("intseq");
ids.Append(featID+1);
var subPath = pfcCreate ("MpfcAssembly").CreateComponentPath( assembly, ids );
subassembly = subPath.Leaf;
var asmDatums = new Array ("A_2", "TOP", "ASM_TOP");
var compDatums = new Array ("A_1", "TOP", "TOP");
var relation = new Array (pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN, pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_MATE);
var relationItem = new Array(pfcCreate("pfcModelItemType").ITEM_AXIS,pfcCreate("pfcModelItemType").ITEM_SURFACE);
var constrs = pfcCreate ("pfcComponentConstraints");
for (var i = 0; i < 2; i++)
{
var asmItem = subassembly.GetItemByName (relationItem[i], asmDatums [i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName (relationItem[i], compDatums [i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var MpfcSelect = pfcCreate ("MpfcSelect");
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate ("pfcComponentConstraint").Create (relation[i]);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate ("pfcConstraintAttributes").Create (true, false);
constrs.Append (constr);
}
asmcomp.SetConstraints (constrs, void null);
/**-------------------------------------------------------------------------------------------------------------------**/
/**----------------------------------------------- link3 -------------------------------------------------------------**/
var descr = pfcCreate ("pfcModelDescriptor").CreateFromFileName ("v:/home/fourbar/link3.prt");
var componentModel = session.GetModelFromDescr (descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var relation = new Array (pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN, pfcCreate ("pfcComponentConstraintType").ASM_CONSTRAINT_MATE);
var relationItem = new Array(pfcCreate("pfcModelItemType").ITEM_AXIS,pfcCreate("pfcModelItemType").ITEM_SURFACE);
var constrs = pfcCreate ("pfcComponentConstraints");
var ids = pfcCreate ("intseq");
ids.Append(featID+2);
var subPath = pfcCreate ("MpfcAssembly").CreateComponentPath( assembly, ids );
subassembly = subPath.Leaf;
var asmDatums = new Array ("A_2");
var compDatums = new Array ("A_1");
for (var i = 0; i < 1; i++)
{
var asmItem = subassembly.GetItemByName (relationItem[i], asmDatums [i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName (relationItem[i], compDatums [i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var MpfcSelect = pfcCreate ("MpfcSelect");
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate ("pfcComponentConstraint").Create (relation[i]);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate ("pfcConstraintAttributes").Create (true, false);
constrs.Append (constr);
}
asmcomp.SetConstraints (constrs, void null);
var ids = pfcCreate ("intseq");
ids.Append(featID);
var subPath = pfcCreate ("MpfcAssembly").CreateComponentPath( assembly, ids );
subassembly = subPath.Leaf;
var asmDatums = new Array ("A_2", "TOP");
var compDatums = new Array ("A_2", "BOTTON");
for (var i = 0; i < 2; i++)
{
var asmItem = subassembly.GetItemByName (relationItem[i], asmDatums [i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName (relationItem[i], compDatums [i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var MpfcSelect = pfcCreate ("MpfcSelect");
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate ("pfcComponentConstraint").Create (relation[i]);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate ("pfcConstraintAttributes").Create (true, true);
constrs.Append (constr);
}
asmcomp.SetConstraints (constrs, void null);
/**-------------------------------------------------------------------------------------------------------------------**/
var session = pfcGetProESession ();
var solid = session.CurrentModel;
properties = solid.GetMassProperty(void null);
var COG = properties.GravityCenter;
document.write("MassProperty:<br />");
document.write("Mass:"+(properties.Mass.toFixed(2))+" pound<br />");
document.write("Average Density:"+(properties.Density.toFixed(2))+" pound/inch^3<br />");
document.write("Surface area:"+(properties.SurfaceArea.toFixed(2))+" inch^2<br />");
document.write("Volume:"+(properties.Volume.toFixed(2))+" inch^3<br />");
document.write("COG_X:"+COG.Item(0).toFixed(2)+"<br />");
document.write("COG_Y:"+COG.Item(1).toFixed(2)+"<br />");
document.write("COG_Z:"+COG.Item(2).toFixed(2)+"<br />");
try
{
document.write("Current Directory:<br />"+currentDir);
}
catch (err)
{
alert ("Exception occurred: "+pfcGetExceptionType (err));
}
assembly.Regenerate (void null);
session.GetModelWindow (assembly).Repaint();
</script>
</body>
</html>
'''
return outstring
|
LokiCoder/Sick-Beard | refs/heads/torrent_1080_subtitles | lib/tvdb_api/setup.py | 50 | from setuptools import setup
setup(
name = 'tvdb_api',
version='1.9',
author='dbr/Ben',
description='Interface to thetvdb.com',
url='http://github.com/dbr/tvdb_api/tree/master',
license='unlicense',
long_description="""\
An easy to use API interface to TheTVDB.com
Basic usage is:
>>> import tvdb_api
>>> t = tvdb_api.Tvdb()
>>> ep = t['My Name Is Earl'][1][22]
>>> ep
<Episode 01x22 - Stole a Badge>
>>> ep['episodename']
u'Stole a Badge'
""",
py_modules = ['tvdb_api', 'tvdb_ui', 'tvdb_exceptions', 'tvdb_cache'],
classifiers=[
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Multimedia",
"Topic :: Utilities",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
|
tushar-rishav/coala | refs/heads/master | tests/output/dbus/dbus_test_files/LocalTestBear.py | 26 | from coalib.bears.LocalBear import LocalBear
from coalib.results.HiddenResult import HiddenResult
from coalib.results.Result import Result
class LocalTestBear(LocalBear): # pragma: no cover
def run(self, filename, file):
return [Result("LocalTestBear", "test msg"),
HiddenResult("LocalTestBear", "hidden msg")]
|
tdickers/mitmproxy | refs/heads/master | test/mitmproxy/script/test_script.py | 1 | from mitmproxy.script import Script
from mitmproxy.exceptions import ScriptException
from test.mitmproxy import tutils
class TestParseCommand:
def test_empty_command(self):
with tutils.raises(ScriptException):
Script.parse_command("")
with tutils.raises(ScriptException):
Script.parse_command(" ")
def test_no_script_file(self):
with tutils.raises("not found"):
Script.parse_command("notfound")
with tutils.tmpdir() as dir:
with tutils.raises("not a file"):
Script.parse_command(dir)
def test_parse_args(self):
with tutils.chdir(tutils.test_data.dirname):
assert Script.parse_command("data/scripts/a.py") == ["data/scripts/a.py"]
assert Script.parse_command("data/scripts/a.py foo bar") == ["data/scripts/a.py", "foo", "bar"]
assert Script.parse_command("data/scripts/a.py 'foo bar'") == ["data/scripts/a.py", "foo bar"]
@tutils.skip_not_windows
def test_parse_windows(self):
with tutils.chdir(tutils.test_data.dirname):
assert Script.parse_command("data\\scripts\\a.py") == ["data\\scripts\\a.py"]
assert Script.parse_command("data\\scripts\\a.py 'foo \\ bar'") == ["data\\scripts\\a.py", 'foo \\ bar']
def test_simple():
with tutils.chdir(tutils.test_data.path("data/scripts")):
s = Script("a.py --var 42", None)
assert s.filename == "a.py"
assert s.ns is None
s.load()
assert s.ns["var"] == 42
s.run("here")
assert s.ns["var"] == 43
s.unload()
assert s.ns is None
with tutils.raises(ScriptException):
s.run("here")
with Script("a.py --var 42", None) as s:
s.run("here")
def test_script_exception():
with tutils.chdir(tutils.test_data.path("data/scripts")):
s = Script("syntaxerr.py", None)
with tutils.raises(ScriptException):
s.load()
s = Script("starterr.py", None)
with tutils.raises(ScriptException):
s.load()
s = Script("a.py", None)
s.load()
with tutils.raises(ScriptException):
s.load()
s = Script("a.py", None)
with tutils.raises(ScriptException):
s.run("here")
with tutils.raises(ScriptException):
with Script("reqerr.py", None) as s:
s.run("request", None)
s = Script("unloaderr.py", None)
s.load()
with tutils.raises(ScriptException):
s.unload()
|
Taceor/EggZlist | refs/heads/master | node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py | 1355 | # Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""cmake output module
This module is under development and should be considered experimental.
This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is
created for each configuration.
This module's original purpose was to support editing in IDEs like KDevelop
which use CMake for project management. It is also possible to use CMake to
generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator
will convert the CMakeLists.txt to a code::blocks cbp for the editor to read,
but build using CMake. As a result QtCreator editor is unaware of compiler
defines. The generated CMakeLists.txt can also be used to build on Linux. There
is currently no support for building on platforms other than Linux.
The generated CMakeLists.txt should properly compile all projects. However,
there is a mismatch between gyp and cmake with regard to linking. All attempts
are made to work around this, but CMake sometimes sees -Wl,--start-group as a
library and incorrectly repeats it. As a result the output of this generator
should not be relied on for building.
When using with kdevelop, use version 4.4+. Previous versions of kdevelop will
not be able to find the header file directories described in the generated
CMakeLists.txt file.
"""
import multiprocessing
import os
import signal
import string
import subprocess
import gyp.common
generator_default_variables = {
'EXECUTABLE_PREFIX': '',
'EXECUTABLE_SUFFIX': '',
'STATIC_LIB_PREFIX': 'lib',
'STATIC_LIB_SUFFIX': '.a',
'SHARED_LIB_PREFIX': 'lib',
'SHARED_LIB_SUFFIX': '.so',
'SHARED_LIB_DIR': '${builddir}/lib.${TOOLSET}',
'LIB_DIR': '${obj}.${TOOLSET}',
'INTERMEDIATE_DIR': '${obj}.${TOOLSET}/${TARGET}/geni',
'SHARED_INTERMEDIATE_DIR': '${obj}/gen',
'PRODUCT_DIR': '${builddir}',
'RULE_INPUT_PATH': '${RULE_INPUT_PATH}',
'RULE_INPUT_DIRNAME': '${RULE_INPUT_DIRNAME}',
'RULE_INPUT_NAME': '${RULE_INPUT_NAME}',
'RULE_INPUT_ROOT': '${RULE_INPUT_ROOT}',
'RULE_INPUT_EXT': '${RULE_INPUT_EXT}',
'CONFIGURATION_NAME': '${configuration}',
}
FULL_PATH_VARS = ('${CMAKE_CURRENT_LIST_DIR}', '${builddir}', '${obj}')
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = True
COMPILABLE_EXTENSIONS = {
'.c': 'cc',
'.cc': 'cxx',
'.cpp': 'cxx',
'.cxx': 'cxx',
'.s': 's', # cc
'.S': 's', # cc
}
def RemovePrefix(a, prefix):
"""Returns 'a' without 'prefix' if it starts with 'prefix'."""
return a[len(prefix):] if a.startswith(prefix) else a
def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
def Compilable(filename):
"""Return true if the file is compilable (should be in OBJS)."""
return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS)
def Linkable(filename):
"""Return true if the file is linkable (should be on the link line)."""
return filename.endswith('.o')
def NormjoinPathForceCMakeSource(base_path, rel_path):
"""Resolves rel_path against base_path and returns the result.
If rel_path is an absolute path it is returned unchanged.
Otherwise it is resolved against base_path and normalized.
If the result is a relative path, it is forced to be relative to the
CMakeLists.txt.
"""
if os.path.isabs(rel_path):
return rel_path
if any([rel_path.startswith(var) for var in FULL_PATH_VARS]):
return rel_path
# TODO: do we need to check base_path for absolute variables as well?
return os.path.join('${CMAKE_CURRENT_LIST_DIR}',
os.path.normpath(os.path.join(base_path, rel_path)))
def NormjoinPath(base_path, rel_path):
"""Resolves rel_path against base_path and returns the result.
TODO: what is this really used for?
If rel_path begins with '$' it is returned unchanged.
Otherwise it is resolved against base_path if relative, then normalized.
"""
if rel_path.startswith('$') and not rel_path.startswith('${configuration}'):
return rel_path
return os.path.normpath(os.path.join(base_path, rel_path))
def CMakeStringEscape(a):
"""Escapes the string 'a' for use inside a CMake string.
This means escaping
'\' otherwise it may be seen as modifying the next character
'"' otherwise it will end the string
';' otherwise the string becomes a list
The following do not need to be escaped
'#' when the lexer is in string state, this does not start a comment
The following are yet unknown
'$' generator variables (like ${obj}) must not be escaped,
but text $ should be escaped
what is wanted is to know which $ come from generator variables
"""
return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"')
def SetFileProperty(output, source_name, property_name, values, sep):
"""Given a set of source file, sets the given property on them."""
output.write('set_source_files_properties(')
output.write(source_name)
output.write(' PROPERTIES ')
output.write(property_name)
output.write(' "')
for value in values:
output.write(CMakeStringEscape(value))
output.write(sep)
output.write('")\n')
def SetFilesProperty(output, variable, property_name, values, sep):
"""Given a set of source files, sets the given property on them."""
output.write('set_source_files_properties(')
WriteVariable(output, variable)
output.write(' PROPERTIES ')
output.write(property_name)
output.write(' "')
for value in values:
output.write(CMakeStringEscape(value))
output.write(sep)
output.write('")\n')
def SetTargetProperty(output, target_name, property_name, values, sep=''):
"""Given a target, sets the given property."""
output.write('set_target_properties(')
output.write(target_name)
output.write(' PROPERTIES ')
output.write(property_name)
output.write(' "')
for value in values:
output.write(CMakeStringEscape(value))
output.write(sep)
output.write('")\n')
def SetVariable(output, variable_name, value):
"""Sets a CMake variable."""
output.write('set(')
output.write(variable_name)
output.write(' "')
output.write(CMakeStringEscape(value))
output.write('")\n')
def SetVariableList(output, variable_name, values):
"""Sets a CMake variable to a list."""
if not values:
return SetVariable(output, variable_name, "")
if len(values) == 1:
return SetVariable(output, variable_name, values[0])
output.write('list(APPEND ')
output.write(variable_name)
output.write('\n "')
output.write('"\n "'.join([CMakeStringEscape(value) for value in values]))
output.write('")\n')
def UnsetVariable(output, variable_name):
"""Unsets a CMake variable."""
output.write('unset(')
output.write(variable_name)
output.write(')\n')
def WriteVariable(output, variable_name, prepend=None):
if prepend:
output.write(prepend)
output.write('${')
output.write(variable_name)
output.write('}')
class CMakeTargetType(object):
def __init__(self, command, modifier, property_modifier):
self.command = command
self.modifier = modifier
self.property_modifier = property_modifier
cmake_target_type_from_gyp_target_type = {
'executable': CMakeTargetType('add_executable', None, 'RUNTIME'),
'static_library': CMakeTargetType('add_library', 'STATIC', 'ARCHIVE'),
'shared_library': CMakeTargetType('add_library', 'SHARED', 'LIBRARY'),
'loadable_module': CMakeTargetType('add_library', 'MODULE', 'LIBRARY'),
'none': CMakeTargetType('add_custom_target', 'SOURCES', None),
}
def StringToCMakeTargetName(a):
"""Converts the given string 'a' to a valid CMake target name.
All invalid characters are replaced by '_'.
Invalid for cmake: ' ', '/', '(', ')', '"'
Invalid for make: ':'
Invalid for unknown reasons but cause failures: '.'
"""
return a.translate(string.maketrans(' /():."', '_______'))
def WriteActions(target_name, actions, extra_sources, extra_deps,
path_to_gyp, output):
"""Write CMake for the 'actions' in the target.
Args:
target_name: the name of the CMake target being generated.
actions: the Gyp 'actions' dict for this target.
extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
extra_deps: [<cmake_taget>] to append with generated targets.
path_to_gyp: relative path from CMakeLists.txt being generated to
the Gyp file in which the target being generated is defined.
"""
for action in actions:
action_name = StringToCMakeTargetName(action['action_name'])
action_target_name = '%s__%s' % (target_name, action_name)
inputs = action['inputs']
inputs_name = action_target_name + '__input'
SetVariableList(output, inputs_name,
[NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs])
outputs = action['outputs']
cmake_outputs = [NormjoinPathForceCMakeSource(path_to_gyp, out)
for out in outputs]
outputs_name = action_target_name + '__output'
SetVariableList(output, outputs_name, cmake_outputs)
# Build up a list of outputs.
# Collect the output dirs we'll need.
dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir)
if int(action.get('process_outputs_as_sources', False)):
extra_sources.extend(zip(cmake_outputs, outputs))
# add_custom_command
output.write('add_custom_command(OUTPUT ')
WriteVariable(output, outputs_name)
output.write('\n')
if len(dirs) > 0:
for directory in dirs:
output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ')
output.write(directory)
output.write('\n')
output.write(' COMMAND ')
output.write(gyp.common.EncodePOSIXShellList(action['action']))
output.write('\n')
output.write(' DEPENDS ')
WriteVariable(output, inputs_name)
output.write('\n')
output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/')
output.write(path_to_gyp)
output.write('\n')
output.write(' COMMENT ')
if 'message' in action:
output.write(action['message'])
else:
output.write(action_target_name)
output.write('\n')
output.write(' VERBATIM\n')
output.write(')\n')
# add_custom_target
output.write('add_custom_target(')
output.write(action_target_name)
output.write('\n DEPENDS ')
WriteVariable(output, outputs_name)
output.write('\n SOURCES ')
WriteVariable(output, inputs_name)
output.write('\n)\n')
extra_deps.append(action_target_name)
def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source):
if rel_path.startswith(("${RULE_INPUT_PATH}","${RULE_INPUT_DIRNAME}")):
if any([rule_source.startswith(var) for var in FULL_PATH_VARS]):
return rel_path
return NormjoinPathForceCMakeSource(base_path, rel_path)
def WriteRules(target_name, rules, extra_sources, extra_deps,
path_to_gyp, output):
"""Write CMake for the 'rules' in the target.
Args:
target_name: the name of the CMake target being generated.
actions: the Gyp 'actions' dict for this target.
extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
extra_deps: [<cmake_taget>] to append with generated targets.
path_to_gyp: relative path from CMakeLists.txt being generated to
the Gyp file in which the target being generated is defined.
"""
for rule in rules:
rule_name = StringToCMakeTargetName(target_name + '__' + rule['rule_name'])
inputs = rule.get('inputs', [])
inputs_name = rule_name + '__input'
SetVariableList(output, inputs_name,
[NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs])
outputs = rule['outputs']
var_outputs = []
for count, rule_source in enumerate(rule.get('rule_sources', [])):
action_name = rule_name + '_' + str(count)
rule_source_dirname, rule_source_basename = os.path.split(rule_source)
rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename)
SetVariable(output, 'RULE_INPUT_PATH', rule_source)
SetVariable(output, 'RULE_INPUT_DIRNAME', rule_source_dirname)
SetVariable(output, 'RULE_INPUT_NAME', rule_source_basename)
SetVariable(output, 'RULE_INPUT_ROOT', rule_source_root)
SetVariable(output, 'RULE_INPUT_EXT', rule_source_ext)
# Build up a list of outputs.
# Collect the output dirs we'll need.
dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir)
# Create variables for the output, as 'local' variable will be unset.
these_outputs = []
for output_index, out in enumerate(outputs):
output_name = action_name + '_' + str(output_index)
SetVariable(output, output_name,
NormjoinRulePathForceCMakeSource(path_to_gyp, out,
rule_source))
if int(rule.get('process_outputs_as_sources', False)):
extra_sources.append(('${' + output_name + '}', out))
these_outputs.append('${' + output_name + '}')
var_outputs.append('${' + output_name + '}')
# add_custom_command
output.write('add_custom_command(OUTPUT\n')
for out in these_outputs:
output.write(' ')
output.write(out)
output.write('\n')
for directory in dirs:
output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ')
output.write(directory)
output.write('\n')
output.write(' COMMAND ')
output.write(gyp.common.EncodePOSIXShellList(rule['action']))
output.write('\n')
output.write(' DEPENDS ')
WriteVariable(output, inputs_name)
output.write(' ')
output.write(NormjoinPath(path_to_gyp, rule_source))
output.write('\n')
# CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives.
# The cwd is the current build directory.
output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/')
output.write(path_to_gyp)
output.write('\n')
output.write(' COMMENT ')
if 'message' in rule:
output.write(rule['message'])
else:
output.write(action_name)
output.write('\n')
output.write(' VERBATIM\n')
output.write(')\n')
UnsetVariable(output, 'RULE_INPUT_PATH')
UnsetVariable(output, 'RULE_INPUT_DIRNAME')
UnsetVariable(output, 'RULE_INPUT_NAME')
UnsetVariable(output, 'RULE_INPUT_ROOT')
UnsetVariable(output, 'RULE_INPUT_EXT')
# add_custom_target
output.write('add_custom_target(')
output.write(rule_name)
output.write(' DEPENDS\n')
for out in var_outputs:
output.write(' ')
output.write(out)
output.write('\n')
output.write('SOURCES ')
WriteVariable(output, inputs_name)
output.write('\n')
for rule_source in rule.get('rule_sources', []):
output.write(' ')
output.write(NormjoinPath(path_to_gyp, rule_source))
output.write('\n')
output.write(')\n')
extra_deps.append(rule_name)
def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output):
"""Write CMake for the 'copies' in the target.
Args:
target_name: the name of the CMake target being generated.
actions: the Gyp 'actions' dict for this target.
extra_deps: [<cmake_taget>] to append with generated targets.
path_to_gyp: relative path from CMakeLists.txt being generated to
the Gyp file in which the target being generated is defined.
"""
copy_name = target_name + '__copies'
# CMake gets upset with custom targets with OUTPUT which specify no output.
have_copies = any(copy['files'] for copy in copies)
if not have_copies:
output.write('add_custom_target(')
output.write(copy_name)
output.write(')\n')
extra_deps.append(copy_name)
return
class Copy(object):
def __init__(self, ext, command):
self.cmake_inputs = []
self.cmake_outputs = []
self.gyp_inputs = []
self.gyp_outputs = []
self.ext = ext
self.inputs_name = None
self.outputs_name = None
self.command = command
file_copy = Copy('', 'copy')
dir_copy = Copy('_dirs', 'copy_directory')
for copy in copies:
files = copy['files']
destination = copy['destination']
for src in files:
path = os.path.normpath(src)
basename = os.path.split(path)[1]
dst = os.path.join(destination, basename)
copy = file_copy if os.path.basename(src) else dir_copy
copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src))
copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst))
copy.gyp_inputs.append(src)
copy.gyp_outputs.append(dst)
for copy in (file_copy, dir_copy):
if copy.cmake_inputs:
copy.inputs_name = copy_name + '__input' + copy.ext
SetVariableList(output, copy.inputs_name, copy.cmake_inputs)
copy.outputs_name = copy_name + '__output' + copy.ext
SetVariableList(output, copy.outputs_name, copy.cmake_outputs)
# add_custom_command
output.write('add_custom_command(\n')
output.write('OUTPUT')
for copy in (file_copy, dir_copy):
if copy.outputs_name:
WriteVariable(output, copy.outputs_name, ' ')
output.write('\n')
for copy in (file_copy, dir_copy):
for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs):
# 'cmake -E copy src dst' will create the 'dst' directory if needed.
output.write('COMMAND ${CMAKE_COMMAND} -E %s ' % copy.command)
output.write(src)
output.write(' ')
output.write(dst)
output.write("\n")
output.write('DEPENDS')
for copy in (file_copy, dir_copy):
if copy.inputs_name:
WriteVariable(output, copy.inputs_name, ' ')
output.write('\n')
output.write('WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/')
output.write(path_to_gyp)
output.write('\n')
output.write('COMMENT Copying for ')
output.write(target_name)
output.write('\n')
output.write('VERBATIM\n')
output.write(')\n')
# add_custom_target
output.write('add_custom_target(')
output.write(copy_name)
output.write('\n DEPENDS')
for copy in (file_copy, dir_copy):
if copy.outputs_name:
WriteVariable(output, copy.outputs_name, ' ')
output.write('\n SOURCES')
if file_copy.inputs_name:
WriteVariable(output, file_copy.inputs_name, ' ')
output.write('\n)\n')
extra_deps.append(copy_name)
def CreateCMakeTargetBaseName(qualified_target):
"""This is the name we would like the target to have."""
_, gyp_target_name, gyp_target_toolset = (
gyp.common.ParseQualifiedTarget(qualified_target))
cmake_target_base_name = gyp_target_name
if gyp_target_toolset and gyp_target_toolset != 'target':
cmake_target_base_name += '_' + gyp_target_toolset
return StringToCMakeTargetName(cmake_target_base_name)
def CreateCMakeTargetFullName(qualified_target):
"""An unambiguous name for the target."""
gyp_file, gyp_target_name, gyp_target_toolset = (
gyp.common.ParseQualifiedTarget(qualified_target))
cmake_target_full_name = gyp_file + ':' + gyp_target_name
if gyp_target_toolset and gyp_target_toolset != 'target':
cmake_target_full_name += '_' + gyp_target_toolset
return StringToCMakeTargetName(cmake_target_full_name)
class CMakeNamer(object):
"""Converts Gyp target names into CMake target names.
CMake requires that target names be globally unique. One way to ensure
this is to fully qualify the names of the targets. Unfortunatly, this
ends up with all targets looking like "chrome_chrome_gyp_chrome" instead
of just "chrome". If this generator were only interested in building, it
would be possible to fully qualify all target names, then create
unqualified target names which depend on all qualified targets which
should have had that name. This is more or less what the 'make' generator
does with aliases. However, one goal of this generator is to create CMake
files for use with IDEs, and fully qualified names are not as user
friendly.
Since target name collision is rare, we do the above only when required.
Toolset variants are always qualified from the base, as this is required for
building. However, it also makes sense for an IDE, as it is possible for
defines to be different.
"""
def __init__(self, target_list):
self.cmake_target_base_names_conficting = set()
cmake_target_base_names_seen = set()
for qualified_target in target_list:
cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target)
if cmake_target_base_name not in cmake_target_base_names_seen:
cmake_target_base_names_seen.add(cmake_target_base_name)
else:
self.cmake_target_base_names_conficting.add(cmake_target_base_name)
def CreateCMakeTargetName(self, qualified_target):
base_name = CreateCMakeTargetBaseName(qualified_target)
if base_name in self.cmake_target_base_names_conficting:
return CreateCMakeTargetFullName(qualified_target)
return base_name
def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
options, generator_flags, all_qualified_targets, output):
# The make generator does this always.
# TODO: It would be nice to be able to tell CMake all dependencies.
circular_libs = generator_flags.get('circular', True)
if not generator_flags.get('standalone', False):
output.write('\n#')
output.write(qualified_target)
output.write('\n')
gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir)
rel_gyp_dir = os.path.dirname(rel_gyp_file)
# Relative path from build dir to top dir.
build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
# Relative path from build dir to gyp dir.
build_to_gyp = os.path.join(build_to_top, rel_gyp_dir)
path_from_cmakelists_to_gyp = build_to_gyp
spec = target_dicts.get(qualified_target, {})
config = spec.get('configurations', {}).get(config_to_use, {})
target_name = spec.get('target_name', '<missing target name>')
target_type = spec.get('type', '<missing target type>')
target_toolset = spec.get('toolset')
cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type)
if cmake_target_type is None:
print ('Target %s has unknown target type %s, skipping.' %
( target_name, target_type ) )
return
SetVariable(output, 'TARGET', target_name)
SetVariable(output, 'TOOLSET', target_toolset)
cmake_target_name = namer.CreateCMakeTargetName(qualified_target)
extra_sources = []
extra_deps = []
# Actions must come first, since they can generate more OBJs for use below.
if 'actions' in spec:
WriteActions(cmake_target_name, spec['actions'], extra_sources, extra_deps,
path_from_cmakelists_to_gyp, output)
# Rules must be early like actions.
if 'rules' in spec:
WriteRules(cmake_target_name, spec['rules'], extra_sources, extra_deps,
path_from_cmakelists_to_gyp, output)
# Copies
if 'copies' in spec:
WriteCopies(cmake_target_name, spec['copies'], extra_deps,
path_from_cmakelists_to_gyp, output)
# Target and sources
srcs = spec.get('sources', [])
# Gyp separates the sheep from the goats based on file extensions.
# A full separation is done here because of flag handing (see below).
s_sources = []
c_sources = []
cxx_sources = []
linkable_sources = []
other_sources = []
for src in srcs:
_, ext = os.path.splitext(src)
src_type = COMPILABLE_EXTENSIONS.get(ext, None)
src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src);
if src_type == 's':
s_sources.append(src_norm_path)
elif src_type == 'cc':
c_sources.append(src_norm_path)
elif src_type == 'cxx':
cxx_sources.append(src_norm_path)
elif Linkable(ext):
linkable_sources.append(src_norm_path)
else:
other_sources.append(src_norm_path)
for extra_source in extra_sources:
src, real_source = extra_source
_, ext = os.path.splitext(real_source)
src_type = COMPILABLE_EXTENSIONS.get(ext, None)
if src_type == 's':
s_sources.append(src)
elif src_type == 'cc':
c_sources.append(src)
elif src_type == 'cxx':
cxx_sources.append(src)
elif Linkable(ext):
linkable_sources.append(src)
else:
other_sources.append(src)
s_sources_name = None
if s_sources:
s_sources_name = cmake_target_name + '__asm_srcs'
SetVariableList(output, s_sources_name, s_sources)
c_sources_name = None
if c_sources:
c_sources_name = cmake_target_name + '__c_srcs'
SetVariableList(output, c_sources_name, c_sources)
cxx_sources_name = None
if cxx_sources:
cxx_sources_name = cmake_target_name + '__cxx_srcs'
SetVariableList(output, cxx_sources_name, cxx_sources)
linkable_sources_name = None
if linkable_sources:
linkable_sources_name = cmake_target_name + '__linkable_srcs'
SetVariableList(output, linkable_sources_name, linkable_sources)
other_sources_name = None
if other_sources:
other_sources_name = cmake_target_name + '__other_srcs'
SetVariableList(output, other_sources_name, other_sources)
# CMake gets upset when executable targets provide no sources.
# http://www.cmake.org/pipermail/cmake/2010-July/038461.html
dummy_sources_name = None
has_sources = (s_sources_name or
c_sources_name or
cxx_sources_name or
linkable_sources_name or
other_sources_name)
if target_type == 'executable' and not has_sources:
dummy_sources_name = cmake_target_name + '__dummy_srcs'
SetVariable(output, dummy_sources_name,
"${obj}.${TOOLSET}/${TARGET}/genc/dummy.c")
output.write('if(NOT EXISTS "')
WriteVariable(output, dummy_sources_name)
output.write('")\n')
output.write(' file(WRITE "')
WriteVariable(output, dummy_sources_name)
output.write('" "")\n')
output.write("endif()\n")
# CMake is opposed to setting linker directories and considers the practice
# of setting linker directories dangerous. Instead, it favors the use of
# find_library and passing absolute paths to target_link_libraries.
# However, CMake does provide the command link_directories, which adds
# link directories to targets defined after it is called.
# As a result, link_directories must come before the target definition.
# CMake unfortunately has no means of removing entries from LINK_DIRECTORIES.
library_dirs = config.get('library_dirs')
if library_dirs is not None:
output.write('link_directories(')
for library_dir in library_dirs:
output.write(' ')
output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir))
output.write('\n')
output.write(')\n')
output.write(cmake_target_type.command)
output.write('(')
output.write(cmake_target_name)
if cmake_target_type.modifier is not None:
output.write(' ')
output.write(cmake_target_type.modifier)
if s_sources_name:
WriteVariable(output, s_sources_name, ' ')
if c_sources_name:
WriteVariable(output, c_sources_name, ' ')
if cxx_sources_name:
WriteVariable(output, cxx_sources_name, ' ')
if linkable_sources_name:
WriteVariable(output, linkable_sources_name, ' ')
if other_sources_name:
WriteVariable(output, other_sources_name, ' ')
if dummy_sources_name:
WriteVariable(output, dummy_sources_name, ' ')
output.write(')\n')
# Let CMake know if the 'all' target should depend on this target.
exclude_from_all = ('TRUE' if qualified_target not in all_qualified_targets
else 'FALSE')
SetTargetProperty(output, cmake_target_name,
'EXCLUDE_FROM_ALL', exclude_from_all)
for extra_target_name in extra_deps:
SetTargetProperty(output, extra_target_name,
'EXCLUDE_FROM_ALL', exclude_from_all)
# Output name and location.
if target_type != 'none':
# Link as 'C' if there are no other files
if not c_sources and not cxx_sources:
SetTargetProperty(output, cmake_target_name, 'LINKER_LANGUAGE', ['C'])
# Mark uncompiled sources as uncompiled.
if other_sources_name:
output.write('set_source_files_properties(')
WriteVariable(output, other_sources_name, '')
output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n')
# Mark object sources as linkable.
if linkable_sources_name:
output.write('set_source_files_properties(')
WriteVariable(output, other_sources_name, '')
output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n')
# Output directory
target_output_directory = spec.get('product_dir')
if target_output_directory is None:
if target_type in ('executable', 'loadable_module'):
target_output_directory = generator_default_variables['PRODUCT_DIR']
elif target_type == 'shared_library':
target_output_directory = '${builddir}/lib.${TOOLSET}'
elif spec.get('standalone_static_library', False):
target_output_directory = generator_default_variables['PRODUCT_DIR']
else:
base_path = gyp.common.RelativePath(os.path.dirname(gyp_file),
options.toplevel_dir)
target_output_directory = '${obj}.${TOOLSET}'
target_output_directory = (
os.path.join(target_output_directory, base_path))
cmake_target_output_directory = NormjoinPathForceCMakeSource(
path_from_cmakelists_to_gyp,
target_output_directory)
SetTargetProperty(output,
cmake_target_name,
cmake_target_type.property_modifier + '_OUTPUT_DIRECTORY',
cmake_target_output_directory)
# Output name
default_product_prefix = ''
default_product_name = target_name
default_product_ext = ''
if target_type == 'static_library':
static_library_prefix = generator_default_variables['STATIC_LIB_PREFIX']
default_product_name = RemovePrefix(default_product_name,
static_library_prefix)
default_product_prefix = static_library_prefix
default_product_ext = generator_default_variables['STATIC_LIB_SUFFIX']
elif target_type in ('loadable_module', 'shared_library'):
shared_library_prefix = generator_default_variables['SHARED_LIB_PREFIX']
default_product_name = RemovePrefix(default_product_name,
shared_library_prefix)
default_product_prefix = shared_library_prefix
default_product_ext = generator_default_variables['SHARED_LIB_SUFFIX']
elif target_type != 'executable':
print ('ERROR: What output file should be generated?',
'type', target_type, 'target', target_name)
product_prefix = spec.get('product_prefix', default_product_prefix)
product_name = spec.get('product_name', default_product_name)
product_ext = spec.get('product_extension')
if product_ext:
product_ext = '.' + product_ext
else:
product_ext = default_product_ext
SetTargetProperty(output, cmake_target_name, 'PREFIX', product_prefix)
SetTargetProperty(output, cmake_target_name,
cmake_target_type.property_modifier + '_OUTPUT_NAME',
product_name)
SetTargetProperty(output, cmake_target_name, 'SUFFIX', product_ext)
# Make the output of this target referenceable as a source.
cmake_target_output_basename = product_prefix + product_name + product_ext
cmake_target_output = os.path.join(cmake_target_output_directory,
cmake_target_output_basename)
SetFileProperty(output, cmake_target_output, 'GENERATED', ['TRUE'], '')
# Includes
includes = config.get('include_dirs')
if includes:
# This (target include directories) is what requires CMake 2.8.8
includes_name = cmake_target_name + '__include_dirs'
SetVariableList(output, includes_name,
[NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include)
for include in includes])
output.write('set_property(TARGET ')
output.write(cmake_target_name)
output.write(' APPEND PROPERTY INCLUDE_DIRECTORIES ')
WriteVariable(output, includes_name, '')
output.write(')\n')
# Defines
defines = config.get('defines')
if defines is not None:
SetTargetProperty(output,
cmake_target_name,
'COMPILE_DEFINITIONS',
defines,
';')
# Compile Flags - http://www.cmake.org/Bug/view.php?id=6493
# CMake currently does not have target C and CXX flags.
# So, instead of doing...
# cflags_c = config.get('cflags_c')
# if cflags_c is not None:
# SetTargetProperty(output, cmake_target_name,
# 'C_COMPILE_FLAGS', cflags_c, ' ')
# cflags_cc = config.get('cflags_cc')
# if cflags_cc is not None:
# SetTargetProperty(output, cmake_target_name,
# 'CXX_COMPILE_FLAGS', cflags_cc, ' ')
# Instead we must...
cflags = config.get('cflags', [])
cflags_c = config.get('cflags_c', [])
cflags_cxx = config.get('cflags_cc', [])
if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources):
SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', cflags, ' ')
elif c_sources and not (s_sources or cxx_sources):
flags = []
flags.extend(cflags)
flags.extend(cflags_c)
SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ')
elif cxx_sources and not (s_sources or c_sources):
flags = []
flags.extend(cflags)
flags.extend(cflags_cxx)
SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ')
else:
# TODO: This is broken, one cannot generally set properties on files,
# as other targets may require different properties on the same files.
if s_sources and cflags:
SetFilesProperty(output, s_sources_name, 'COMPILE_FLAGS', cflags, ' ')
if c_sources and (cflags or cflags_c):
flags = []
flags.extend(cflags)
flags.extend(cflags_c)
SetFilesProperty(output, c_sources_name, 'COMPILE_FLAGS', flags, ' ')
if cxx_sources and (cflags or cflags_cxx):
flags = []
flags.extend(cflags)
flags.extend(cflags_cxx)
SetFilesProperty(output, cxx_sources_name, 'COMPILE_FLAGS', flags, ' ')
# Linker flags
ldflags = config.get('ldflags')
if ldflags is not None:
SetTargetProperty(output, cmake_target_name, 'LINK_FLAGS', ldflags, ' ')
# Note on Dependencies and Libraries:
# CMake wants to handle link order, resolving the link line up front.
# Gyp does not retain or enforce specifying enough information to do so.
# So do as other gyp generators and use --start-group and --end-group.
# Give CMake as little information as possible so that it doesn't mess it up.
# Dependencies
rawDeps = spec.get('dependencies', [])
static_deps = []
shared_deps = []
other_deps = []
for rawDep in rawDeps:
dep_cmake_name = namer.CreateCMakeTargetName(rawDep)
dep_spec = target_dicts.get(rawDep, {})
dep_target_type = dep_spec.get('type', None)
if dep_target_type == 'static_library':
static_deps.append(dep_cmake_name)
elif dep_target_type == 'shared_library':
shared_deps.append(dep_cmake_name)
else:
other_deps.append(dep_cmake_name)
# ensure all external dependencies are complete before internal dependencies
# extra_deps currently only depend on their own deps, so otherwise run early
if static_deps or shared_deps or other_deps:
for extra_dep in extra_deps:
output.write('add_dependencies(')
output.write(extra_dep)
output.write('\n')
for deps in (static_deps, shared_deps, other_deps):
for dep in gyp.common.uniquer(deps):
output.write(' ')
output.write(dep)
output.write('\n')
output.write(')\n')
linkable = target_type in ('executable', 'loadable_module', 'shared_library')
other_deps.extend(extra_deps)
if other_deps or (not linkable and (static_deps or shared_deps)):
output.write('add_dependencies(')
output.write(cmake_target_name)
output.write('\n')
for dep in gyp.common.uniquer(other_deps):
output.write(' ')
output.write(dep)
output.write('\n')
if not linkable:
for deps in (static_deps, shared_deps):
for lib_dep in gyp.common.uniquer(deps):
output.write(' ')
output.write(lib_dep)
output.write('\n')
output.write(')\n')
# Libraries
if linkable:
external_libs = [lib for lib in spec.get('libraries', []) if len(lib) > 0]
if external_libs or static_deps or shared_deps:
output.write('target_link_libraries(')
output.write(cmake_target_name)
output.write('\n')
if static_deps:
write_group = circular_libs and len(static_deps) > 1
if write_group:
output.write('-Wl,--start-group\n')
for dep in gyp.common.uniquer(static_deps):
output.write(' ')
output.write(dep)
output.write('\n')
if write_group:
output.write('-Wl,--end-group\n')
if shared_deps:
for dep in gyp.common.uniquer(shared_deps):
output.write(' ')
output.write(dep)
output.write('\n')
if external_libs:
for lib in gyp.common.uniquer(external_libs):
output.write(' ')
output.write(lib)
output.write('\n')
output.write(')\n')
UnsetVariable(output, 'TOOLSET')
UnsetVariable(output, 'TARGET')
def GenerateOutputForConfig(target_list, target_dicts, data,
params, config_to_use):
options = params['options']
generator_flags = params['generator_flags']
# generator_dir: relative path from pwd to where make puts build files.
# Makes migrating from make to cmake easier, cmake doesn't put anything here.
# Each Gyp configuration creates a different CMakeLists.txt file
# to avoid incompatibilities between Gyp and CMake configurations.
generator_dir = os.path.relpath(options.generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
# build_dir: relative path from source root to our output files.
# e.g. "out/Debug"
build_dir = os.path.normpath(os.path.join(generator_dir,
output_dir,
config_to_use))
toplevel_build = os.path.join(options.toplevel_dir, build_dir)
output_file = os.path.join(toplevel_build, 'CMakeLists.txt')
gyp.common.EnsureDirExists(output_file)
output = open(output_file, 'w')
output.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n')
output.write('cmake_policy(VERSION 2.8.8)\n')
gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1])
output.write('project(')
output.write(project_target)
output.write(')\n')
SetVariable(output, 'configuration', config_to_use)
ar = None
cc = None
cxx = None
make_global_settings = data[gyp_file].get('make_global_settings', [])
build_to_top = gyp.common.InvertRelativePath(build_dir,
options.toplevel_dir)
for key, value in make_global_settings:
if key == 'AR':
ar = os.path.join(build_to_top, value)
if key == 'CC':
cc = os.path.join(build_to_top, value)
if key == 'CXX':
cxx = os.path.join(build_to_top, value)
ar = gyp.common.GetEnvironFallback(['AR_target', 'AR'], ar)
cc = gyp.common.GetEnvironFallback(['CC_target', 'CC'], cc)
cxx = gyp.common.GetEnvironFallback(['CXX_target', 'CXX'], cxx)
if ar:
SetVariable(output, 'CMAKE_AR', ar)
if cc:
SetVariable(output, 'CMAKE_C_COMPILER', cc)
if cxx:
SetVariable(output, 'CMAKE_CXX_COMPILER', cxx)
# The following appears to be as-yet undocumented.
# http://public.kitware.com/Bug/view.php?id=8392
output.write('enable_language(ASM)\n')
# ASM-ATT does not support .S files.
# output.write('enable_language(ASM-ATT)\n')
if cc:
SetVariable(output, 'CMAKE_ASM_COMPILER', cc)
SetVariable(output, 'builddir', '${CMAKE_CURRENT_BINARY_DIR}')
SetVariable(output, 'obj', '${builddir}/obj')
output.write('\n')
# TODO: Undocumented/unsupported (the CMake Java generator depends on it).
# CMake by default names the object resulting from foo.c to be foo.c.o.
# Gyp traditionally names the object resulting from foo.c foo.o.
# This should be irrelevant, but some targets extract .o files from .a
# and depend on the name of the extracted .o files.
output.write('set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n')
output.write('set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n')
output.write('\n')
# Force ninja to use rsp files. Otherwise link and ar lines can get too long,
# resulting in 'Argument list too long' errors.
output.write('set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n')
output.write('\n')
namer = CMakeNamer(target_list)
# The list of targets upon which the 'all' target should depend.
# CMake has it's own implicit 'all' target, one is not created explicitly.
all_qualified_targets = set()
for build_file in params['build_files']:
for qualified_target in gyp.common.AllTargets(target_list,
target_dicts,
os.path.normpath(build_file)):
all_qualified_targets.add(qualified_target)
for qualified_target in target_list:
WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
options, generator_flags, all_qualified_targets, output)
output.close()
def PerformBuild(data, configurations, params):
options = params['options']
generator_flags = params['generator_flags']
# generator_dir: relative path from pwd to where make puts build files.
# Makes migrating from make to cmake easier, cmake doesn't put anything here.
generator_dir = os.path.relpath(options.generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
for config_name in configurations:
# build_dir: relative path from source root to our output files.
# e.g. "out/Debug"
build_dir = os.path.normpath(os.path.join(generator_dir,
output_dir,
config_name))
arguments = ['cmake', '-G', 'Ninja']
print 'Generating [%s]: %s' % (config_name, arguments)
subprocess.check_call(arguments, cwd=build_dir)
arguments = ['ninja', '-C', build_dir]
print 'Building [%s]: %s' % (config_name, arguments)
subprocess.check_call(arguments)
def CallGenerateOutputForConfig(arglist):
# Ignore the interrupt signal so that the parent process catches it and
# kills all multiprocessing children.
signal.signal(signal.SIGINT, signal.SIG_IGN)
target_list, target_dicts, data, params, config_name = arglist
GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
def GenerateOutput(target_list, target_dicts, data, params):
user_config = params.get('generator_flags', {}).get('config', None)
if user_config:
GenerateOutputForConfig(target_list, target_dicts, data,
params, user_config)
else:
config_names = target_dicts[target_list[0]]['configurations'].keys()
if params['parallel']:
try:
pool = multiprocessing.Pool(len(config_names))
arglists = []
for config_name in config_names:
arglists.append((target_list, target_dicts, data,
params, config_name))
pool.map(CallGenerateOutputForConfig, arglists)
except KeyboardInterrupt, e:
pool.terminate()
raise e
else:
for config_name in config_names:
GenerateOutputForConfig(target_list, target_dicts, data,
params, config_name)
|
aps-sids/zulip | refs/heads/master | confirmation/migrations/__init__.py | 12133432 | |
lwiecek/django | refs/heads/master | tests/raw_query/__init__.py | 12133432 | |
nextgis/nextgisweb | refs/heads/updates | nextgisweb/postgis/view.py | 1 | # -*- coding: utf-8 -*-
from __future__ import division, unicode_literals, print_function, absolute_import
from ..resource import Widget
from .model import PostgisConnection, PostgisLayer
class PostgisConnectionWidget(Widget):
resource = PostgisConnection
operation = ('create', 'update')
amdmod = 'ngw-postgis/ConnectionWidget'
class PostgisLayerWidget(Widget):
resource = PostgisLayer
operation = ('create', 'update')
amdmod = 'ngw-postgis/LayerWidget'
|
chauhanhardik/populo | refs/heads/master | lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py | 37 | """
Unit tests for instructor_dashboard.py.
"""
import ddt
from mock import patch
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test.utils import override_settings
from courseware.tabs import get_course_tab_list
from courseware.tests.factories import UserFactory
from courseware.tests.helpers import LoginEnrollmentTestCase
from common.test.utils import XssTestMixin
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from shoppingcart.models import PaidCourseRegistration, Order, CourseRegCodeItem
from course_modes.models import CourseMode
from student.roles import CourseFinanceAdminRole
from student.models import CourseEnrollment
@ddt.ddt
class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssTestMixin):
"""
Tests for the instructor dashboard (not legacy).
"""
def setUp(self):
"""
Set up tests
"""
super(TestInstructorDashboard, self).setUp()
self.course = CourseFactory.create(
grading_policy={"GRADE_CUTOFFS": {"A": 0.75, "B": 0.63, "C": 0.57, "D": 0.5}},
display_name='<script>alert("XSS")</script>'
)
self.course_mode = CourseMode(course_id=self.course.id,
mode_slug="honor",
mode_display_name="honor cert",
min_price=40)
self.course_mode.save()
# Create instructor account
self.instructor = AdminFactory.create()
self.client.login(username=self.instructor.username, password="test")
# URL for instructor dash
self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
def get_dashboard_enrollment_message(self):
"""
Returns expected dashboard enrollment message with link to Insights.
"""
return 'Enrollment data is now available in <a href="http://example.com/courses/{}" ' \
'target="_blank">Example</a>.'.format(unicode(self.course.id))
def get_dashboard_analytics_message(self):
"""
Returns expected dashboard demographic message with link to Insights.
"""
return 'For analytics about your course, go to <a href="http://example.com/courses/{}" ' \
'target="_blank">Example</a>.'.format(unicode(self.course.id))
def test_instructor_tab(self):
"""
Verify that the instructor tab appears for staff only.
"""
def has_instructor_tab(user, course):
"""Returns true if the "Instructor" tab is shown."""
request = RequestFactory().request()
request.user = user
tabs = get_course_tab_list(request, course)
return len([tab for tab in tabs if tab.name == 'Instructor']) == 1
self.assertTrue(has_instructor_tab(self.instructor, self.course))
student = UserFactory.create()
self.assertFalse(has_instructor_tab(student, self.course))
def test_default_currency_in_the_html_response(self):
"""
Test that checks the default currency_symbol ($) in the response
"""
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id)
response = self.client.get(self.url)
self.assertTrue('${amount}'.format(amount=total_amount) in response.content)
def test_course_name_xss(self):
"""Test that the instructor dashboard correctly escapes course names
with script tags.
"""
response = self.client.get(self.url)
self.assert_xss(response, '<script>alert("XSS")</script>')
@override_settings(PAID_COURSE_REGISTRATION_CURRENCY=['PKR', 'Rs'])
def test_override_currency_settings_in_the_html_response(self):
"""
Test that checks the default currency_symbol ($) in the response
"""
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id)
response = self.client.get(self.url)
self.assertIn('{currency}{amount}'.format(currency='Rs', amount=total_amount), response.content)
@patch.dict(settings.FEATURES, {'DISPLAY_ANALYTICS_ENROLLMENTS': False})
@override_settings(ANALYTICS_DASHBOARD_URL='')
def test_no_enrollments(self):
"""
Test enrollment section is hidden.
"""
response = self.client.get(self.url)
# no enrollment information should be visible
self.assertFalse('<h2>Enrollment Information</h2>' in response.content)
@patch.dict(settings.FEATURES, {'DISPLAY_ANALYTICS_ENROLLMENTS': True})
@override_settings(ANALYTICS_DASHBOARD_URL='')
def test_show_enrollments_data(self):
"""
Test enrollment data is shown.
"""
response = self.client.get(self.url)
# enrollment information visible
self.assertTrue('<h2>Enrollment Information</h2>' in response.content)
self.assertTrue('<td>Verified</td>' in response.content)
self.assertTrue('<td>Audit</td>' in response.content)
self.assertTrue('<td>Honor</td>' in response.content)
self.assertTrue('<td>Professional</td>' in response.content)
# dashboard link hidden
self.assertFalse(self.get_dashboard_enrollment_message() in response.content)
@patch.dict(settings.FEATURES, {'DISPLAY_ANALYTICS_ENROLLMENTS': True})
@override_settings(ANALYTICS_DASHBOARD_URL='')
def test_show_enrollment_data_for_prof_ed(self):
# Create both "professional" (meaning professional + verification)
# and "no-id-professional" (meaning professional without verification)
# These should be aggregated for display purposes.
users = [UserFactory() for _ in range(2)]
CourseEnrollment.enroll(users[0], self.course.id, mode="professional")
CourseEnrollment.enroll(users[1], self.course.id, mode="no-id-professional")
response = self.client.get(self.url)
# Check that the number of professional enrollments is two
self.assertContains(response, "<td>Professional</td><td>2</td>")
@patch.dict(settings.FEATURES, {'DISPLAY_ANALYTICS_ENROLLMENTS': False})
@override_settings(ANALYTICS_DASHBOARD_URL='http://example.com')
@override_settings(ANALYTICS_DASHBOARD_NAME='Example')
def test_show_dashboard_enrollment_message(self):
"""
Test enrollment dashboard message is shown and data is hidden.
"""
response = self.client.get(self.url)
# enrollment information hidden
self.assertFalse('<td>Verified</td>' in response.content)
self.assertFalse('<td>Audit</td>' in response.content)
self.assertFalse('<td>Honor</td>' in response.content)
self.assertFalse('<td>Professional</td>' in response.content)
# link to dashboard shown
expected_message = self.get_dashboard_enrollment_message()
self.assertTrue(expected_message in response.content)
@override_settings(ANALYTICS_DASHBOARD_URL='')
@override_settings(ANALYTICS_DASHBOARD_NAME='')
def test_dashboard_analytics_tab_not_shown(self):
"""
Test dashboard analytics tab isn't shown if insights isn't configured.
"""
response = self.client.get(self.url)
analytics_section = '<li class="nav-item"><a href="" data-section="instructor_analytics">Analytics</a></li>'
self.assertFalse(analytics_section in response.content)
@override_settings(ANALYTICS_DASHBOARD_URL='http://example.com')
@override_settings(ANALYTICS_DASHBOARD_NAME='Example')
def test_dashboard_analytics_points_at_insights(self):
"""
Test analytics dashboard message is shown
"""
response = self.client.get(self.url)
analytics_section = '<li class="nav-item"><a href="" data-section="instructor_analytics">Analytics</a></li>'
self.assertTrue(analytics_section in response.content)
# link to dashboard shown
expected_message = self.get_dashboard_analytics_message()
self.assertTrue(expected_message in response.content)
def add_course_to_user_cart(self, cart, course_key):
"""
adding course to user cart
"""
reg_item = PaidCourseRegistration.add_to_order(cart, course_key)
return reg_item
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_PAID_COURSE_REGISTRATION': True})
def test_total_credit_cart_sales_amount(self):
"""
Test to check the total amount for all the credit card purchases.
"""
student = UserFactory.create()
self.client.login(username=student.username, password="test")
student_cart = Order.get_cart_for_user(student)
item = self.add_course_to_user_cart(student_cart, self.course.id)
resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': item.id, 'qty': 4})
self.assertEqual(resp.status_code, 200)
student_cart.purchase()
self.client.login(username=self.instructor.username, password="test")
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
single_purchase_total = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id)
bulk_purchase_total = CourseRegCodeItem.get_total_amount_of_purchased_item(self.course.id)
total_amount = single_purchase_total + bulk_purchase_total
response = self.client.get(self.url)
self.assertIn('{currency}{amount}'.format(currency='$', amount=total_amount), response.content)
@ddt.data(
(True, True, True),
(True, False, False),
(True, None, False),
(False, True, False),
(False, False, False),
(False, None, False),
)
@ddt.unpack
def test_ccx_coaches_option_on_admin_list_management_instructor(
self, ccx_feature_flag, enable_ccx, expected_result
):
"""
Test whether the "CCX Coaches" option is visible or hidden depending on the value of course.enable_ccx.
"""
with patch.dict(settings.FEATURES, {'CUSTOM_COURSES_EDX': ccx_feature_flag}):
self.course.enable_ccx = enable_ccx
self.store.update_item(self.course, self.instructor.id)
response = self.client.get(self.url)
self.assertEquals(
expected_result,
'CCX Coaches are able to create their own Custom Courses based on this course' in response.content
)
def test_grade_cutoffs(self):
"""
Verify that grade cutoffs are displayed in the correct order.
"""
response = self.client.get(self.url)
self.assertIn('D: 0.5, C: 0.57, B: 0.63, A: 0.75', response.content)
|
hramrach/osc | refs/heads/master | osc/babysitter.py | 2 | # Copyright (C) 2008 Novell Inc. All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or (at your option) any later version.
from __future__ import print_function
import errno
import os.path
import pdb
import sys
import signal
import traceback
from urlgrabber.grabber import URLGrabError
from osc import oscerr
from .oscsslexcp import NoSecureSSLError
from osc.util.cpio import CpioError
from osc.util.packagequery import PackageError
try:
from M2Crypto.SSL.Checker import SSLVerificationError
from M2Crypto.SSL import SSLError as SSLError
except:
SSLError = None
SSLVerificationError = None
try:
# import as RPMError because the class "error" is too generic
from rpm import error as RPMError
except:
# if rpm-python isn't installed (we might be on a debian system):
RPMError = None
try:
from http.client import HTTPException, BadStatusLine
from urllib.error import URLError, HTTPError
except ImportError:
#python 2.x
from httplib import HTTPException, BadStatusLine
from urllib2 import URLError, HTTPError
# the good things are stolen from Matt Mackall's mercurial
def catchterm(*args):
raise oscerr.SignalInterrupt
for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
num = getattr(signal, name, None)
if num:
signal.signal(num, catchterm)
def run(prg, argv=None):
try:
try:
if '--debugger' in sys.argv:
pdb.set_trace()
# here we actually run the program:
return prg.main(argv)
except:
# look for an option in the prg.options object and in the config
# dict print stack trace, if desired
if getattr(prg.options, 'traceback', None) or getattr(prg.conf, 'config', {}).get('traceback', None) or \
getattr(prg.options, 'post_mortem', None) or getattr(prg.conf, 'config', {}).get('post_mortem', None):
traceback.print_exc(file=sys.stderr)
# we could use http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215
# enter the debugger, if desired
if getattr(prg.options, 'post_mortem', None) or getattr(prg.conf, 'config', {}).get('post_mortem', None):
if sys.stdout.isatty() and not hasattr(sys, 'ps1'):
pdb.post_mortem(sys.exc_info()[2])
else:
print('sys.stdout is not a tty. Not jumping into pdb.', file=sys.stderr)
raise
except oscerr.SignalInterrupt:
print('killed!', file=sys.stderr)
return 1
except KeyboardInterrupt:
print('interrupted!', file=sys.stderr)
return 130
except oscerr.UserAbort:
print('aborted.', file=sys.stderr)
return 1
except oscerr.APIError as e:
print('BuildService API error:', e.msg, file=sys.stderr)
return 1
except oscerr.LinkExpandError as e:
print('Link "%s/%s" cannot be expanded:\n' % (e.prj, e.pac), e.msg, file=sys.stderr)
print('Use "osc repairlink" to fix merge conflicts.\n', file=sys.stderr)
return 1
except oscerr.WorkingCopyWrongVersion as e:
print(e, file=sys.stderr)
return 1
except oscerr.NoWorkingCopy as e:
print(e, file=sys.stderr)
if os.path.isdir('.git'):
print("Current directory looks like git.", file=sys.stderr)
if os.path.isdir('.hg'):
print("Current directory looks like mercurial.", file=sys.stderr)
if os.path.isdir('.svn'):
print("Current directory looks like svn.", file=sys.stderr)
if os.path.isdir('CVS'):
print("Current directory looks like cvs.", file=sys.stderr)
return 1
except HTTPError as e:
print('Server returned an error:', e, file=sys.stderr)
if hasattr(e, 'osc_msg'):
print(e.osc_msg, file=sys.stderr)
try:
body = e.read()
except AttributeError:
body = ''
if getattr(prg.options, 'debug', None) or \
getattr(prg.conf, 'config', {}).get('debug', None):
print(e.hdrs, file=sys.stderr)
print(body, file=sys.stderr)
if e.code in [400, 403, 404, 500]:
if '<summary>' in body:
msg = body.split('<summary>')[1]
msg = msg.split('</summary>')[0]
msg = msg.replace('<', '<').replace('>' , '>').replace('&', '&')
print(msg, file=sys.stderr)
if e.code >= 500 and e.code <= 599:
print('\nRequest: %s' % e.filename)
print('Headers:')
for h, v in e.hdrs.items():
if h != 'Set-Cookie':
print("%s: %s" % (h, v))
return 1
except BadStatusLine as e:
print('Server returned an invalid response:', e, file=sys.stderr)
print(e.line, file=sys.stderr)
return 1
except HTTPException as e:
print(e, file=sys.stderr)
return 1
except URLError as e:
print('Failed to reach a server:\n', e.reason, file=sys.stderr)
return 1
except URLGrabError as e:
print('Failed to grab %s: %s' % (e.url, e.exception), file=sys.stderr)
return 1
except IOError as e:
# ignore broken pipe
if e.errno != errno.EPIPE:
raise
return 1
except OSError as e:
if e.errno != errno.ENOENT:
raise
print(e, file=sys.stderr)
return 1
except (oscerr.ConfigError, oscerr.NoConfigfile) as e:
print(e.msg, file=sys.stderr)
return 1
except oscerr.OscIOError as e:
print(e.msg, file=sys.stderr)
if getattr(prg.options, 'debug', None) or \
getattr(prg.conf, 'config', {}).get('debug', None):
print(e.e, file=sys.stderr)
return 1
except (oscerr.WrongOptions, oscerr.WrongArgs) as e:
print(e, file=sys.stderr)
return 2
except oscerr.ExtRuntimeError as e:
print(e.file + ':', e.msg, file=sys.stderr)
return 1
except oscerr.ServiceRuntimeError as e:
print(e.msg, file=sys.stderr)
except oscerr.WorkingCopyOutdated as e:
print(e, file=sys.stderr)
return 1
except (oscerr.PackageExists, oscerr.PackageMissing, oscerr.WorkingCopyInconsistent) as e:
print(e.msg, file=sys.stderr)
return 1
except oscerr.PackageInternalError as e:
print('a package internal error occured\n' \
'please file a bug and attach your current package working copy ' \
'and the following traceback to it:', file=sys.stderr)
print(e.msg, file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return 1
except oscerr.PackageError as e:
print(e.msg, file=sys.stderr)
return 1
except PackageError as e:
print('%s:' % e.fname, e.msg, file=sys.stderr)
return 1
except RPMError as e:
print(e, file=sys.stderr)
return 1
except SSLError as e:
print("SSL Error:", e, file=sys.stderr)
return 1
except SSLVerificationError as e:
print("Certificate Verification Error:", e, file=sys.stderr)
return 1
except NoSecureSSLError as e:
print(e, file=sys.stderr)
return 1
except CpioError as e:
print(e, file=sys.stderr)
return 1
except oscerr.OscBaseError as e:
print('*** Error:', e, file=sys.stderr)
return 1
# vim: sw=4 et
|
village-people/flying-pig | refs/heads/master | ai_challenge/evaluator.py | 1 | # Village People, 2017
import torch
import torch.multiprocessing as mp
from models import get_model
from termcolor import colored as clr
from time import sleep
class Evaluator(mp.Process):
def __init__(self, shared_objects, config):
super(Evaluator, self).__init__()
self.shared_objects = shared_objects
self.config = config
def run(self):
config = self.config
torch.set_num_threads(config.num_threads)
self.stats = stats = self.shared_objects["stats_leRMS"]
self.shared_model = shared_model = self.shared_objects["model"]
self.model = model = get_model(config.model.name)(config.model)
if config.use_cuda:
model.cuda()
start_at, stop_at = config.start_at, config.stop_at
eval_every = config.frequency
last_eval_at = -eval_every
crt_episode = stats.get_episodes()
while crt_episode < stop_at:
if crt_episode > start_at and crt_episode > last_eval + eval_every:
last_eval = crt_episode
model.load_state_dict(shared_model.state_dict())
self.start_evaluation(crt_episode)
else:
print("not yet")
sleep(1)
crt_episode = stats.get_episodes()
self.info("Evaluation done")
def start_evaluation(self, crt_episode):
config = self.config
eval_episodes = config.episodes
clients = config.clients
self.info("Evaluation started at {:d}".format(crt_episode))
env = PigChaseEnvironment(clients,
self.state_builder,
role=1,
randomize_positions=True)
alien = mp.Process(run_alien, args=(clients, eval_episodes))
alien.start()
sleep(5)
self.metrics[crt_episode] = metrics = []
agent_loop(self.model, env, eval_episodes, metrics)
alien.join()
from numpy import mean, var
m, v = mean(metircs), var(metrics)
if self.best_m is None or m > self.best_m:
m_str = clr("{:2.4f}".format(m), "white", "on_magenta")
self.best_m = m
else:
m_str = clr("{:2.4f}".format(m), "red")
self.info("Rewards: Mean={:s}, Var={:2.4f}".format(m_str, v))
def info(self, message):
print(clr("[EVAL] ", "red") + message)
def run_alien(clients, eval_episodes):
builder = PigChaseSymbolicStateBuilder()
env = PigChaseEnvironment(clients, builder, role=0,
randomize_positions=True)
agent = PigChaseChallengeAgent("Alien")
agent_loop(agent, env, eval_episodes)
def agent_loop(agent, env, eval_episodes, metrics_acc=None):
"""Adapted from pig_chase/evaluation.py"""
agent_done = False
reward = 0
episode = 0
obs = env.reset()
it = 0
while episode < eval_episodes:
if env.done:
obs = env.reset()
while obs is None:
obs = env.reset()
episode += 1
it += 1
action = agent.act(obs, reward, agent_done, is_training=False)
obs, reward, agent_done = env.do(action)
if metrics_acc is not None:
metrics_acc.append(reward)
|
chauhanhardik/populo | refs/heads/master | common/lib/xmodule/xmodule/open_ended_grading_classes/grading_service_module.py | 106 | # This class gives a common interface for logging into the grading controller
import logging
import requests
import dogstats_wrapper as dog_stats_api
from lxml import etree
from requests.exceptions import RequestException, ConnectionError, HTTPError
from .combined_open_ended_rubric import CombinedOpenEndedRubric, RubricParsingError
log = logging.getLogger(__name__)
class GradingServiceError(Exception):
"""
Exception for grading service. Shown when Open Response Assessment servers cannot be reached.
"""
pass
class GradingService(object):
"""
Interface to staff grading backend.
"""
def __init__(self, config):
self.username = config['username']
self.password = config['password']
self.session = requests.Session()
self.render_template = config['render_template']
def _login(self):
"""
Log into the staff grading service.
Raises requests.exceptions.HTTPError if something goes wrong.
Returns the decoded json dict of the response.
"""
response = self.session.post(self.login_url,
{'username': self.username,
'password': self.password, })
response.raise_for_status()
return response.json()
def _metric_name(self, suffix):
"""
Return a metric name for datadog, using `self.METRIC_NAME` as
a prefix, and `suffix` as the suffix.
Arguments:
suffix (str): The metric suffix to use.
"""
return '{}.{}'.format(self.METRIC_NAME, suffix)
def _record_result(self, action, data, tags=None):
"""
Log results from an API call to an ORA service to datadog.
Arguments:
action (str): The ORA action being recorded.
data (dict): The data returned from the ORA service. Should contain the key 'success'.
tags (list): A list of tags to attach to the logged metric.
"""
if tags is None:
tags = []
tags.append(u'result:{}'.format(data.get('success', False)))
tags.append(u'action:{}'.format(action))
dog_stats_api.increment(self._metric_name('request.count'), tags=tags)
def post(self, url, data, allow_redirects=False):
"""
Make a post request to the grading controller. Returns the parsed json results of that request.
"""
try:
op = lambda: self.session.post(url, data=data,
allow_redirects=allow_redirects)
response_json = self._try_with_login(op)
except (RequestException, ConnectionError, HTTPError, ValueError) as err:
# reraise as promised GradingServiceError, but preserve stacktrace.
#This is a dev_facing_error
error_string = "Problem posting data to the grading controller. URL: {0}, data: {1}".format(url, data)
log.error(error_string)
raise GradingServiceError(error_string)
return response_json
def get(self, url, params, allow_redirects=False):
"""
Make a get request to the grading controller. Returns the parsed json results of that request.
"""
op = lambda: self.session.get(url,
allow_redirects=allow_redirects,
params=params)
try:
response_json = self._try_with_login(op)
except (RequestException, ConnectionError, HTTPError, ValueError) as err:
# reraise as promised GradingServiceError, but preserve stacktrace.
#This is a dev_facing_error
error_string = "Problem getting data from the grading controller. URL: {0}, params: {1}".format(url, params)
log.error(error_string)
raise GradingServiceError(error_string)
return response_json
def _try_with_login(self, operation):
"""
Call operation(), which should return a requests response object. If
the request fails with a 'login_required' error, call _login() and try
the operation again.
Returns the result of operation(). Does not catch exceptions.
"""
response = operation()
resp_json = response.json()
if (resp_json
and resp_json.get('success') is False
and resp_json.get('error') == 'login_required'):
# apparently we aren't logged in. Try to fix that.
r = self._login()
if r and not r.get('success'):
log.warning("Couldn't log into ORA backend. Response: %s",
r)
# try again
response = operation()
response.raise_for_status()
resp_json = response.json()
return resp_json
def _render_rubric(self, response, view_only=False):
"""
Given an HTTP Response json with the key 'rubric', render out the html
required to display the rubric and put it back into the response
returns the updated response as a dictionary that can be serialized later
"""
try:
if 'rubric' in response:
rubric = response['rubric']
rubric_renderer = CombinedOpenEndedRubric(self.render_template, view_only)
rubric_dict = rubric_renderer.render_rubric(rubric)
success = rubric_dict['success']
rubric_html = rubric_dict['html']
response['rubric'] = rubric_html
return response
# if we can't parse the rubric into HTML,
except (etree.XMLSyntaxError, RubricParsingError):
#This is a dev_facing_error
log.exception("Cannot parse rubric string. Raw string: {0}".format(response['rubric']))
return {'success': False,
'error': 'Error displaying submission'}
except ValueError:
#This is a dev_facing_error
log.exception("Error parsing response: {0}".format(response))
return {'success': False,
'error': "Error displaying submission"}
|
tareqalayan/ansible | refs/heads/devel | test/units/modules/network/nxos/test_nxos_bgp.py | 18 | # (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_bgp
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosBgpModule(TestNxosModule):
module = nxos_bgp
def setUp(self):
super(TestNxosBgpModule, self).setUp()
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bgp.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_config = patch('ansible.modules.network.nxos.nxos_bgp.get_config')
self.get_config = self.mock_get_config.start()
def tearDown(self):
super(TestNxosBgpModule, self).tearDown()
self.mock_load_config.stop()
self.mock_get_config.stop()
def load_fixtures(self, commands=None, device=''):
self.get_config.return_value = load_fixture('nxos_bgp', 'config.cfg')
self.load_config.return_value = []
def test_nxos_bgp(self):
set_module_args(dict(asn=65535, router_id='192.0.2.1'))
result = self.execute_module(changed=True)
self.assertEqual(result['commands'], ['router bgp 65535', 'router-id 192.0.2.1'])
def test_nxos_bgp_change_nothing(self):
set_module_args(dict(asn=65535, router_id='192.168.1.1'))
self.execute_module(changed=False)
def test_nxos_bgp_wrong_asn(self):
set_module_args(dict(asn=10, router_id='192.168.1.1'))
result = self.execute_module(failed=True)
self.assertEqual(result['msg'], 'Another BGP ASN already exists.')
def test_nxos_bgp_remove(self):
set_module_args(dict(asn=65535, state='absent'))
self.execute_module(changed=True, commands=['no router bgp 65535'])
def test_nxos_bgp_remove_vrf(self):
set_module_args(dict(asn=65535, vrf='test2', state='absent'))
self.execute_module(changed=True, commands=['router bgp 65535', 'no vrf test2'])
def test_nxos_bgp_remove_nonexistant_vrf(self):
set_module_args(dict(asn=65535, vrf='foo', state='absent'))
self.execute_module(changed=False)
def test_nxos_bgp_remove_wrong_asn(self):
set_module_args(dict(asn=10, state='absent'))
self.execute_module(changed=False)
def test_nxos_bgp_vrf(self):
set_module_args(dict(asn=65535, vrf='test', router_id='192.0.2.1'))
result = self.execute_module(changed=True, commands=['router bgp 65535', 'vrf test', 'router-id 192.0.2.1'])
self.assertEqual(result['warnings'], ["VRF test doesn't exist."])
def test_nxos_bgp_global_param(self):
set_module_args(dict(asn=65535, shutdown=True))
self.execute_module(changed=True, commands=['router bgp 65535', 'shutdown'])
def test_nxos_bgp_global_param_outside_default(self):
set_module_args(dict(asn=65535, vrf='test', shutdown=True))
result = self.execute_module(failed=True)
self.assertEqual(result['msg'], 'Global params can be modified only under "default" VRF.')
def test_nxos_bgp_default_value(self):
set_module_args(dict(asn=65535, graceful_restart_timers_restart='default'))
self.execute_module(
changed=True,
commands=['router bgp 65535', 'graceful-restart restart-time 120']
)
class TestNxosBgp32BitsAS(TestNxosModule):
module = nxos_bgp
def setUp(self):
super(TestNxosBgp32BitsAS, self).setUp()
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bgp.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_config = patch('ansible.modules.network.nxos.nxos_bgp.get_config')
self.get_config = self.mock_get_config.start()
def tearDown(self):
super(TestNxosBgp32BitsAS, self).tearDown()
self.mock_load_config.stop()
self.mock_get_config.stop()
def load_fixtures(self, commands=None, device=''):
self.get_config.return_value = load_fixture('nxos_bgp', 'config_32_bits_as.cfg')
self.load_config.return_value = []
def test_nxos_bgp_change_nothing(self):
set_module_args(dict(asn='65535.65535', router_id='192.168.1.1'))
self.execute_module(changed=False)
def test_nxos_bgp_wrong_asn(self):
set_module_args(dict(asn='65535.10', router_id='192.168.1.1'))
result = self.execute_module(failed=True)
self.assertEqual(result['msg'], 'Another BGP ASN already exists.')
def test_nxos_bgp_remove(self):
set_module_args(dict(asn='65535.65535', state='absent'))
self.execute_module(changed=True, commands=['no router bgp 65535.65535'])
|
xfournet/intellij-community | refs/heads/master | plugins/hg4idea/testData/bin/hgext/bugzilla.py | 93 | # bugzilla.py - bugzilla integration for mercurial
#
# Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
# Copyright 2011-2 Jim Hague <jim.hague@acm.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''hooks for integrating with the Bugzilla bug tracker
This hook extension adds comments on bugs in Bugzilla when changesets
that refer to bugs by Bugzilla ID are seen. The comment is formatted using
the Mercurial template mechanism.
The bug references can optionally include an update for Bugzilla of the
hours spent working on the bug. Bugs can also be marked fixed.
Three basic modes of access to Bugzilla are provided:
1. Access via the Bugzilla XMLRPC interface. Requires Bugzilla 3.4 or later.
2. Check data via the Bugzilla XMLRPC interface and submit bug change
via email to Bugzilla email interface. Requires Bugzilla 3.4 or later.
3. Writing directly to the Bugzilla database. Only Bugzilla installations
using MySQL are supported. Requires Python MySQLdb.
Writing directly to the database is susceptible to schema changes, and
relies on a Bugzilla contrib script to send out bug change
notification emails. This script runs as the user running Mercurial,
must be run on the host with the Bugzilla install, and requires
permission to read Bugzilla configuration details and the necessary
MySQL user and password to have full access rights to the Bugzilla
database. For these reasons this access mode is now considered
deprecated, and will not be updated for new Bugzilla versions going
forward. Only adding comments is supported in this access mode.
Access via XMLRPC needs a Bugzilla username and password to be specified
in the configuration. Comments are added under that username. Since the
configuration must be readable by all Mercurial users, it is recommended
that the rights of that user are restricted in Bugzilla to the minimum
necessary to add comments. Marking bugs fixed requires Bugzilla 4.0 and later.
Access via XMLRPC/email uses XMLRPC to query Bugzilla, but sends
email to the Bugzilla email interface to submit comments to bugs.
The From: address in the email is set to the email address of the Mercurial
user, so the comment appears to come from the Mercurial user. In the event
that the Mercurial user email is not recognized by Bugzilla as a Bugzilla
user, the email associated with the Bugzilla username used to log into
Bugzilla is used instead as the source of the comment. Marking bugs fixed
works on all supported Bugzilla versions.
Configuration items common to all access modes:
bugzilla.version
The access type to use. Values recognized are:
:``xmlrpc``: Bugzilla XMLRPC interface.
:``xmlrpc+email``: Bugzilla XMLRPC and email interfaces.
:``3.0``: MySQL access, Bugzilla 3.0 and later.
:``2.18``: MySQL access, Bugzilla 2.18 and up to but not
including 3.0.
:``2.16``: MySQL access, Bugzilla 2.16 and up to but not
including 2.18.
bugzilla.regexp
Regular expression to match bug IDs for update in changeset commit message.
It must contain one "()" named group ``<ids>`` containing the bug
IDs separated by non-digit characters. It may also contain
a named group ``<hours>`` with a floating-point number giving the
hours worked on the bug. If no named groups are present, the first
"()" group is assumed to contain the bug IDs, and work time is not
updated. The default expression matches ``Bug 1234``, ``Bug no. 1234``,
``Bug number 1234``, ``Bugs 1234,5678``, ``Bug 1234 and 5678`` and
variations thereof, followed by an hours number prefixed by ``h`` or
``hours``, e.g. ``hours 1.5``. Matching is case insensitive.
bugzilla.fixregexp
Regular expression to match bug IDs for marking fixed in changeset
commit message. This must contain a "()" named group ``<ids>` containing
the bug IDs separated by non-digit characters. It may also contain
a named group ``<hours>`` with a floating-point number giving the
hours worked on the bug. If no named groups are present, the first
"()" group is assumed to contain the bug IDs, and work time is not
updated. The default expression matches ``Fixes 1234``, ``Fixes bug 1234``,
``Fixes bugs 1234,5678``, ``Fixes 1234 and 5678`` and
variations thereof, followed by an hours number prefixed by ``h`` or
``hours``, e.g. ``hours 1.5``. Matching is case insensitive.
bugzilla.fixstatus
The status to set a bug to when marking fixed. Default ``RESOLVED``.
bugzilla.fixresolution
The resolution to set a bug to when marking fixed. Default ``FIXED``.
bugzilla.style
The style file to use when formatting comments.
bugzilla.template
Template to use when formatting comments. Overrides style if
specified. In addition to the usual Mercurial keywords, the
extension specifies:
:``{bug}``: The Bugzilla bug ID.
:``{root}``: The full pathname of the Mercurial repository.
:``{webroot}``: Stripped pathname of the Mercurial repository.
:``{hgweb}``: Base URL for browsing Mercurial repositories.
Default ``changeset {node|short} in repo {root} refers to bug
{bug}.\\ndetails:\\n\\t{desc|tabindent}``
bugzilla.strip
The number of path separator characters to strip from the front of
the Mercurial repository path (``{root}`` in templates) to produce
``{webroot}``. For example, a repository with ``{root}``
``/var/local/my-project`` with a strip of 2 gives a value for
``{webroot}`` of ``my-project``. Default 0.
web.baseurl
Base URL for browsing Mercurial repositories. Referenced from
templates as ``{hgweb}``.
Configuration items common to XMLRPC+email and MySQL access modes:
bugzilla.usermap
Path of file containing Mercurial committer email to Bugzilla user email
mappings. If specified, the file should contain one mapping per
line::
committer = Bugzilla user
See also the ``[usermap]`` section.
The ``[usermap]`` section is used to specify mappings of Mercurial
committer email to Bugzilla user email. See also ``bugzilla.usermap``.
Contains entries of the form ``committer = Bugzilla user``.
XMLRPC access mode configuration:
bugzilla.bzurl
The base URL for the Bugzilla installation.
Default ``http://localhost/bugzilla``.
bugzilla.user
The username to use to log into Bugzilla via XMLRPC. Default
``bugs``.
bugzilla.password
The password for Bugzilla login.
XMLRPC+email access mode uses the XMLRPC access mode configuration items,
and also:
bugzilla.bzemail
The Bugzilla email address.
In addition, the Mercurial email settings must be configured. See the
documentation in hgrc(5), sections ``[email]`` and ``[smtp]``.
MySQL access mode configuration:
bugzilla.host
Hostname of the MySQL server holding the Bugzilla database.
Default ``localhost``.
bugzilla.db
Name of the Bugzilla database in MySQL. Default ``bugs``.
bugzilla.user
Username to use to access MySQL server. Default ``bugs``.
bugzilla.password
Password to use to access MySQL server.
bugzilla.timeout
Database connection timeout (seconds). Default 5.
bugzilla.bzuser
Fallback Bugzilla user name to record comments with, if changeset
committer cannot be found as a Bugzilla user.
bugzilla.bzdir
Bugzilla install directory. Used by default notify. Default
``/var/www/html/bugzilla``.
bugzilla.notify
The command to run to get Bugzilla to send bug change notification
emails. Substitutes from a map with 3 keys, ``bzdir``, ``id`` (bug
id) and ``user`` (committer bugzilla email). Default depends on
version; from 2.18 it is "cd %(bzdir)s && perl -T
contrib/sendbugmail.pl %(id)s %(user)s".
Activating the extension::
[extensions]
bugzilla =
[hooks]
# run bugzilla hook on every change pulled or pushed in here
incoming.bugzilla = python:hgext.bugzilla.hook
Example configurations:
XMLRPC example configuration. This uses the Bugzilla at
``http://my-project.org/bugzilla``, logging in as user
``bugmail@my-project.org`` with password ``plugh``. It is used with a
collection of Mercurial repositories in ``/var/local/hg/repos/``,
with a web interface at ``http://my-project.org/hg``. ::
[bugzilla]
bzurl=http://my-project.org/bugzilla
user=bugmail@my-project.org
password=plugh
version=xmlrpc
template=Changeset {node|short} in {root|basename}.
{hgweb}/{webroot}/rev/{node|short}\\n
{desc}\\n
strip=5
[web]
baseurl=http://my-project.org/hg
XMLRPC+email example configuration. This uses the Bugzilla at
``http://my-project.org/bugzilla``, logging in as user
``bugmail@my-project.org`` with password ``plugh``. It is used with a
collection of Mercurial repositories in ``/var/local/hg/repos/``,
with a web interface at ``http://my-project.org/hg``. Bug comments
are sent to the Bugzilla email address
``bugzilla@my-project.org``. ::
[bugzilla]
bzurl=http://my-project.org/bugzilla
user=bugmail@my-project.org
password=plugh
version=xmlrpc
bzemail=bugzilla@my-project.org
template=Changeset {node|short} in {root|basename}.
{hgweb}/{webroot}/rev/{node|short}\\n
{desc}\\n
strip=5
[web]
baseurl=http://my-project.org/hg
[usermap]
user@emaildomain.com=user.name@bugzilladomain.com
MySQL example configuration. This has a local Bugzilla 3.2 installation
in ``/opt/bugzilla-3.2``. The MySQL database is on ``localhost``,
the Bugzilla database name is ``bugs`` and MySQL is
accessed with MySQL username ``bugs`` password ``XYZZY``. It is used
with a collection of Mercurial repositories in ``/var/local/hg/repos/``,
with a web interface at ``http://my-project.org/hg``. ::
[bugzilla]
host=localhost
password=XYZZY
version=3.0
bzuser=unknown@domain.com
bzdir=/opt/bugzilla-3.2
template=Changeset {node|short} in {root|basename}.
{hgweb}/{webroot}/rev/{node|short}\\n
{desc}\\n
strip=5
[web]
baseurl=http://my-project.org/hg
[usermap]
user@emaildomain.com=user.name@bugzilladomain.com
All the above add a comment to the Bugzilla bug record of the form::
Changeset 3b16791d6642 in repository-name.
http://my-project.org/hg/repository-name/rev/3b16791d6642
Changeset commit comment. Bug 1234.
'''
from mercurial.i18n import _
from mercurial.node import short
from mercurial import cmdutil, mail, templater, util
import re, time, urlparse, xmlrpclib
testedwith = 'internal'
class bzaccess(object):
'''Base class for access to Bugzilla.'''
def __init__(self, ui):
self.ui = ui
usermap = self.ui.config('bugzilla', 'usermap')
if usermap:
self.ui.readconfig(usermap, sections=['usermap'])
def map_committer(self, user):
'''map name of committer to Bugzilla user name.'''
for committer, bzuser in self.ui.configitems('usermap'):
if committer.lower() == user.lower():
return bzuser
return user
# Methods to be implemented by access classes.
#
# 'bugs' is a dict keyed on bug id, where values are a dict holding
# updates to bug state. Recognized dict keys are:
#
# 'hours': Value, float containing work hours to be updated.
# 'fix': If key present, bug is to be marked fixed. Value ignored.
def filter_real_bug_ids(self, bugs):
'''remove bug IDs that do not exist in Bugzilla from bugs.'''
pass
def filter_cset_known_bug_ids(self, node, bugs):
'''remove bug IDs where node occurs in comment text from bugs.'''
pass
def updatebug(self, bugid, newstate, text, committer):
'''update the specified bug. Add comment text and set new states.
If possible add the comment as being from the committer of
the changeset. Otherwise use the default Bugzilla user.
'''
pass
def notify(self, bugs, committer):
'''Force sending of Bugzilla notification emails.
Only required if the access method does not trigger notification
emails automatically.
'''
pass
# Bugzilla via direct access to MySQL database.
class bzmysql(bzaccess):
'''Support for direct MySQL access to Bugzilla.
The earliest Bugzilla version this is tested with is version 2.16.
If your Bugzilla is version 3.4 or above, you are strongly
recommended to use the XMLRPC access method instead.
'''
@staticmethod
def sql_buglist(ids):
'''return SQL-friendly list of bug ids'''
return '(' + ','.join(map(str, ids)) + ')'
_MySQLdb = None
def __init__(self, ui):
try:
import MySQLdb as mysql
bzmysql._MySQLdb = mysql
except ImportError, err:
raise util.Abort(_('python mysql support not available: %s') % err)
bzaccess.__init__(self, ui)
host = self.ui.config('bugzilla', 'host', 'localhost')
user = self.ui.config('bugzilla', 'user', 'bugs')
passwd = self.ui.config('bugzilla', 'password')
db = self.ui.config('bugzilla', 'db', 'bugs')
timeout = int(self.ui.config('bugzilla', 'timeout', 5))
self.ui.note(_('connecting to %s:%s as %s, password %s\n') %
(host, db, user, '*' * len(passwd)))
self.conn = bzmysql._MySQLdb.connect(host=host,
user=user, passwd=passwd,
db=db,
connect_timeout=timeout)
self.cursor = self.conn.cursor()
self.longdesc_id = self.get_longdesc_id()
self.user_ids = {}
self.default_notify = "cd %(bzdir)s && ./processmail %(id)s %(user)s"
def run(self, *args, **kwargs):
'''run a query.'''
self.ui.note(_('query: %s %s\n') % (args, kwargs))
try:
self.cursor.execute(*args, **kwargs)
except bzmysql._MySQLdb.MySQLError:
self.ui.note(_('failed query: %s %s\n') % (args, kwargs))
raise
def get_longdesc_id(self):
'''get identity of longdesc field'''
self.run('select fieldid from fielddefs where name = "longdesc"')
ids = self.cursor.fetchall()
if len(ids) != 1:
raise util.Abort(_('unknown database schema'))
return ids[0][0]
def filter_real_bug_ids(self, bugs):
'''filter not-existing bugs from set.'''
self.run('select bug_id from bugs where bug_id in %s' %
bzmysql.sql_buglist(bugs.keys()))
existing = [id for (id,) in self.cursor.fetchall()]
for id in bugs.keys():
if id not in existing:
self.ui.status(_('bug %d does not exist\n') % id)
del bugs[id]
def filter_cset_known_bug_ids(self, node, bugs):
'''filter bug ids that already refer to this changeset from set.'''
self.run('''select bug_id from longdescs where
bug_id in %s and thetext like "%%%s%%"''' %
(bzmysql.sql_buglist(bugs.keys()), short(node)))
for (id,) in self.cursor.fetchall():
self.ui.status(_('bug %d already knows about changeset %s\n') %
(id, short(node)))
del bugs[id]
def notify(self, bugs, committer):
'''tell bugzilla to send mail.'''
self.ui.status(_('telling bugzilla to send mail:\n'))
(user, userid) = self.get_bugzilla_user(committer)
for id in bugs.keys():
self.ui.status(_(' bug %s\n') % id)
cmdfmt = self.ui.config('bugzilla', 'notify', self.default_notify)
bzdir = self.ui.config('bugzilla', 'bzdir',
'/var/www/html/bugzilla')
try:
# Backwards-compatible with old notify string, which
# took one string. This will throw with a new format
# string.
cmd = cmdfmt % id
except TypeError:
cmd = cmdfmt % {'bzdir': bzdir, 'id': id, 'user': user}
self.ui.note(_('running notify command %s\n') % cmd)
fp = util.popen('(%s) 2>&1' % cmd)
out = fp.read()
ret = fp.close()
if ret:
self.ui.warn(out)
raise util.Abort(_('bugzilla notify command %s') %
util.explainexit(ret)[0])
self.ui.status(_('done\n'))
def get_user_id(self, user):
'''look up numeric bugzilla user id.'''
try:
return self.user_ids[user]
except KeyError:
try:
userid = int(user)
except ValueError:
self.ui.note(_('looking up user %s\n') % user)
self.run('''select userid from profiles
where login_name like %s''', user)
all = self.cursor.fetchall()
if len(all) != 1:
raise KeyError(user)
userid = int(all[0][0])
self.user_ids[user] = userid
return userid
def get_bugzilla_user(self, committer):
'''See if committer is a registered bugzilla user. Return
bugzilla username and userid if so. If not, return default
bugzilla username and userid.'''
user = self.map_committer(committer)
try:
userid = self.get_user_id(user)
except KeyError:
try:
defaultuser = self.ui.config('bugzilla', 'bzuser')
if not defaultuser:
raise util.Abort(_('cannot find bugzilla user id for %s') %
user)
userid = self.get_user_id(defaultuser)
user = defaultuser
except KeyError:
raise util.Abort(_('cannot find bugzilla user id for %s or %s')
% (user, defaultuser))
return (user, userid)
def updatebug(self, bugid, newstate, text, committer):
'''update bug state with comment text.
Try adding comment as committer of changeset, otherwise as
default bugzilla user.'''
if len(newstate) > 0:
self.ui.warn(_("Bugzilla/MySQL cannot update bug state\n"))
(user, userid) = self.get_bugzilla_user(committer)
now = time.strftime('%Y-%m-%d %H:%M:%S')
self.run('''insert into longdescs
(bug_id, who, bug_when, thetext)
values (%s, %s, %s, %s)''',
(bugid, userid, now, text))
self.run('''insert into bugs_activity (bug_id, who, bug_when, fieldid)
values (%s, %s, %s, %s)''',
(bugid, userid, now, self.longdesc_id))
self.conn.commit()
class bzmysql_2_18(bzmysql):
'''support for bugzilla 2.18 series.'''
def __init__(self, ui):
bzmysql.__init__(self, ui)
self.default_notify = \
"cd %(bzdir)s && perl -T contrib/sendbugmail.pl %(id)s %(user)s"
class bzmysql_3_0(bzmysql_2_18):
'''support for bugzilla 3.0 series.'''
def __init__(self, ui):
bzmysql_2_18.__init__(self, ui)
def get_longdesc_id(self):
'''get identity of longdesc field'''
self.run('select id from fielddefs where name = "longdesc"')
ids = self.cursor.fetchall()
if len(ids) != 1:
raise util.Abort(_('unknown database schema'))
return ids[0][0]
# Bugzilla via XMLRPC interface.
class cookietransportrequest(object):
"""A Transport request method that retains cookies over its lifetime.
The regular xmlrpclib transports ignore cookies. Which causes
a bit of a problem when you need a cookie-based login, as with
the Bugzilla XMLRPC interface.
So this is a helper for defining a Transport which looks for
cookies being set in responses and saves them to add to all future
requests.
"""
# Inspiration drawn from
# http://blog.godson.in/2010/09/how-to-make-python-xmlrpclib-client.html
# http://www.itkovian.net/base/transport-class-for-pythons-xml-rpc-lib/
cookies = []
def send_cookies(self, connection):
if self.cookies:
for cookie in self.cookies:
connection.putheader("Cookie", cookie)
def request(self, host, handler, request_body, verbose=0):
self.verbose = verbose
self.accept_gzip_encoding = False
# issue XML-RPC request
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_cookies(h)
self.send_user_agent(h)
self.send_content(h, request_body)
# Deal with differences between Python 2.4-2.6 and 2.7.
# In the former h is a HTTP(S). In the latter it's a
# HTTP(S)Connection. Luckily, the 2.4-2.6 implementation of
# HTTP(S) has an underlying HTTP(S)Connection, so extract
# that and use it.
try:
response = h.getresponse()
except AttributeError:
response = h._conn.getresponse()
# Add any cookie definitions to our list.
for header in response.msg.getallmatchingheaders("Set-Cookie"):
val = header.split(": ", 1)[1]
cookie = val.split(";", 1)[0]
self.cookies.append(cookie)
if response.status != 200:
raise xmlrpclib.ProtocolError(host + handler, response.status,
response.reason, response.msg.headers)
payload = response.read()
parser, unmarshaller = self.getparser()
parser.feed(payload)
parser.close()
return unmarshaller.close()
# The explicit calls to the underlying xmlrpclib __init__() methods are
# necessary. The xmlrpclib.Transport classes are old-style classes, and
# it turns out their __init__() doesn't get called when doing multiple
# inheritance with a new-style class.
class cookietransport(cookietransportrequest, xmlrpclib.Transport):
def __init__(self, use_datetime=0):
if util.safehasattr(xmlrpclib.Transport, "__init__"):
xmlrpclib.Transport.__init__(self, use_datetime)
class cookiesafetransport(cookietransportrequest, xmlrpclib.SafeTransport):
def __init__(self, use_datetime=0):
if util.safehasattr(xmlrpclib.Transport, "__init__"):
xmlrpclib.SafeTransport.__init__(self, use_datetime)
class bzxmlrpc(bzaccess):
"""Support for access to Bugzilla via the Bugzilla XMLRPC API.
Requires a minimum Bugzilla version 3.4.
"""
def __init__(self, ui):
bzaccess.__init__(self, ui)
bzweb = self.ui.config('bugzilla', 'bzurl',
'http://localhost/bugzilla/')
bzweb = bzweb.rstrip("/") + "/xmlrpc.cgi"
user = self.ui.config('bugzilla', 'user', 'bugs')
passwd = self.ui.config('bugzilla', 'password')
self.fixstatus = self.ui.config('bugzilla', 'fixstatus', 'RESOLVED')
self.fixresolution = self.ui.config('bugzilla', 'fixresolution',
'FIXED')
self.bzproxy = xmlrpclib.ServerProxy(bzweb, self.transport(bzweb))
ver = self.bzproxy.Bugzilla.version()['version'].split('.')
self.bzvermajor = int(ver[0])
self.bzverminor = int(ver[1])
self.bzproxy.User.login(dict(login=user, password=passwd))
def transport(self, uri):
if urlparse.urlparse(uri, "http")[0] == "https":
return cookiesafetransport()
else:
return cookietransport()
def get_bug_comments(self, id):
"""Return a string with all comment text for a bug."""
c = self.bzproxy.Bug.comments(dict(ids=[id], include_fields=['text']))
return ''.join([t['text'] for t in c['bugs'][str(id)]['comments']])
def filter_real_bug_ids(self, bugs):
probe = self.bzproxy.Bug.get(dict(ids=sorted(bugs.keys()),
include_fields=[],
permissive=True))
for badbug in probe['faults']:
id = badbug['id']
self.ui.status(_('bug %d does not exist\n') % id)
del bugs[id]
def filter_cset_known_bug_ids(self, node, bugs):
for id in sorted(bugs.keys()):
if self.get_bug_comments(id).find(short(node)) != -1:
self.ui.status(_('bug %d already knows about changeset %s\n') %
(id, short(node)))
del bugs[id]
def updatebug(self, bugid, newstate, text, committer):
args = {}
if 'hours' in newstate:
args['work_time'] = newstate['hours']
if self.bzvermajor >= 4:
args['ids'] = [bugid]
args['comment'] = {'body' : text}
if 'fix' in newstate:
args['status'] = self.fixstatus
args['resolution'] = self.fixresolution
self.bzproxy.Bug.update(args)
else:
if 'fix' in newstate:
self.ui.warn(_("Bugzilla/XMLRPC needs Bugzilla 4.0 or later "
"to mark bugs fixed\n"))
args['id'] = bugid
args['comment'] = text
self.bzproxy.Bug.add_comment(args)
class bzxmlrpcemail(bzxmlrpc):
"""Read data from Bugzilla via XMLRPC, send updates via email.
Advantages of sending updates via email:
1. Comments can be added as any user, not just logged in user.
2. Bug statuses or other fields not accessible via XMLRPC can
potentially be updated.
There is no XMLRPC function to change bug status before Bugzilla
4.0, so bugs cannot be marked fixed via XMLRPC before Bugzilla 4.0.
But bugs can be marked fixed via email from 3.4 onwards.
"""
# The email interface changes subtly between 3.4 and 3.6. In 3.4,
# in-email fields are specified as '@<fieldname> = <value>'. In
# 3.6 this becomes '@<fieldname> <value>'. And fieldname @bug_id
# in 3.4 becomes @id in 3.6. 3.6 and 4.0 both maintain backwards
# compatibility, but rather than rely on this use the new format for
# 4.0 onwards.
def __init__(self, ui):
bzxmlrpc.__init__(self, ui)
self.bzemail = self.ui.config('bugzilla', 'bzemail')
if not self.bzemail:
raise util.Abort(_("configuration 'bzemail' missing"))
mail.validateconfig(self.ui)
def makecommandline(self, fieldname, value):
if self.bzvermajor >= 4:
return "@%s %s" % (fieldname, str(value))
else:
if fieldname == "id":
fieldname = "bug_id"
return "@%s = %s" % (fieldname, str(value))
def send_bug_modify_email(self, bugid, commands, comment, committer):
'''send modification message to Bugzilla bug via email.
The message format is documented in the Bugzilla email_in.pl
specification. commands is a list of command lines, comment is the
comment text.
To stop users from crafting commit comments with
Bugzilla commands, specify the bug ID via the message body, rather
than the subject line, and leave a blank line after it.
'''
user = self.map_committer(committer)
matches = self.bzproxy.User.get(dict(match=[user]))
if not matches['users']:
user = self.ui.config('bugzilla', 'user', 'bugs')
matches = self.bzproxy.User.get(dict(match=[user]))
if not matches['users']:
raise util.Abort(_("default bugzilla user %s email not found") %
user)
user = matches['users'][0]['email']
commands.append(self.makecommandline("id", bugid))
text = "\n".join(commands) + "\n\n" + comment
_charsets = mail._charsets(self.ui)
user = mail.addressencode(self.ui, user, _charsets)
bzemail = mail.addressencode(self.ui, self.bzemail, _charsets)
msg = mail.mimeencode(self.ui, text, _charsets)
msg['From'] = user
msg['To'] = bzemail
msg['Subject'] = mail.headencode(self.ui, "Bug modification", _charsets)
sendmail = mail.connect(self.ui)
sendmail(user, bzemail, msg.as_string())
def updatebug(self, bugid, newstate, text, committer):
cmds = []
if 'hours' in newstate:
cmds.append(self.makecommandline("work_time", newstate['hours']))
if 'fix' in newstate:
cmds.append(self.makecommandline("bug_status", self.fixstatus))
cmds.append(self.makecommandline("resolution", self.fixresolution))
self.send_bug_modify_email(bugid, cmds, text, committer)
class bugzilla(object):
# supported versions of bugzilla. different versions have
# different schemas.
_versions = {
'2.16': bzmysql,
'2.18': bzmysql_2_18,
'3.0': bzmysql_3_0,
'xmlrpc': bzxmlrpc,
'xmlrpc+email': bzxmlrpcemail
}
_default_bug_re = (r'bugs?\s*,?\s*(?:#|nos?\.?|num(?:ber)?s?)?\s*'
r'(?P<ids>(?:\d+\s*(?:,?\s*(?:and)?)?\s*)+)'
r'\.?\s*(?:h(?:ours?)?\s*(?P<hours>\d*(?:\.\d+)?))?')
_default_fix_re = (r'fix(?:es)?\s*(?:bugs?\s*)?,?\s*'
r'(?:nos?\.?|num(?:ber)?s?)?\s*'
r'(?P<ids>(?:#?\d+\s*(?:,?\s*(?:and)?)?\s*)+)'
r'\.?\s*(?:h(?:ours?)?\s*(?P<hours>\d*(?:\.\d+)?))?')
_bz = None
def __init__(self, ui, repo):
self.ui = ui
self.repo = repo
def bz(self):
'''return object that knows how to talk to bugzilla version in
use.'''
if bugzilla._bz is None:
bzversion = self.ui.config('bugzilla', 'version')
try:
bzclass = bugzilla._versions[bzversion]
except KeyError:
raise util.Abort(_('bugzilla version %s not supported') %
bzversion)
bugzilla._bz = bzclass(self.ui)
return bugzilla._bz
def __getattr__(self, key):
return getattr(self.bz(), key)
_bug_re = None
_fix_re = None
_split_re = None
def find_bugs(self, ctx):
'''return bugs dictionary created from commit comment.
Extract bug info from changeset comments. Filter out any that are
not known to Bugzilla, and any that already have a reference to
the given changeset in their comments.
'''
if bugzilla._bug_re is None:
bugzilla._bug_re = re.compile(
self.ui.config('bugzilla', 'regexp',
bugzilla._default_bug_re), re.IGNORECASE)
bugzilla._fix_re = re.compile(
self.ui.config('bugzilla', 'fixregexp',
bugzilla._default_fix_re), re.IGNORECASE)
bugzilla._split_re = re.compile(r'\D+')
start = 0
hours = 0.0
bugs = {}
bugmatch = bugzilla._bug_re.search(ctx.description(), start)
fixmatch = bugzilla._fix_re.search(ctx.description(), start)
while True:
bugattribs = {}
if not bugmatch and not fixmatch:
break
if not bugmatch:
m = fixmatch
elif not fixmatch:
m = bugmatch
else:
if bugmatch.start() < fixmatch.start():
m = bugmatch
else:
m = fixmatch
start = m.end()
if m is bugmatch:
bugmatch = bugzilla._bug_re.search(ctx.description(), start)
if 'fix' in bugattribs:
del bugattribs['fix']
else:
fixmatch = bugzilla._fix_re.search(ctx.description(), start)
bugattribs['fix'] = None
try:
ids = m.group('ids')
except IndexError:
ids = m.group(1)
try:
hours = float(m.group('hours'))
bugattribs['hours'] = hours
except IndexError:
pass
except TypeError:
pass
except ValueError:
self.ui.status(_("%s: invalid hours\n") % m.group('hours'))
for id in bugzilla._split_re.split(ids):
if not id:
continue
bugs[int(id)] = bugattribs
if bugs:
self.filter_real_bug_ids(bugs)
if bugs:
self.filter_cset_known_bug_ids(ctx.node(), bugs)
return bugs
def update(self, bugid, newstate, ctx):
'''update bugzilla bug with reference to changeset.'''
def webroot(root):
'''strip leading prefix of repo root and turn into
url-safe path.'''
count = int(self.ui.config('bugzilla', 'strip', 0))
root = util.pconvert(root)
while count > 0:
c = root.find('/')
if c == -1:
break
root = root[c + 1:]
count -= 1
return root
mapfile = self.ui.config('bugzilla', 'style')
tmpl = self.ui.config('bugzilla', 'template')
t = cmdutil.changeset_templater(self.ui, self.repo,
False, None, mapfile, False)
if not mapfile and not tmpl:
tmpl = _('changeset {node|short} in repo {root} refers '
'to bug {bug}.\ndetails:\n\t{desc|tabindent}')
if tmpl:
tmpl = templater.parsestring(tmpl, quoted=False)
t.use_template(tmpl)
self.ui.pushbuffer()
t.show(ctx, changes=ctx.changeset(),
bug=str(bugid),
hgweb=self.ui.config('web', 'baseurl'),
root=self.repo.root,
webroot=webroot(self.repo.root))
data = self.ui.popbuffer()
self.updatebug(bugid, newstate, data, util.email(ctx.user()))
def hook(ui, repo, hooktype, node=None, **kwargs):
'''add comment to bugzilla for each changeset that refers to a
bugzilla bug id. only add a comment once per bug, so same change
seen multiple times does not fill bug with duplicate data.'''
if node is None:
raise util.Abort(_('hook type %s does not pass a changeset id') %
hooktype)
try:
bz = bugzilla(ui, repo)
ctx = repo[node]
bugs = bz.find_bugs(ctx)
if bugs:
for bug in bugs:
bz.update(bug, bugs[bug], ctx)
bz.notify(bugs, util.email(ctx.user()))
except Exception, e:
raise util.Abort(_('Bugzilla error: %s') % e)
|
selste/micropython | refs/heads/master | tests/basics/class_use_other.py | 106 | # check that we can use an instance of B in a method of A
class A:
def store(a, b):
a.value = b
class B:
pass
b = B()
A.store(b, 1)
print(b.value)
|
Wuguanping/Server_Manage_Plugin | refs/heads/master | Openstack_Plugin/ironic-plugin-pike/ironic/tests/unit/api/base.py | 4 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
"""Base classes for API tests."""
# NOTE: Ported from ceilometer/tests/api.py (subsequently moved to
# ceilometer/tests/api/__init__.py). This should be oslo'ified:
# https://bugs.launchpad.net/ironic/+bug/1255115.
import mock
from oslo_config import cfg
import pecan
import pecan.testing
from six.moves.urllib import parse as urlparse
from ironic.tests.unit.db import base as db_base
PATH_PREFIX = '/v1'
cfg.CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token')
class BaseApiTest(db_base.DbTestCase):
"""Pecan controller functional testing class.
Used for functional tests of Pecan controllers where you need to
test your literal application and its integration with the
framework.
"""
SOURCE_DATA = {'test_source': {'somekey': '666'}}
def setUp(self):
super(BaseApiTest, self).setUp()
cfg.CONF.set_override("auth_version", "v3",
group='keystone_authtoken')
cfg.CONF.set_override("admin_user", "admin",
group='keystone_authtoken')
cfg.CONF.set_override("auth_strategy", "noauth")
self.app = self._make_app()
def reset_pecan():
pecan.set_config({}, overwrite=True)
self.addCleanup(reset_pecan)
p = mock.patch('ironic.api.controllers.v1.Controller._check_version')
self._check_version = p.start()
self.addCleanup(p.stop)
def _make_app(self):
# Determine where we are so we can set up paths in the config
root_dir = self.path_get()
self.app_config = {
'app': {
'root': 'ironic.api.controllers.root.RootController',
'modules': ['ironic.api'],
'static_root': '%s/public' % root_dir,
'debug': True,
'template_path': '%s/api/templates' % root_dir,
'acl_public_routes': ['/', '/v1'],
},
}
return pecan.testing.load_test_app(self.app_config)
def _request_json(self, path, params, expect_errors=False, headers=None,
method="post", extra_environ=None, status=None,
path_prefix=PATH_PREFIX):
"""Sends simulated HTTP request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param method: Request method type. Appropriate method function call
should be used rather than passing attribute in.
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
:param path_prefix: prefix of the url path
"""
full_path = path_prefix + path
print('%s: %s %s' % (method.upper(), full_path, params))
response = getattr(self.app, "%s_json" % method)(
str(full_path),
params=params,
headers=headers,
status=status,
extra_environ=extra_environ,
expect_errors=expect_errors
)
print('GOT:%s' % response)
return response
def put_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Sends simulated HTTP PUT request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="put")
def post_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Sends simulated HTTP POST request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="post")
def patch_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Sends simulated HTTP PATCH request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="patch")
def delete(self, path, expect_errors=False, headers=None,
extra_environ=None, status=None, path_prefix=PATH_PREFIX):
"""Sends simulated HTTP DELETE request to Pecan test app.
:param path: url path of target service
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
:param path_prefix: prefix of the url path
"""
full_path = path_prefix + path
print('DELETE: %s' % (full_path))
response = self.app.delete(str(full_path),
headers=headers,
status=status,
extra_environ=extra_environ,
expect_errors=expect_errors)
print('GOT:%s' % response)
return response
def get_json(self, path, expect_errors=False, headers=None,
extra_environ=None, q=None, path_prefix=PATH_PREFIX,
**params):
"""Sends simulated HTTP GET request to Pecan test app.
:param path: url path of target service
:param expect_errors: Boolean value;whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param q: list of queries consisting of: field, value, op, and type
keys
:param path_prefix: prefix of the url path
:param params: content for wsgi.input of request
"""
q = q if q is not None else []
full_path = path_prefix + path
query_params = {'q.field': [],
'q.value': [],
'q.op': [],
}
for query in q:
for name in ['field', 'op', 'value']:
query_params['q.%s' % name].append(query.get(name, ''))
all_params = {}
all_params.update(params)
if q:
all_params.update(query_params)
print('GET: %s %r' % (full_path, all_params))
response = self.app.get(full_path,
params=all_params,
headers=headers,
extra_environ=extra_environ,
expect_errors=expect_errors)
if not expect_errors:
response = response.json
print('GOT:%s' % response)
return response
def validate_link(self, link, bookmark=False, headers=None):
"""Checks if the given link can get correct data."""
# removes the scheme and net location parts of the link
url_parts = list(urlparse.urlparse(link))
url_parts[0] = url_parts[1] = ''
# bookmark link should not have the version in the URL
if bookmark and url_parts[2].startswith(PATH_PREFIX):
return False
full_path = urlparse.urlunparse(url_parts)
try:
self.get_json(full_path, path_prefix='', headers=headers)
return True
except Exception:
return False
|
mattrobenolt/django | refs/heads/master | django/utils/itercompat.py | 712 | """
Providing iterator functions that are not in all version of Python we support.
Where possible, we try to use the system-native version and only fall back to
these implementations if necessary.
"""
def is_iterable(x):
"A implementation independent way of checking for iterables"
try:
iter(x)
except TypeError:
return False
else:
return True
|
blaze33/django | refs/heads/ticket_19456 | tests/regressiontests/syndication/urls.py | 47 | from __future__ import absolute_import
from django.conf.urls import patterns
from . import feeds
urlpatterns = patterns('django.contrib.syndication.views',
(r'^syndication/complex/(?P<foo>.*)/$', feeds.ComplexFeed()),
(r'^syndication/rss2/$', feeds.TestRss2Feed()),
(r'^syndication/rss091/$', feeds.TestRss091Feed()),
(r'^syndication/no_pubdate/$', feeds.TestNoPubdateFeed()),
(r'^syndication/atom/$', feeds.TestAtomFeed()),
(r'^syndication/custom/$', feeds.TestCustomFeed()),
(r'^syndication/naive-dates/$', feeds.NaiveDatesFeed()),
(r'^syndication/aware-dates/$', feeds.TZAwareDatesFeed()),
(r'^syndication/feedurl/$', feeds.TestFeedUrlFeed()),
(r'^syndication/articles/$', feeds.ArticlesFeed()),
(r'^syndication/template/$', feeds.TemplateFeed()),
)
|
jperon/musite | refs/heads/master | static/js/brython/Lib/long_int1/__init__.py | 503 | from browser import html, document, window
import javascript
#memorize/cache?
def _get_value(other):
if isinstance(other, LongInt):
return other.value
return other
class BigInt:
def __init__(self):
pass
def __abs__(self):
return LongInt(self.value.abs())
def __add__(self, other):
return LongInt(self.value.plus(_get_value(other)))
def __and__(self, other):
pass
def __divmod__(self, other):
_value=_get_value(other)
return LongInt(self.value.div(_value)), LongInt(self.value.mod(_value))
def __div__(self, other):
return LongInt(self.value.div(_get_value(other)))
def __eq__(self, other):
return bool(self.value.eq(_get_value(other)))
def __floordiv__(self, other):
return LongInt(self.value.div(_get_value(other)).floor())
def __ge__(self, other):
return bool(self.value.gte(_get_value(other)))
def __gt__(self, other):
return bool(self.value.gt(_get_value(other)))
def __index__(self):
if self.value.isInt():
return int(self.value.toNumber())
raise TypeError("This is not an integer")
def __le__(self, other):
return bool(self.value.lte(_get_value(other)))
def __lt__(self, other):
return bool(self.value.lt(_get_value(other)))
def __lshift__(self, shift):
if isinstance(shift, int):
_v=LongInt(2)**shift
return LongInt(self.value.times(_v.value))
def __mod__(self, other):
return LongInt(self.value.mod(_get_value(other)))
def __mul__(self, other):
return LongInt(self.value.times(_get_value(other)))
def __neg__(self, other):
return LongInt(self.value.neg(_get_value(other)))
def __or__(self, other):
pass
def __pow__(self, other):
return LongInt(self.value.pow(_get_value(other)))
def __rshift__(self, other):
pass
def __sub__(self, other):
return LongInt(self.value.minus(_get_value(other)))
def __repr__(self):
return "%s(%s)" % (self.__name__, self.value.toString(10))
def __str__(self):
return "%s(%s)" % (self.__name__, self.value.toString(10))
def __xor__(self, other):
pass
_precision=20
def get_precision(value):
if isinstance(value, LongInt):
return len(str(value.value.toString(10)))
return len(str(value))
class DecimalJS(BigInt):
def __init__(self, value=0, base=10):
global _precision
_prec=get_precision(value)
if _prec > _precision:
_precision=_prec
window.eval('Decimal.precision=%s' % _precision)
self.value=javascript.JSConstructor(window.Decimal)(value, base)
class BigNumberJS(BigInt):
def __init__(self, value=0, base=10):
self.value=javascript.JSConstructor(window.BigNumber)(value, base)
class BigJS(BigInt):
def __init__(self, value=0, base=10):
self.value=javascript.JSConstructor(window.Big)(value, base)
def __floordiv__(self, other):
_v=LongInt(self.value.div(_get_value(other)))
if _v >= 0:
return LongInt(_v.value.round(0, 0)) #round down
return LongInt(_v.value.round(0, 3)) #round up
def __pow__(self, other):
if isinstance(other, LongInt):
_value=int(other.value.toString(10))
elif isinstance(other, str):
_value=int(other)
return LongInt(self.value.pow(_value))
#_path = __file__[:__file__.rfind('/')]+'/'
_path = __BRYTHON__.brython_path + 'Lib/long_int1/'
#to use decimal.js library uncomment these 2 lines
#javascript.load(_path+'decimal.min.js', ['Decimal'])
#LongInt=DecimalJS
#to use bignumber.js library uncomment these 2 lines
javascript.load(_path+'bignumber.min.js', ['BigNumber'])
LongInt=BigNumberJS
#big.js does not have a "base" so only base 10 stuff works.
#to use big.js library uncomment these 2 lines
#javascript.load(_path+'big.min.js', ['Big'])
#LongInt=BigJS
|
t-mertz/slurmCompanion | refs/heads/master | django-web/sshcomm/tests.py | 1 | from django.test import TestCase
from .models import RemoteServer
from .security import create_key, create_string_key, encode_key, decode_key, crop_key, encrypt_Crypto, decrypt_Crypto
import datetime
# Create your tests here.
class RemoteServerTests(TestCase):
"""Tests for RemoteServer model"""
def test_get_installed_servers_empty(self):
self.assertEqual(RemoteServer.get_installed_servers(), [])
def test_get_installed_servers_one(self):
new_server = RemoteServer(server_url="", server_name="abc", date_added=datetime.date(2016,1,1))
new_server.save()
self.assertEqual(RemoteServer.get_installed_servers(), [("abc", "abc")])
def test_get_installed_servers_two(self):
new_server = RemoteServer(server_url="", server_name="abc", date_added=datetime.date(2016,1,1))
new_server.save()
new_server = RemoteServer(server_url="", server_name="def", date_added=datetime.date(2016,1,1))
new_server.save()
self.assertEqual(RemoteServer.get_installed_servers(), [("abc", "abc"), ("def", "def")])
class TestKeyCreation(TestCase):
def test_create_key_nonzero(self):
self.assertTrue(len(create_key('uname', 'pw')) > 0)
def test_create_key_differs_with_similar_input(self):
self.assertNotEqual(create_key('uname', 'pw'), create_key('uname1', 'pw'))
def test_create_string_key_nonzero(self):
self.assertTrue(len(create_string_key('uname', 'pw')) > 0)
def test_create_string_key_differs_with_similar_input(self):
self.assertNotEqual(create_string_key('uname', 'pw'), create_string_key('uname1', 'pw'))
class TestKeyConversion(TestCase):
def test_encode_key_letter_a(self):
import json
key = json.dumps([97])
self.assertEqual(encode_key(b'a'), key)
def test_encode_key_letter_short_string(self):
import json
key = json.dumps([73, 32, 107, 110, 111, 119, 32, 116, 104, 105, 115, 32, 116, 101, 120, 116])
self.assertEqual(encode_key(b'I know this text'), key)
def test_decode_key_letter_a(self):
import json
key = json.dumps([97])
self.assertEqual(decode_key(key), b'a')
def test_decode_key_letter_short_string(self):
import json
key = json.dumps([73, 32, 107, 110, 111, 119, 32, 116, 104, 105, 115, 32, 116, 101, 120, 116])
self.assertEqual(decode_key(key), b'I know this text')
def test_encode_decode(self):
test_bytes = b"This is a test sentence designed to test the conversion from string -> bytes. It can contain any ASCII character: $%&#/[]{}^()_=''"
self.assertEqual(decode_key(encode_key(test_bytes)), test_bytes)
class TestEnDecryption(TestCase):
def test_crop_key_empty_raises_valueerror(self):
self.assertRaises(ValueError, crop_key, b'', 16)
def test_crop_key_too_short_odd(self):
self.assertEqual(len(crop_key(b'key', 16)), 16)
def test_crop_key_too_short_even(self):
self.assertEqual(len(crop_key(b'key1', 16)), 16)
def test_crop_key_too_long_odd(self):
self.assertEqual(len(crop_key(b'key', 2)), 2)
def test_crop_key_too_long_even(self):
self.assertEqual(len(crop_key(b'key1', 2)), 2)
def test_crop_key_exact(self):
key = b'Sixteen byte key'
self.assertEqual(crop_key(key, 16), key)
def test_encrypt_decrypt(self):
key = b'Sixteen byte key'
test_text = "this is my test text"
crypt_text = encode_key(encrypt_Crypto(test_text, key))
plain_text = decrypt_Crypto(crypt_text, key).decode('utf-8')
self.assertEqual(test_text, plain_text) |
imruahmed/microblog | refs/heads/master | flask/lib/python2.7/site-packages/sqlalchemy/engine/default.py | 55 | # engine/default.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Default implementations of per-dialect sqlalchemy.engine classes.
These are semi-private implementation classes which are only of importance
to database dialect authors; dialects will usually use the classes here
as the base class for their own corresponding classes.
"""
import re
import random
from . import reflection, interfaces, result
from ..sql import compiler, expression
from .. import types as sqltypes
from .. import exc, util, pool, processors
import codecs
import weakref
from .. import event
AUTOCOMMIT_REGEXP = re.compile(
r'\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER)',
re.I | re.UNICODE)
class DefaultDialect(interfaces.Dialect):
"""Default implementation of Dialect"""
statement_compiler = compiler.SQLCompiler
ddl_compiler = compiler.DDLCompiler
type_compiler = compiler.GenericTypeCompiler
preparer = compiler.IdentifierPreparer
supports_alter = True
# the first value we'd get for an autoincrement
# column.
default_sequence_base = 1
# most DBAPIs happy with this for execute().
# not cx_oracle.
execute_sequence_format = tuple
supports_views = True
supports_sequences = False
sequences_optional = False
preexecute_autoincrement_sequences = False
postfetch_lastrowid = True
implicit_returning = False
supports_right_nested_joins = True
supports_native_enum = False
supports_native_boolean = False
supports_simple_order_by_label = True
engine_config_types = util.immutabledict([
('convert_unicode', util.bool_or_str('force')),
('pool_timeout', util.asint),
('echo', util.bool_or_str('debug')),
('echo_pool', util.bool_or_str('debug')),
('pool_recycle', util.asint),
('pool_size', util.asint),
('max_overflow', util.asint),
('pool_threadlocal', util.asbool),
])
# if the NUMERIC type
# returns decimal.Decimal.
# *not* the FLOAT type however.
supports_native_decimal = False
if util.py3k:
supports_unicode_statements = True
supports_unicode_binds = True
returns_unicode_strings = True
description_encoding = None
else:
supports_unicode_statements = False
supports_unicode_binds = False
returns_unicode_strings = False
description_encoding = 'use_encoding'
name = 'default'
# length at which to truncate
# any identifier.
max_identifier_length = 9999
# length at which to truncate
# the name of an index.
# Usually None to indicate
# 'use max_identifier_length'.
# thanks to MySQL, sigh
max_index_name_length = None
supports_sane_rowcount = True
supports_sane_multi_rowcount = True
dbapi_type_map = {}
colspecs = {}
default_paramstyle = 'named'
supports_default_values = False
supports_empty_insert = True
supports_multivalues_insert = False
server_version_info = None
construct_arguments = None
"""Optional set of argument specifiers for various SQLAlchemy
constructs, typically schema items.
To implement, establish as a series of tuples, as in::
construct_arguments = [
(schema.Index, {
"using": False,
"where": None,
"ops": None
})
]
If the above construct is established on the Postgresql dialect,
the :class:`.Index` construct will now accept the keyword arguments
``postgresql_using``, ``postgresql_where``, nad ``postgresql_ops``.
Any other argument specified to the constructor of :class:`.Index`
which is prefixed with ``postgresql_`` will raise :class:`.ArgumentError`.
A dialect which does not include a ``construct_arguments`` member will
not participate in the argument validation system. For such a dialect,
any argument name is accepted by all participating constructs, within
the namespace of arguments prefixed with that dialect name. The rationale
here is so that third-party dialects that haven't yet implemented this
feature continue to function in the old way.
.. versionadded:: 0.9.2
.. seealso::
:class:`.DialectKWArgs` - implementing base class which consumes
:attr:`.DefaultDialect.construct_arguments`
"""
# indicates symbol names are
# UPPERCASEd if they are case insensitive
# within the database.
# if this is True, the methods normalize_name()
# and denormalize_name() must be provided.
requires_name_normalize = False
reflection_options = ()
dbapi_exception_translation_map = util.immutabledict()
"""mapping used in the extremely unusual case that a DBAPI's
published exceptions don't actually have the __name__ that they
are linked towards.
.. versionadded:: 1.0.5
"""
def __init__(self, convert_unicode=False,
encoding='utf-8', paramstyle=None, dbapi=None,
implicit_returning=None,
supports_right_nested_joins=None,
case_sensitive=True,
supports_native_boolean=None,
label_length=None, **kwargs):
if not getattr(self, 'ported_sqla_06', True):
util.warn(
"The %s dialect is not yet ported to the 0.6 format" %
self.name)
self.convert_unicode = convert_unicode
self.encoding = encoding
self.positional = False
self._ischema = None
self.dbapi = dbapi
if paramstyle is not None:
self.paramstyle = paramstyle
elif self.dbapi is not None:
self.paramstyle = self.dbapi.paramstyle
else:
self.paramstyle = self.default_paramstyle
if implicit_returning is not None:
self.implicit_returning = implicit_returning
self.positional = self.paramstyle in ('qmark', 'format', 'numeric')
self.identifier_preparer = self.preparer(self)
self.type_compiler = self.type_compiler(self)
if supports_right_nested_joins is not None:
self.supports_right_nested_joins = supports_right_nested_joins
if supports_native_boolean is not None:
self.supports_native_boolean = supports_native_boolean
self.case_sensitive = case_sensitive
if label_length and label_length > self.max_identifier_length:
raise exc.ArgumentError(
"Label length of %d is greater than this dialect's"
" maximum identifier length of %d" %
(label_length, self.max_identifier_length))
self.label_length = label_length
if self.description_encoding == 'use_encoding':
self._description_decoder = \
processors.to_unicode_processor_factory(
encoding
)
elif self.description_encoding is not None:
self._description_decoder = \
processors.to_unicode_processor_factory(
self.description_encoding
)
self._encoder = codecs.getencoder(self.encoding)
self._decoder = processors.to_unicode_processor_factory(self.encoding)
@util.memoized_property
def _type_memos(self):
return weakref.WeakKeyDictionary()
@property
def dialect_description(self):
return self.name + "+" + self.driver
@classmethod
def get_pool_class(cls, url):
return getattr(cls, 'poolclass', pool.QueuePool)
def initialize(self, connection):
try:
self.server_version_info = \
self._get_server_version_info(connection)
except NotImplementedError:
self.server_version_info = None
try:
self.default_schema_name = \
self._get_default_schema_name(connection)
except NotImplementedError:
self.default_schema_name = None
try:
self.default_isolation_level = \
self.get_isolation_level(connection.connection)
except NotImplementedError:
self.default_isolation_level = None
self.returns_unicode_strings = self._check_unicode_returns(connection)
if self.description_encoding is not None and \
self._check_unicode_description(connection):
self._description_decoder = self.description_encoding = None
self.do_rollback(connection.connection)
def on_connect(self):
"""return a callable which sets up a newly created DBAPI connection.
This is used to set dialect-wide per-connection options such as
isolation modes, unicode modes, etc.
If a callable is returned, it will be assembled into a pool listener
that receives the direct DBAPI connection, with all wrappers removed.
If None is returned, no listener will be generated.
"""
return None
def _check_unicode_returns(self, connection, additional_tests=None):
if util.py2k and not self.supports_unicode_statements:
cast_to = util.binary_type
else:
cast_to = util.text_type
if self.positional:
parameters = self.execute_sequence_format()
else:
parameters = {}
def check_unicode(test):
statement = cast_to(
expression.select([test]).compile(dialect=self))
try:
cursor = connection.connection.cursor()
connection._cursor_execute(cursor, statement, parameters)
row = cursor.fetchone()
cursor.close()
except exc.DBAPIError as de:
# note that _cursor_execute() will have closed the cursor
# if an exception is thrown.
util.warn("Exception attempting to "
"detect unicode returns: %r" % de)
return False
else:
return isinstance(row[0], util.text_type)
tests = [
# detect plain VARCHAR
expression.cast(
expression.literal_column("'test plain returns'"),
sqltypes.VARCHAR(60)
),
# detect if there's an NVARCHAR type with different behavior
# available
expression.cast(
expression.literal_column("'test unicode returns'"),
sqltypes.Unicode(60)
),
]
if additional_tests:
tests += additional_tests
results = set([check_unicode(test) for test in tests])
if results.issuperset([True, False]):
return "conditional"
else:
return results == set([True])
def _check_unicode_description(self, connection):
# all DBAPIs on Py2K return cursor.description as encoded,
# until pypy2.1beta2 with sqlite, so let's just check it -
# it's likely others will start doing this too in Py2k.
if util.py2k and not self.supports_unicode_statements:
cast_to = util.binary_type
else:
cast_to = util.text_type
cursor = connection.connection.cursor()
try:
cursor.execute(
cast_to(
expression.select([
expression.literal_column("'x'").label("some_label")
]).compile(dialect=self)
)
)
return isinstance(cursor.description[0][0], util.text_type)
finally:
cursor.close()
def type_descriptor(self, typeobj):
"""Provide a database-specific :class:`.TypeEngine` object, given
the generic object which comes from the types module.
This method looks for a dictionary called
``colspecs`` as a class or instance-level variable,
and passes on to :func:`.types.adapt_type`.
"""
return sqltypes.adapt_type(typeobj, self.colspecs)
def reflecttable(
self, connection, table, include_columns, exclude_columns):
insp = reflection.Inspector.from_engine(connection)
return insp.reflecttable(table, include_columns, exclude_columns)
def get_pk_constraint(self, conn, table_name, schema=None, **kw):
"""Compatibility method, adapts the result of get_primary_keys()
for those dialects which don't implement get_pk_constraint().
"""
return {
'constrained_columns':
self.get_primary_keys(conn, table_name,
schema=schema, **kw)
}
def validate_identifier(self, ident):
if len(ident) > self.max_identifier_length:
raise exc.IdentifierError(
"Identifier '%s' exceeds maximum length of %d characters" %
(ident, self.max_identifier_length)
)
def connect(self, *cargs, **cparams):
return self.dbapi.connect(*cargs, **cparams)
def create_connect_args(self, url):
opts = url.translate_connect_args()
opts.update(url.query)
return [[], opts]
def set_engine_execution_options(self, engine, opts):
if 'isolation_level' in opts:
isolation_level = opts['isolation_level']
@event.listens_for(engine, "engine_connect")
def set_isolation(connection, branch):
if not branch:
self._set_connection_isolation(connection, isolation_level)
def set_connection_execution_options(self, connection, opts):
if 'isolation_level' in opts:
self._set_connection_isolation(connection, opts['isolation_level'])
def _set_connection_isolation(self, connection, level):
if connection.in_transaction():
util.warn(
"Connection is already established with a Transaction; "
"setting isolation_level may implicitly rollback or commit "
"the existing transaction, or have no effect until "
"next transaction")
self.set_isolation_level(connection.connection, level)
connection.connection._connection_record.\
finalize_callback.append(self.reset_isolation_level)
def do_begin(self, dbapi_connection):
pass
def do_rollback(self, dbapi_connection):
dbapi_connection.rollback()
def do_commit(self, dbapi_connection):
dbapi_connection.commit()
def do_close(self, dbapi_connection):
dbapi_connection.close()
def create_xid(self):
"""Create a random two-phase transaction ID.
This id will be passed to do_begin_twophase(), do_rollback_twophase(),
do_commit_twophase(). Its format is unspecified.
"""
return "_sa_%032x" % random.randint(0, 2 ** 128)
def do_savepoint(self, connection, name):
connection.execute(expression.SavepointClause(name))
def do_rollback_to_savepoint(self, connection, name):
connection.execute(expression.RollbackToSavepointClause(name))
def do_release_savepoint(self, connection, name):
connection.execute(expression.ReleaseSavepointClause(name))
def do_executemany(self, cursor, statement, parameters, context=None):
cursor.executemany(statement, parameters)
def do_execute(self, cursor, statement, parameters, context=None):
cursor.execute(statement, parameters)
def do_execute_no_params(self, cursor, statement, context=None):
cursor.execute(statement)
def is_disconnect(self, e, connection, cursor):
return False
def reset_isolation_level(self, dbapi_conn):
# default_isolation_level is read from the first connection
# after the initial set of 'isolation_level', if any, so is
# the configured default of this dialect.
self.set_isolation_level(dbapi_conn, self.default_isolation_level)
class DefaultExecutionContext(interfaces.ExecutionContext):
isinsert = False
isupdate = False
isdelete = False
is_crud = False
isddl = False
executemany = False
compiled = None
statement = None
result_column_struct = None
_is_implicit_returning = False
_is_explicit_returning = False
# a hook for SQLite's translation of
# result column names
_translate_colname = None
@classmethod
def _init_ddl(cls, dialect, connection, dbapi_connection, compiled_ddl):
"""Initialize execution context for a DDLElement construct."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
self.compiled = compiled = compiled_ddl
self.isddl = True
self.execution_options = compiled.statement._execution_options
if connection._execution_options:
self.execution_options = dict(self.execution_options)
self.execution_options.update(connection._execution_options)
if not dialect.supports_unicode_statements:
self.unicode_statement = util.text_type(compiled)
self.statement = dialect._encoder(self.unicode_statement)[0]
else:
self.statement = self.unicode_statement = util.text_type(compiled)
self.cursor = self.create_cursor()
self.compiled_parameters = []
if dialect.positional:
self.parameters = [dialect.execute_sequence_format()]
else:
self.parameters = [{}]
return self
@classmethod
def _init_compiled(cls, dialect, connection, dbapi_connection,
compiled, parameters):
"""Initialize execution context for a Compiled construct."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
self.compiled = compiled
if not compiled.can_execute:
raise exc.ArgumentError("Not an executable clause")
self.execution_options = compiled.statement._execution_options.union(
connection._execution_options)
self.result_column_struct = (
compiled._result_columns, compiled._ordered_columns)
self.unicode_statement = util.text_type(compiled)
if not dialect.supports_unicode_statements:
self.statement = self.unicode_statement.encode(
self.dialect.encoding)
else:
self.statement = self.unicode_statement
self.isinsert = compiled.isinsert
self.isupdate = compiled.isupdate
self.isdelete = compiled.isdelete
if not parameters:
self.compiled_parameters = [compiled.construct_params()]
else:
self.compiled_parameters = \
[compiled.construct_params(m, _group_number=grp) for
grp, m in enumerate(parameters)]
self.executemany = len(parameters) > 1
self.cursor = self.create_cursor()
if self.isinsert or self.isupdate or self.isdelete:
self.is_crud = True
self._is_explicit_returning = bool(compiled.statement._returning)
self._is_implicit_returning = bool(
compiled.returning and not compiled.statement._returning)
if not self.isdelete:
if self.compiled.prefetch:
if self.executemany:
self._process_executemany_defaults()
else:
self._process_executesingle_defaults()
processors = compiled._bind_processors
# Convert the dictionary of bind parameter values
# into a dict or list to be sent to the DBAPI's
# execute() or executemany() method.
parameters = []
if dialect.positional:
for compiled_params in self.compiled_parameters:
param = []
for key in self.compiled.positiontup:
if key in processors:
param.append(processors[key](compiled_params[key]))
else:
param.append(compiled_params[key])
parameters.append(dialect.execute_sequence_format(param))
else:
encode = not dialect.supports_unicode_statements
for compiled_params in self.compiled_parameters:
if encode:
param = dict(
(
dialect._encoder(key)[0],
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
else:
param = dict(
(
key,
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
parameters.append(param)
self.parameters = dialect.execute_sequence_format(parameters)
return self
@classmethod
def _init_statement(cls, dialect, connection, dbapi_connection,
statement, parameters):
"""Initialize execution context for a string SQL statement."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
# plain text statement
self.execution_options = connection._execution_options
if not parameters:
if self.dialect.positional:
self.parameters = [dialect.execute_sequence_format()]
else:
self.parameters = [{}]
elif isinstance(parameters[0], dialect.execute_sequence_format):
self.parameters = parameters
elif isinstance(parameters[0], dict):
if dialect.supports_unicode_statements:
self.parameters = parameters
else:
self.parameters = [
dict((dialect._encoder(k)[0], d[k]) for k in d)
for d in parameters
] or [{}]
else:
self.parameters = [dialect.execute_sequence_format(p)
for p in parameters]
self.executemany = len(parameters) > 1
if not dialect.supports_unicode_statements and \
isinstance(statement, util.text_type):
self.unicode_statement = statement
self.statement = dialect._encoder(statement)[0]
else:
self.statement = self.unicode_statement = statement
self.cursor = self.create_cursor()
return self
@classmethod
def _init_default(cls, dialect, connection, dbapi_connection):
"""Initialize execution context for a ColumnDefault construct."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
self.execution_options = connection._execution_options
self.cursor = self.create_cursor()
return self
@util.memoized_property
def engine(self):
return self.root_connection.engine
@util.memoized_property
def postfetch_cols(self):
return self.compiled.postfetch
@util.memoized_property
def prefetch_cols(self):
return self.compiled.prefetch
@util.memoized_property
def returning_cols(self):
self.compiled.returning
@util.memoized_property
def no_parameters(self):
return self.execution_options.get("no_parameters", False)
@util.memoized_property
def should_autocommit(self):
autocommit = self.execution_options.get('autocommit',
not self.compiled and
self.statement and
expression.PARSE_AUTOCOMMIT
or False)
if autocommit is expression.PARSE_AUTOCOMMIT:
return self.should_autocommit_text(self.unicode_statement)
else:
return autocommit
def _execute_scalar(self, stmt, type_):
"""Execute a string statement on the current cursor, returning a
scalar result.
Used to fire off sequences, default phrases, and "select lastrowid"
types of statements individually or in the context of a parent INSERT
or UPDATE statement.
"""
conn = self.root_connection
if isinstance(stmt, util.text_type) and \
not self.dialect.supports_unicode_statements:
stmt = self.dialect._encoder(stmt)[0]
if self.dialect.positional:
default_params = self.dialect.execute_sequence_format()
else:
default_params = {}
conn._cursor_execute(self.cursor, stmt, default_params, context=self)
r = self.cursor.fetchone()[0]
if type_ is not None:
# apply type post processors to the result
proc = type_._cached_result_processor(
self.dialect,
self.cursor.description[0][1]
)
if proc:
return proc(r)
return r
@property
def connection(self):
return self.root_connection._branch()
def should_autocommit_text(self, statement):
return AUTOCOMMIT_REGEXP.match(statement)
def create_cursor(self):
return self._dbapi_connection.cursor()
def pre_exec(self):
pass
def post_exec(self):
pass
def get_result_processor(self, type_, colname, coltype):
"""Return a 'result processor' for a given type as present in
cursor.description.
This has a default implementation that dialects can override
for context-sensitive result type handling.
"""
return type_._cached_result_processor(self.dialect, coltype)
def get_lastrowid(self):
"""return self.cursor.lastrowid, or equivalent, after an INSERT.
This may involve calling special cursor functions,
issuing a new SELECT on the cursor (or a new one),
or returning a stored value that was
calculated within post_exec().
This function will only be called for dialects
which support "implicit" primary key generation,
keep preexecute_autoincrement_sequences set to False,
and when no explicit id value was bound to the
statement.
The function is called once, directly after
post_exec() and before the transaction is committed
or ResultProxy is generated. If the post_exec()
method assigns a value to `self._lastrowid`, the
value is used in place of calling get_lastrowid().
Note that this method is *not* equivalent to the
``lastrowid`` method on ``ResultProxy``, which is a
direct proxy to the DBAPI ``lastrowid`` accessor
in all cases.
"""
return self.cursor.lastrowid
def handle_dbapi_exception(self, e):
pass
def get_result_proxy(self):
return result.ResultProxy(self)
@property
def rowcount(self):
return self.cursor.rowcount
def supports_sane_rowcount(self):
return self.dialect.supports_sane_rowcount
def supports_sane_multi_rowcount(self):
return self.dialect.supports_sane_multi_rowcount
def _setup_crud_result_proxy(self):
if self.isinsert and \
not self.executemany:
if not self._is_implicit_returning and \
not self.compiled.inline and \
self.dialect.postfetch_lastrowid:
self._setup_ins_pk_from_lastrowid()
elif not self._is_implicit_returning:
self._setup_ins_pk_from_empty()
result = self.get_result_proxy()
if self.isinsert:
if self._is_implicit_returning:
row = result.fetchone()
self.returned_defaults = row
self._setup_ins_pk_from_implicit_returning(row)
result._soft_close(_autoclose_connection=False)
result._metadata = None
elif not self._is_explicit_returning:
result._soft_close(_autoclose_connection=False)
result._metadata = None
elif self.isupdate and self._is_implicit_returning:
row = result.fetchone()
self.returned_defaults = row
result._soft_close(_autoclose_connection=False)
result._metadata = None
elif result._metadata is None:
# no results, get rowcount
# (which requires open cursor on some drivers
# such as kintersbasdb, mxodbc)
result.rowcount
result._soft_close(_autoclose_connection=False)
return result
def _setup_ins_pk_from_lastrowid(self):
key_getter = self.compiled._key_getters_for_crud_column[2]
table = self.compiled.statement.table
compiled_params = self.compiled_parameters[0]
lastrowid = self.get_lastrowid()
if lastrowid is not None:
autoinc_col = table._autoincrement_column
if autoinc_col is not None:
# apply type post processors to the lastrowid
proc = autoinc_col.type._cached_result_processor(
self.dialect, None)
if proc is not None:
lastrowid = proc(lastrowid)
self.inserted_primary_key = [
lastrowid if c is autoinc_col else
compiled_params.get(key_getter(c), None)
for c in table.primary_key
]
else:
# don't have a usable lastrowid, so
# do the same as _setup_ins_pk_from_empty
self.inserted_primary_key = [
compiled_params.get(key_getter(c), None)
for c in table.primary_key
]
def _setup_ins_pk_from_empty(self):
key_getter = self.compiled._key_getters_for_crud_column[2]
table = self.compiled.statement.table
compiled_params = self.compiled_parameters[0]
self.inserted_primary_key = [
compiled_params.get(key_getter(c), None)
for c in table.primary_key
]
def _setup_ins_pk_from_implicit_returning(self, row):
key_getter = self.compiled._key_getters_for_crud_column[2]
table = self.compiled.statement.table
compiled_params = self.compiled_parameters[0]
self.inserted_primary_key = [
row[col] if value is None else value
for col, value in [
(col, compiled_params.get(key_getter(col), None))
for col in table.primary_key
]
]
def lastrow_has_defaults(self):
return (self.isinsert or self.isupdate) and \
bool(self.compiled.postfetch)
def set_input_sizes(self, translate=None, exclude_types=None):
"""Given a cursor and ClauseParameters, call the appropriate
style of ``setinputsizes()`` on the cursor, using DB-API types
from the bind parameter's ``TypeEngine`` objects.
This method only called by those dialects which require it,
currently cx_oracle.
"""
if not hasattr(self.compiled, 'bind_names'):
return
types = dict(
(self.compiled.bind_names[bindparam], bindparam.type)
for bindparam in self.compiled.bind_names)
if self.dialect.positional:
inputsizes = []
for key in self.compiled.positiontup:
typeengine = types[key]
dbtype = typeengine.dialect_impl(self.dialect).\
get_dbapi_type(self.dialect.dbapi)
if dbtype is not None and \
(not exclude_types or dbtype not in exclude_types):
inputsizes.append(dbtype)
try:
self.cursor.setinputsizes(*inputsizes)
except Exception as e:
self.root_connection._handle_dbapi_exception(
e, None, None, None, self)
else:
inputsizes = {}
for key in self.compiled.bind_names.values():
typeengine = types[key]
dbtype = typeengine.dialect_impl(self.dialect).\
get_dbapi_type(self.dialect.dbapi)
if dbtype is not None and \
(not exclude_types or dbtype not in exclude_types):
if translate:
key = translate.get(key, key)
if not self.dialect.supports_unicode_binds:
key = self.dialect._encoder(key)[0]
inputsizes[key] = dbtype
try:
self.cursor.setinputsizes(**inputsizes)
except Exception as e:
self.root_connection._handle_dbapi_exception(
e, None, None, None, self)
def _exec_default(self, default, type_):
if default.is_sequence:
return self.fire_sequence(default, type_)
elif default.is_callable:
return default.arg(self)
elif default.is_clause_element:
# TODO: expensive branching here should be
# pulled into _exec_scalar()
conn = self.connection
c = expression.select([default.arg]).compile(bind=conn)
return conn._execute_compiled(c, (), {}).scalar()
else:
return default.arg
def get_insert_default(self, column):
if column.default is None:
return None
else:
return self._exec_default(column.default, column.type)
def get_update_default(self, column):
if column.onupdate is None:
return None
else:
return self._exec_default(column.onupdate, column.type)
def _process_executemany_defaults(self):
key_getter = self.compiled._key_getters_for_crud_column[2]
prefetch = self.compiled.prefetch
scalar_defaults = {}
# pre-determine scalar Python-side defaults
# to avoid many calls of get_insert_default()/
# get_update_default()
for c in prefetch:
if self.isinsert and c.default and c.default.is_scalar:
scalar_defaults[c] = c.default.arg
elif self.isupdate and c.onupdate and c.onupdate.is_scalar:
scalar_defaults[c] = c.onupdate.arg
for param in self.compiled_parameters:
self.current_parameters = param
for c in prefetch:
if c in scalar_defaults:
val = scalar_defaults[c]
elif self.isinsert:
val = self.get_insert_default(c)
else:
val = self.get_update_default(c)
if val is not None:
param[key_getter(c)] = val
del self.current_parameters
def _process_executesingle_defaults(self):
key_getter = self.compiled._key_getters_for_crud_column[2]
prefetch = self.compiled.prefetch
self.current_parameters = compiled_parameters = \
self.compiled_parameters[0]
for c in prefetch:
if self.isinsert:
if c.default and \
not c.default.is_sequence and c.default.is_scalar:
val = c.default.arg
else:
val = self.get_insert_default(c)
else:
val = self.get_update_default(c)
if val is not None:
compiled_parameters[key_getter(c)] = val
del self.current_parameters
DefaultDialect.execution_ctx_cls = DefaultExecutionContext
|
jerryjiahaha/rts2 | refs/heads/master | scripts/rts2saf/rts2saf/log.py | 5 | #!/usr/bin/python
# (C) 2013, Markus Wildi, markus.wildi@bluewin.ch
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Or visit http://www.gnu.org/licenses/gpl.html.
#
__author__ = 'markus.wildi@bluewin.ch'
import logging
import sys
import os
class Logger(object):
"""Define the logger for rts2saf
:var debug: enable more debug output with --debug and --level
:var logformat: format string
:var args: command line arguments or their defaults
"""
def __init__(self,
debug=False,
logformat='%(asctime)s:%(name)s:%(levelname)s:%(message)s',
args=None):
self.debug=debug
self.logformat=logformat
self.args=args
logFile = os.path.join(self.args.toPath, self.args.logfile)
ok= True
if os.access(logFile, os.W_OK):
logging.basicConfig(filename=logFile, level=self.args.level.upper(), format=self.logformat)
else:
if not os.path.isdir(self.args.toPath):
os.mkdir(self.args.toPath)
if os.access(self.args.toPath, os.W_OK):
try:
logging.basicConfig(filename=logFile, level=self.args.level.upper(), format=self.logformat)
except Exception, e:
print 'Logger: can not log to file: {}, trying to log to console, error: {}'.format(logFile, e)
# ugly
args.level= 'DEBUG'
else:
ok = False
logPath='/tmp/rts2saf_log'
logFile=os.path.join(logPath, self.args.logfile)
if not os.path.isdir(logPath):
os.mkdir(logPath)
try:
logging.basicConfig(filename=logFile, level=self.args.level.upper(), format=self.logformat)
except Exception, e:
print 'Logger: can not log to file: {}, trying to log to console, error: {}'.format(logFile, e)
# ugly
args.level= 'DEBUG'
self.logger = logging.getLogger()
# ToDo: simplify that
if args.level in 'DEBUG':
toconsole=True
else:
toconsole=args.toconsole
if toconsole:
# http://www.mglerner.com/blog/?p=8
soh = logging.StreamHandler(sys.stdout)
soh.setLevel(args.level)
self.logger.addHandler(soh)
if ok:
self.logger.info('logging to: {0} '.format(logFile, self.args.logfile))
else:
self.logger.warn('logging to: {0} instead of {1}'.format(logFile, os.path.join(self.args.toPath, self.args.logfile)))
|
gilbertpilz/solum | refs/heads/camp/item-1 | solum/api/handlers/__init__.py | 12133432 | |
adamtegen/node-gyp | refs/heads/master | legacy/tools/gyp/setup.py | 282 | #!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from distutils.core import setup
from distutils.command.install import install
from distutils.command.install_lib import install_lib
from distutils.command.install_scripts import install_scripts
setup(
name='gyp',
version='0.1',
description='Generate Your Projects',
author='Chromium Authors',
author_email='chromium-dev@googlegroups.com',
url='http://code.google.com/p/gyp',
package_dir = {'': 'pylib'},
packages=['gyp', 'gyp.generator'],
scripts = ['gyp'],
cmdclass = {'install': install,
'install_lib': install_lib,
'install_scripts': install_scripts},
)
|
domesticduck/MenuConciergeServer | refs/heads/master | vendor/bundle/ruby/2.0.0/gems/libv8-3.16.14.3/vendor/gyp/setup.py | 282 | #!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from distutils.core import setup
from distutils.command.install import install
from distutils.command.install_lib import install_lib
from distutils.command.install_scripts import install_scripts
setup(
name='gyp',
version='0.1',
description='Generate Your Projects',
author='Chromium Authors',
author_email='chromium-dev@googlegroups.com',
url='http://code.google.com/p/gyp',
package_dir = {'': 'pylib'},
packages=['gyp', 'gyp.generator'],
scripts = ['gyp'],
cmdclass = {'install': install,
'install_lib': install_lib,
'install_scripts': install_scripts},
)
|
s-knibbs/py-web-player | refs/heads/master | pywebplayer/__init__.py | 12133432 | |
fe11x/pythondotorg | refs/heads/master | peps/management/__init__.py | 12133432 | |
havid0707/flasky | refs/heads/master | tests/__init__.py | 12133432 | |
vladmm/intellij-community | refs/heads/master | python/lib/Lib/site-packages/django/contrib/localflavor/ca/__init__.py | 12133432 | |
rishabh96b/Simple-Coding-Solutions | refs/heads/master | reverseString.py | 1 | #Python program to reverse a string
#taking input from user
string1 = list(input()) #converting the string to a list of characters.
#initializing the starting index
i=0
#initializing end index
j= len(string1)-1
while(i<j):
string1[i],string1[j] = string1[j],string1[i] #python way of swapping 2 elements
i+=1
j-=1
#printing the string again by converting list into string
print(''.join(string1))
|
guoxiaolongzte/spark | refs/heads/master | examples/src/main/python/ml/pca_example.py | 123 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 __future__ import print_function
# $example on$
from pyspark.ml.feature import PCA
from pyspark.ml.linalg import Vectors
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("PCAExample")\
.getOrCreate()
# $example on$
data = [(Vectors.sparse(5, [(1, 1.0), (3, 7.0)]),),
(Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),),
(Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)]
df = spark.createDataFrame(data, ["features"])
pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
model = pca.fit(df)
result = model.transform(df).select("pcaFeatures")
result.show(truncate=False)
# $example off$
spark.stop()
|
openstack/neutron | refs/heads/master | neutron/agent/linux/pd.py | 2 | # Copyright 2015 Cisco Systems
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import signal
import eventlet
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutron_lib import constants as n_const
from neutron_lib.utils import runtime
from oslo_log import log as logging
from oslo_utils import netutils
from stevedore import driver
from neutron.agent.linux import ip_lib
from neutron.common import utils
LOG = logging.getLogger(__name__)
class PrefixDelegation(object):
def __init__(self, context, pmon, intf_driver, notifier, pd_update_cb,
agent_conf):
self.context = context
self.pmon = pmon
self.intf_driver = intf_driver
self.notifier = notifier
self.routers = {}
self.pd_update_cb = pd_update_cb
self.agent_conf = agent_conf
self.pd_dhcp_driver = driver.DriverManager(
namespace='neutron.agent.linux.pd_drivers',
name=agent_conf.prefix_delegation_driver,
).driver
registry.subscribe(add_router,
resources.ROUTER,
events.BEFORE_CREATE)
registry.subscribe(update_router,
resources.ROUTER,
events.AFTER_UPDATE)
registry.subscribe(remove_router,
resources.ROUTER,
events.AFTER_DELETE)
self._get_sync_data()
def _is_pd_primary_router(self, router):
return router['primary']
@runtime.synchronized("l3-agent-pd")
def enable_subnet(self, router_id, subnet_id, prefix, ri_ifname, mac):
router = self.routers.get(router_id)
if router is None:
return
pd_info = router['subnets'].get(subnet_id)
if not pd_info:
pd_info = PDInfo(ri_ifname=ri_ifname, mac=mac)
router['subnets'][subnet_id] = pd_info
pd_info.bind_lla = self._get_lla(mac)
if pd_info.sync:
pd_info.mac = mac
pd_info.old_prefix = prefix
elif self._is_pd_primary_router(router):
self._add_lla(router, pd_info.get_bind_lla_with_mask())
def _delete_pd(self, router, pd_info):
if not self._is_pd_primary_router(router):
return
self._delete_lla(router, pd_info.get_bind_lla_with_mask())
if pd_info.client_started:
pd_info.driver.disable(self.pmon, router['ns_name'])
@runtime.synchronized("l3-agent-pd")
def disable_subnet(self, router_id, subnet_id):
prefix_update = {}
router = self.routers.get(router_id)
if not router:
return
pd_info = router['subnets'].get(subnet_id)
if not pd_info:
return
self._delete_pd(router, pd_info)
if self._is_pd_primary_router(router):
prefix_update[subnet_id] = n_const.PROVISIONAL_IPV6_PD_PREFIX
LOG.debug("Update server with prefixes: %s", prefix_update)
self.notifier(self.context, prefix_update)
del router['subnets'][subnet_id]
@runtime.synchronized("l3-agent-pd")
def update_subnet(self, router_id, subnet_id, prefix):
router = self.routers.get(router_id)
if router is not None:
pd_info = router['subnets'].get(subnet_id)
if pd_info and pd_info.old_prefix != prefix:
old_prefix = pd_info.old_prefix
pd_info.old_prefix = prefix
pd_info.prefix = prefix
return old_prefix
@runtime.synchronized("l3-agent-pd")
def add_gw_interface(self, router_id, gw_ifname):
router = self.routers.get(router_id)
if not router:
return
router['gw_interface'] = gw_ifname
if not self._is_pd_primary_router(router):
return
prefix_update = {}
for pd_info in router['subnets'].values():
# gateway is added after internal router ports.
# If a PD is being synced, and if the prefix is available,
# send update if prefix out of sync; If not available,
# start the PD client
bind_lla_with_mask = pd_info.get_bind_lla_with_mask()
if pd_info.sync:
pd_info.sync = False
if pd_info.client_started:
if pd_info.prefix != pd_info.old_prefix:
prefix_update['subnet_id'] = pd_info.prefix
else:
self._delete_lla(router, bind_lla_with_mask)
self._add_lla(router, bind_lla_with_mask)
else:
self._add_lla(router, bind_lla_with_mask)
if prefix_update:
LOG.debug("Update server with prefixes: %s", prefix_update)
self.notifier(self.context, prefix_update)
def delete_router_pd(self, router):
if not self._is_pd_primary_router(router):
return
prefix_update = {}
for subnet_id, pd_info in router['subnets'].items():
self._delete_lla(router, pd_info.get_bind_lla_with_mask())
if pd_info.client_started:
pd_info.driver.disable(self.pmon, router['ns_name'])
pd_info.prefix = None
pd_info.client_started = False
prefix = n_const.PROVISIONAL_IPV6_PD_PREFIX
prefix_update[subnet_id] = prefix
if prefix_update:
LOG.debug("Update server with prefixes: %s", prefix_update)
self.notifier(self.context, prefix_update)
@runtime.synchronized("l3-agent-pd")
def remove_gw_interface(self, router_id):
router = self.routers.get(router_id)
if router is not None:
router['gw_interface'] = None
self.delete_router_pd(router)
@runtime.synchronized("l3-agent-pd")
def get_preserve_ips(self, router_id):
preserve_ips = []
router = self.routers.get(router_id)
if router is not None:
for pd_info in router['subnets'].values():
preserve_ips.append(pd_info.get_bind_lla_with_mask())
return preserve_ips
@runtime.synchronized("l3-agent-pd")
def sync_router(self, router_id):
router = self.routers.get(router_id)
if router is not None and router['gw_interface'] is None:
self.delete_router_pd(router)
@runtime.synchronized("l3-agent-pd")
def remove_stale_ri_ifname(self, router_id, stale_ifname):
router = self.routers.get(router_id)
if router is not None:
subnet_to_delete = None
for subnet_id, pd_info in router['subnets'].items():
if pd_info.ri_ifname == stale_ifname:
self._delete_pd(router, pd_info)
subnet_to_delete = subnet_id
break
if subnet_to_delete:
del router['subnets'][subnet_to_delete]
@staticmethod
def _get_lla(mac):
lla = netutils.get_ipv6_addr_by_EUI64(n_const.IPv6_LLA_PREFIX,
mac)
return lla
def _get_llas(self, gw_ifname, ns_name):
try:
return self.intf_driver.get_ipv6_llas(gw_ifname, ns_name)
except RuntimeError:
# The error message was printed as part of the driver call
# This could happen if the gw_ifname was removed
# simply return and exit the thread
return
def _add_lla(self, router, lla_with_mask):
if router['gw_interface']:
try:
self.intf_driver.add_ipv6_addr(router['gw_interface'],
lla_with_mask,
router['ns_name'],
'link')
# There is a delay before the LLA becomes active.
# This is because the kernel runs DAD to make sure LLA
# uniqueness
# Spawn a thread to wait for the interface to be ready
self._spawn_lla_thread(router['gw_interface'],
router['ns_name'],
lla_with_mask)
except ip_lib.IpAddressAlreadyExists:
pass
def _spawn_lla_thread(self, gw_ifname, ns_name, lla_with_mask):
eventlet.spawn_n(self._ensure_lla_task,
gw_ifname,
ns_name,
lla_with_mask)
def _delete_lla(self, router, lla_with_mask):
if lla_with_mask and router['gw_interface']:
try:
self.intf_driver.delete_ipv6_addr(router['gw_interface'],
lla_with_mask,
router['ns_name'])
except RuntimeError:
# Ignore error if the lla doesn't exist
pass
def _ensure_lla_task(self, gw_ifname, ns_name, lla_with_mask):
# It would be insane for taking so long unless DAD test failed
# In that case, the subnet would never be assigned a prefix.
utils.wait_until_true(functools.partial(self._lla_available,
gw_ifname,
ns_name,
lla_with_mask),
timeout=n_const.LLA_TASK_TIMEOUT,
sleep=2)
def _lla_available(self, gw_ifname, ns_name, lla_with_mask):
llas = self._get_llas(gw_ifname, ns_name)
if self._is_lla_active(lla_with_mask, llas):
LOG.debug("LLA %s is active now", lla_with_mask)
self.pd_update_cb()
return True
@staticmethod
def _is_lla_active(lla_with_mask, llas):
for lla in llas:
if lla_with_mask == lla['cidr']:
return not lla['tentative']
return False
@runtime.synchronized("l3-agent-pd")
def process_ha_state(self, router_id, primary):
router = self.routers.get(router_id)
if router is None or router['primary'] == primary:
return
router['primary'] = primary
if primary:
for pd_info in router['subnets'].values():
bind_lla_with_mask = pd_info.get_bind_lla_with_mask()
self._add_lla(router, bind_lla_with_mask)
else:
for pd_info in router['subnets'].values():
self._delete_lla(router, pd_info.get_bind_lla_with_mask())
if pd_info.client_started:
pd_info.driver.disable(self.pmon,
router['ns_name'],
switch_over=True)
pd_info.client_started = False
@runtime.synchronized("l3-agent-pd")
def process_prefix_update(self):
LOG.debug("Processing IPv6 PD Prefix Update")
prefix_update = {}
for router_id, router in self.routers.items():
if not (self._is_pd_primary_router(router) and
router['gw_interface']):
continue
llas = None
for subnet_id, pd_info in router['subnets'].items():
if pd_info.client_started:
prefix = pd_info.driver.get_prefix()
if prefix != pd_info.prefix:
pd_info.prefix = prefix
prefix_update[subnet_id] = prefix
else:
if not llas:
llas = self._get_llas(router['gw_interface'],
router['ns_name'])
if self._is_lla_active(pd_info.get_bind_lla_with_mask(),
llas):
if not pd_info.driver:
pd_info.driver = self.pd_dhcp_driver(
router_id, subnet_id, pd_info.ri_ifname)
prefix = None
if (pd_info.prefix !=
n_const.PROVISIONAL_IPV6_PD_PREFIX):
prefix = pd_info.prefix
pd_info.driver.enable(self.pmon, router['ns_name'],
router['gw_interface'],
pd_info.bind_lla,
prefix)
pd_info.client_started = True
if prefix_update:
LOG.debug("Update server with prefixes: %s", prefix_update)
self.notifier(self.context, prefix_update)
def after_start(self):
LOG.debug('SIGUSR1 signal handler set')
signal.signal(signal.SIGUSR1, self._handle_sigusr1)
def _handle_sigusr1(self, signum, frame):
"""Update PD on receiving SIGUSR1.
The external DHCPv6 client uses SIGUSR1 to notify agent
of prefix changes.
"""
self.pd_update_cb()
def _get_sync_data(self):
sync_data = self.pd_dhcp_driver.get_sync_data()
for pd_info in sync_data:
router_id = pd_info.router_id
if not self.routers.get(router_id):
self.routers[router_id] = {'primary': True,
'gw_interface': None,
'ns_name': None,
'subnets': {}}
new_pd_info = PDInfo(pd_info=pd_info)
subnets = self.routers[router_id]['subnets']
subnets[pd_info.subnet_id] = new_pd_info
@runtime.synchronized("l3-agent-pd")
def remove_router(resource, event, l3_agent, **kwargs):
router_id = kwargs['router'].router_id
router = l3_agent.pd.routers.get(router_id)
l3_agent.pd.delete_router_pd(router)
del l3_agent.pd.routers[router_id]['subnets']
del l3_agent.pd.routers[router_id]
def get_router_entry(ns_name, primary):
return {'primary': primary,
'gw_interface': None,
'ns_name': ns_name,
'subnets': {}}
@runtime.synchronized("l3-agent-pd")
def add_router(resource, event, l3_agent, **kwargs):
added_router = kwargs['router']
router = l3_agent.pd.routers.get(added_router.router_id)
gw_ns_name = added_router.get_gw_ns_name()
primary = added_router.is_router_primary()
if not router:
l3_agent.pd.routers[added_router.router_id] = (
get_router_entry(gw_ns_name, primary))
else:
# This will happen during l3 agent restart
router['ns_name'] = gw_ns_name
router['primary'] = primary
@runtime.synchronized("l3-agent-pd")
def update_router(resource, event, l3_agent, **kwargs):
updated_router = kwargs['router']
router = l3_agent.pd.routers.get(updated_router.router_id)
if not router:
LOG.exception("Router to be updated is not in internal routers "
"list: %s", updated_router.router_id)
else:
router['ns_name'] = updated_router.get_gw_ns_name()
class PDInfo(object):
"""A class to simplify storing and passing of information relevant to
Prefix Delegation operations for a given subnet.
"""
def __init__(self, pd_info=None, ri_ifname=None, mac=None):
if pd_info is None:
self.prefix = n_const.PROVISIONAL_IPV6_PD_PREFIX
self.old_prefix = n_const.PROVISIONAL_IPV6_PD_PREFIX
self.ri_ifname = ri_ifname
self.mac = mac
self.bind_lla = None
self.sync = False
self.driver = None
self.client_started = False
else:
self.prefix = pd_info.prefix
self.old_prefix = None
self.ri_ifname = pd_info.ri_ifname
self.mac = None
self.bind_lla = None
self.sync = True
self.driver = pd_info.driver
self.client_started = pd_info.client_started
def get_bind_lla_with_mask(self):
bind_lla_with_mask = '%s/64' % self.bind_lla
return bind_lla_with_mask
|
relrix/hydropower | refs/heads/master | test_black_screen.py | 1 | """hydropower.
Copyright (C) 2016 - Shishir Pokharel
shishir.pokharel@gmail.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from headwater import powerhouse
from threading import Thread
import time
import random
hydroObj = powerhouse.powerhouse()
hydroObj.start()
|
vsajip/django | refs/heads/django3 | tests/regressiontests/model_permalink/__init__.py | 12133432 | |
ritzk/ansible-modules-core | refs/heads/devel | utilities/logic/__init__.py | 12133432 | |
petewarden/tensorflow | refs/heads/master | third_party/__init__.py | 12133432 | |
weijia/djangoautoconf | refs/heads/master | djangoautoconf/auto_conf_admin_tools/admin_features/__init__.py | 12133432 | |
DarkFenX/Pyfa | refs/heads/master | gui/fitCommands/gui/commandFit/__init__.py | 12133432 | |
spreeker/democracygame | refs/heads/master | external_apps/south/tests/circular_a/migrations/__init__.py | 12133432 | |
b-cube/thredds_catalog_crawler | refs/heads/master | tests/__init__.py | 12133432 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.